code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _hook_syscall(self, uc, data):
"""
Unicorn hook that transfers control to Manticore so it can execute the syscall
"""
logger.debug(f"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall")
self.sync_unicorn_to_manticore()
from ..nativ... | Unicorn hook that transfers control to Manticore so it can execute the syscall | Below is the the instruction that describes the task:
### Input:
Unicorn hook that transfers control to Manticore so it can execute the syscall
### Response:
def _hook_syscall(self, uc, data):
"""
Unicorn hook that transfers control to Manticore so it can execute the syscall
"""
log... |
def clean_tempfiles():
'''Clean up temp files'''
for fn in TEMP_FILES:
if os.path.exists(fn):
os.unlink(fn) | Clean up temp files | Below is the the instruction that describes the task:
### Input:
Clean up temp files
### Response:
def clean_tempfiles():
'''Clean up temp files'''
for fn in TEMP_FILES:
if os.path.exists(fn):
os.unlink(fn) |
def save(self, filething=None, v1=1, v2_version=4, v23_sep='/',
padding=None):
"""save(filething=None, v1=1, v2_version=4, v23_sep='/', padding=None)
Save changes to a file.
See :meth:`mutagen.id3.ID3.save` for more info.
"""
if v2_version == 3:
# EasyI... | save(filething=None, v1=1, v2_version=4, v23_sep='/', padding=None)
Save changes to a file.
See :meth:`mutagen.id3.ID3.save` for more info. | Below is the the instruction that describes the task:
### Input:
save(filething=None, v1=1, v2_version=4, v23_sep='/', padding=None)
Save changes to a file.
See :meth:`mutagen.id3.ID3.save` for more info.
### Response:
def save(self, filething=None, v1=1, v2_version=4, v23_sep='/',
pa... |
def close(self):
"""
Closes the lvm and vg_t handle. Usually you would never need to use this method
unless you are doing operations using the ctypes function wrappers in conversion.py
*Raises:*
* HandleError
"""
if self.handle:
cl = lvm_vg_clo... | Closes the lvm and vg_t handle. Usually you would never need to use this method
unless you are doing operations using the ctypes function wrappers in conversion.py
*Raises:*
* HandleError | Below is the the instruction that describes the task:
### Input:
Closes the lvm and vg_t handle. Usually you would never need to use this method
unless you are doing operations using the ctypes function wrappers in conversion.py
*Raises:*
* HandleError
### Response:
def close(self):... |
def get_data_dir():
"""
Find out our installation prefix and data directory. These can be in
different places depending on how ansible-cmdb was installed.
"""
data_dir_paths = [
os.path.join(os.path.dirname(ansiblecmdb.__file__), 'data'),
os.path.join(os.path.dirname(sys.argv[0]), '.... | Find out our installation prefix and data directory. These can be in
different places depending on how ansible-cmdb was installed. | Below is the the instruction that describes the task:
### Input:
Find out our installation prefix and data directory. These can be in
different places depending on how ansible-cmdb was installed.
### Response:
def get_data_dir():
"""
Find out our installation prefix and data directory. These can be in
... |
def list_objects(service_instance, vim_object, properties=None):
'''
Returns a simple list of objects from a given service instance.
service_instance
The Service Instance for which to obtain a list of objects.
object_type
The type of content for which to obtain information.
proper... | Returns a simple list of objects from a given service instance.
service_instance
The Service Instance for which to obtain a list of objects.
object_type
The type of content for which to obtain information.
properties
An optional list of object properties used to return reference r... | Below is the the instruction that describes the task:
### Input:
Returns a simple list of objects from a given service instance.
service_instance
The Service Instance for which to obtain a list of objects.
object_type
The type of content for which to obtain information.
properties
... |
def get_marker(marker_type, enum_ammo=False):
'''
Returns a marker function of the requested marker_type
>>> marker = get_marker('uniq')(__test_missile)
>>> type(marker)
<type 'str'>
>>> len(marker)
32
>>> get_marker('uri')(__test_missile)
'_example_search_hello_help_us'
>>> m... | Returns a marker function of the requested marker_type
>>> marker = get_marker('uniq')(__test_missile)
>>> type(marker)
<type 'str'>
>>> len(marker)
32
>>> get_marker('uri')(__test_missile)
'_example_search_hello_help_us'
>>> marker = get_marker('non-existent')(__test_missile)
Tra... | Below is the the instruction that describes the task:
### Input:
Returns a marker function of the requested marker_type
>>> marker = get_marker('uniq')(__test_missile)
>>> type(marker)
<type 'str'>
>>> len(marker)
32
>>> get_marker('uri')(__test_missile)
'_example_search_hello_help_us'... |
def field(self, name):
'''
Get the gdb.Value for the given field within the PyObject, coping with
some python 2 versus python 3 differences.
Various libpython types are defined using the "PyObject_HEAD" and
"PyObject_VAR_HEAD" macros.
In Python 2, this these are defined... | Get the gdb.Value for the given field within the PyObject, coping with
some python 2 versus python 3 differences.
Various libpython types are defined using the "PyObject_HEAD" and
"PyObject_VAR_HEAD" macros.
In Python 2, this these are defined so that "ob_type" and (for a var
o... | Below is the the instruction that describes the task:
### Input:
Get the gdb.Value for the given field within the PyObject, coping with
some python 2 versus python 3 differences.
Various libpython types are defined using the "PyObject_HEAD" and
"PyObject_VAR_HEAD" macros.
In Python... |
def generate_multiline_list(
self,
items, # type: typing.List[typing.Text]
before='', # type: typing.Text
after='', # type: typing.Text
delim=('(', ')'), # type: DelimTuple
compact=True, # type: bool
sep=',', ... | Given a list of items, emits one item per line.
This is convenient for function prototypes and invocations, as well as
for instantiating arrays, sets, and maps in some languages.
TODO(kelkabany): A backend that uses tabs cannot be used with this
if compact is false.
Args:
... | Below is the the instruction that describes the task:
### Input:
Given a list of items, emits one item per line.
This is convenient for function prototypes and invocations, as well as
for instantiating arrays, sets, and maps in some languages.
TODO(kelkabany): A backend that uses tabs cann... |
def continuous_query_exists(database, name, **client_args):
'''
Check if continuous query with given name exists on the database.
database
Name of the database for which the continuous query was
defined.
name
Name of the continuous query to check.
CLI Example:
.. code... | Check if continuous query with given name exists on the database.
database
Name of the database for which the continuous query was
defined.
name
Name of the continuous query to check.
CLI Example:
.. code-block:: bash
salt '*' influxdb.continuous_query_exists metrics... | Below is the the instruction that describes the task:
### Input:
Check if continuous query with given name exists on the database.
database
Name of the database for which the continuous query was
defined.
name
Name of the continuous query to check.
CLI Example:
.. code-bl... |
def date(name=None):
"""
Creates the grammar for a Date (D) field, accepting only numbers in a
certain pattern.
:param name: name for the field
:return: grammar for the date field
"""
if name is None:
name = 'Date Field'
# Basic field
# This regex allows values from 000001... | Creates the grammar for a Date (D) field, accepting only numbers in a
certain pattern.
:param name: name for the field
:return: grammar for the date field | Below is the the instruction that describes the task:
### Input:
Creates the grammar for a Date (D) field, accepting only numbers in a
certain pattern.
:param name: name for the field
:return: grammar for the date field
### Response:
def date(name=None):
"""
Creates the grammar for a Date (D) ... |
def number_of_states(dtrajs):
r"""
Determine the number of states from a set of discrete trajectories
Parameters
----------
dtrajs : list of int-arrays
discrete trajectories
"""
# determine number of states n
nmax = 0
for dtraj in dtrajs:
nmax = max(nmax, np.max(dtra... | r"""
Determine the number of states from a set of discrete trajectories
Parameters
----------
dtrajs : list of int-arrays
discrete trajectories | Below is the the instruction that describes the task:
### Input:
r"""
Determine the number of states from a set of discrete trajectories
Parameters
----------
dtrajs : list of int-arrays
discrete trajectories
### Response:
def number_of_states(dtrajs):
r"""
Determine the number of ... |
def black(m):
"""Return a function that maps all values from [0.0,m] to 0, and maps
the range [m,1.0] into [0.0, 1.0] linearly.
"""
m = float(m)
def f(x):
if x <= m:
return 0.0
return (x - m) / (1.0 - m)
return f | Return a function that maps all values from [0.0,m] to 0, and maps
the range [m,1.0] into [0.0, 1.0] linearly. | Below is the the instruction that describes the task:
### Input:
Return a function that maps all values from [0.0,m] to 0, and maps
the range [m,1.0] into [0.0, 1.0] linearly.
### Response:
def black(m):
"""Return a function that maps all values from [0.0,m] to 0, and maps
the range [m,1.0] into [0.0, ... |
def mpl_weight2qt(weight):
"""Convert a weight from matplotlib definition to a Qt weight
Parameters
----------
weight: int or string
Either an integer between 1 and 1000 or a string out of
:attr:`weights_mpl2qt`
Returns
-------
int
One type of the PyQt5.QtGui.QFont.... | Convert a weight from matplotlib definition to a Qt weight
Parameters
----------
weight: int or string
Either an integer between 1 and 1000 or a string out of
:attr:`weights_mpl2qt`
Returns
-------
int
One type of the PyQt5.QtGui.QFont.Weight | Below is the the instruction that describes the task:
### Input:
Convert a weight from matplotlib definition to a Qt weight
Parameters
----------
weight: int or string
Either an integer between 1 and 1000 or a string out of
:attr:`weights_mpl2qt`
Returns
-------
int
... |
def plaintext(cls):
"""Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_b... | Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object. | Below is the the instruction that describes the task:
### Input:
Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object.
### Respo... |
def add_xref(self, id, xref):
"""
Adds an xref to the xref graph
"""
# note: does not update meta object
if self.xref_graph is None:
self.xref_graph = nx.MultiGraph()
self.xref_graph.add_edge(xref, id) | Adds an xref to the xref graph | Below is the the instruction that describes the task:
### Input:
Adds an xref to the xref graph
### Response:
def add_xref(self, id, xref):
"""
Adds an xref to the xref graph
"""
# note: does not update meta object
if self.xref_graph is None:
self.xref_graph = nx... |
def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order | Below is the the instruction that describes the task:
### Input:
Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
### Response:
def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/... |
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force):
"""
Set or change the configuration lock code.
A lock code may be used to protect the application configuration.
The lock code must be a 32 characters (16 bytes) hex value.
"""
dev = ctx.obj['dev']
def prompt_new_lo... | Set or change the configuration lock code.
A lock code may be used to protect the application configuration.
The lock code must be a 32 characters (16 bytes) hex value. | Below is the the instruction that describes the task:
### Input:
Set or change the configuration lock code.
A lock code may be used to protect the application configuration.
The lock code must be a 32 characters (16 bytes) hex value.
### Response:
def set_lock_code(ctx, lock_code, new_lock_code, clear, ge... |
def sismember(self, name, value):
"""Emulate sismember."""
redis_set = self._get_set(name, 'SISMEMBER')
if not redis_set:
return 0
result = self._encode(value) in redis_set
return 1 if result else 0 | Emulate sismember. | Below is the the instruction that describes the task:
### Input:
Emulate sismember.
### Response:
def sismember(self, name, value):
"""Emulate sismember."""
redis_set = self._get_set(name, 'SISMEMBER')
if not redis_set:
return 0
result = self._encode(value) in redis_set... |
def sina_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
"""Downloads Sina videos by URL.
"""
if 'news.sina.com.cn/zxt' in url:
sina_zxt(url, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs)
return
vid = match1(url, r'vid=(\d+)')
if vid is Non... | Downloads Sina videos by URL. | Below is the the instruction that describes the task:
### Input:
Downloads Sina videos by URL.
### Response:
def sina_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
"""Downloads Sina videos by URL.
"""
if 'news.sina.com.cn/zxt' in url:
sina_zxt(url, output_dir=output_dir,... |
def generate_fft_plan(length, level=None, dtype='float64', forward=True):
"""Build a `REAL8FFTPlan` for a fast Fourier transform.
Parameters
----------
length : `int`
number of samples to plan for in each FFT.
level : `int`, optional
amount of work to do when planning the FFT, defa... | Build a `REAL8FFTPlan` for a fast Fourier transform.
Parameters
----------
length : `int`
number of samples to plan for in each FFT.
level : `int`, optional
amount of work to do when planning the FFT, default set by
`LAL_FFTPLAN_LEVEL` module variable.
dtype : :class:`nump... | Below is the the instruction that describes the task:
### Input:
Build a `REAL8FFTPlan` for a fast Fourier transform.
Parameters
----------
length : `int`
number of samples to plan for in each FFT.
level : `int`, optional
amount of work to do when planning the FFT, default set by
... |
def is_valid(self, field_name: str, value, kg: dict) -> Optional[dict]:
"""
Check if this value is valid for the given name property according to input knowledge graph and ontology.
If is valid, then return a dict with key @id or @value for ObjectProperty or DatatypeProperty.
No schema c... | Check if this value is valid for the given name property according to input knowledge graph and ontology.
If is valid, then return a dict with key @id or @value for ObjectProperty or DatatypeProperty.
No schema checked by this function.
:param field_name: name of the property, if prefix is omit... | Below is the the instruction that describes the task:
### Input:
Check if this value is valid for the given name property according to input knowledge graph and ontology.
If is valid, then return a dict with key @id or @value for ObjectProperty or DatatypeProperty.
No schema checked by this function... |
def _plot_graph(G, vertex_color, vertex_size, highlight,
edges, edge_color, edge_width,
indices, colorbar, limits, ax, title, backend):
r"""Plot a graph with signals as color or vertex size.
Parameters
----------
vertex_color : array_like or color
Signal to plot ... | r"""Plot a graph with signals as color or vertex size.
Parameters
----------
vertex_color : array_like or color
Signal to plot as vertex color (length is the number of vertices).
If None, vertex color is set to `graph.plotting['vertex_color']`.
Alternatively, a color can be set in a... | Below is the the instruction that describes the task:
### Input:
r"""Plot a graph with signals as color or vertex size.
Parameters
----------
vertex_color : array_like or color
Signal to plot as vertex color (length is the number of vertices).
If None, vertex color is set to `graph.plot... |
def ignite(self, args=None):
"""
* Make the virtualenv
* Install dependencies into that virtualenv
* Start the program!
"""
if args is None:
args = sys.argv[1:]
if os.environ.get("MANAGED_VIRTUALENV", None) != "1":
made = self.make_virtual... | * Make the virtualenv
* Install dependencies into that virtualenv
* Start the program! | Below is the the instruction that describes the task:
### Input:
* Make the virtualenv
* Install dependencies into that virtualenv
* Start the program!
### Response:
def ignite(self, args=None):
"""
* Make the virtualenv
* Install dependencies into that virtualenv
* ... |
def get_hash(self, place):
"""
Return the Geohash of *place*.
If it's not present in the collection, ``None`` will be returned
instead.
"""
pickled_place = self._pickle(place)
try:
return self.redis.geohash(self.key, pickled_place)[0]
except (A... | Return the Geohash of *place*.
If it's not present in the collection, ``None`` will be returned
instead. | Below is the the instruction that describes the task:
### Input:
Return the Geohash of *place*.
If it's not present in the collection, ``None`` will be returned
instead.
### Response:
def get_hash(self, place):
"""
Return the Geohash of *place*.
If it's not present in the co... |
def warnpy3k(message, category=None, stacklevel=1):
"""Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option.
"""
if sys.py3kwarning:
if category is None:
category = DeprecationWarning
warn(message, categ... | Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option. | Below is the the instruction that describes the task:
### Input:
Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option.
### Response:
def warnpy3k(message, category=None, stacklevel=1):
"""Issue a deprecation warning for Python 3.x rel... |
def compute_ratings(data=None):
""" Returns the tuples of (model_id, rating, sigma)
N.B. that `model_id` here is NOT the model number in the run
'data' is tuples of (winner, loser) model_ids (not model numbers)
"""
if data is None:
with sqlite3.connect("ratings.db") as db:
data ... | Returns the tuples of (model_id, rating, sigma)
N.B. that `model_id` here is NOT the model number in the run
'data' is tuples of (winner, loser) model_ids (not model numbers) | Below is the the instruction that describes the task:
### Input:
Returns the tuples of (model_id, rating, sigma)
N.B. that `model_id` here is NOT the model number in the run
'data' is tuples of (winner, loser) model_ids (not model numbers)
### Response:
def compute_ratings(data=None):
""" Returns the ... |
def send_config_set(
self,
config_commands=None,
exit_config_mode=False,
delay_factor=1,
max_loops=150,
strip_prompt=False,
strip_command=False,
config_mode_command=None,
):
"""Remain in configuration mode."""
return super(VyOSSSH, self... | Remain in configuration mode. | Below is the the instruction that describes the task:
### Input:
Remain in configuration mode.
### Response:
def send_config_set(
self,
config_commands=None,
exit_config_mode=False,
delay_factor=1,
max_loops=150,
strip_prompt=False,
strip_command=False,
... |
def pipeline_delete(id, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Delete Ingest pipeline. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_delete mypipeline
'''
es = _get_instance(hosts, profile)
try... | .. versionadded:: 2017.7.0
Delete Ingest pipeline. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_delete mypipeline | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2017.7.0
Delete Ingest pipeline. Available since Elasticsearch 5.0.
id
Pipeline id
CLI example::
salt myminion elasticsearch.pipeline_delete mypipeline
### Response:
def pipeline_delete(id, hosts=None... |
def bulk_shear(pressure, u, v, heights=None, bottom=None, depth=None):
r"""Calculate bulk shear through a layer.
Layer top and bottom specified in meters or pressure.
Parameters
----------
pressure : `pint.Quantity`
Atmospheric pressure profile
u : `pint.Quantity`
U-component o... | r"""Calculate bulk shear through a layer.
Layer top and bottom specified in meters or pressure.
Parameters
----------
pressure : `pint.Quantity`
Atmospheric pressure profile
u : `pint.Quantity`
U-component of wind.
v : `pint.Quantity`
V-component of wind.
height : `... | Below is the the instruction that describes the task:
### Input:
r"""Calculate bulk shear through a layer.
Layer top and bottom specified in meters or pressure.
Parameters
----------
pressure : `pint.Quantity`
Atmospheric pressure profile
u : `pint.Quantity`
U-component of wind... |
def expected_values(self, beta):
""" Expected values of the function given the covariance matrix and hyperparameters
Parameters
----------
beta : np.ndarray
Contains untransformed values for latent variables
Returns
----------
The exp... | Expected values of the function given the covariance matrix and hyperparameters
Parameters
----------
beta : np.ndarray
Contains untransformed values for latent variables
Returns
----------
The expected values of the function | Below is the the instruction that describes the task:
### Input:
Expected values of the function given the covariance matrix and hyperparameters
Parameters
----------
beta : np.ndarray
Contains untransformed values for latent variables
Returns
--... |
def next_frame_pixel_noise():
"""Basic 2-frame conv model with pixel noise."""
hparams = next_frame_basic_deterministic()
hparams.add_hparam("video_modality_input_noise", 0.05)
hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom
hparams.top["inputs"] = modalities.video_top
return hparams | Basic 2-frame conv model with pixel noise. | Below is the the instruction that describes the task:
### Input:
Basic 2-frame conv model with pixel noise.
### Response:
def next_frame_pixel_noise():
"""Basic 2-frame conv model with pixel noise."""
hparams = next_frame_basic_deterministic()
hparams.add_hparam("video_modality_input_noise", 0.05)
hparams.... |
def get_by(self, name):
"""get a todo list ux by name
:rtype: TodoListUX
"""
item = self.app.get_by(name)
return TodoListUX(ux=self, controlled_list=item) | get a todo list ux by name
:rtype: TodoListUX | Below is the the instruction that describes the task:
### Input:
get a todo list ux by name
:rtype: TodoListUX
### Response:
def get_by(self, name):
"""get a todo list ux by name
:rtype: TodoListUX
"""
item = self.app.get_by(name)
return TodoListUX(ux=self, control... |
def print_statements(self):
"""Print all INDRA Statements collected by the processors."""
for i, stmt in enumerate(self.statements):
print("%s: %s" % (i, stmt)) | Print all INDRA Statements collected by the processors. | Below is the the instruction that describes the task:
### Input:
Print all INDRA Statements collected by the processors.
### Response:
def print_statements(self):
"""Print all INDRA Statements collected by the processors."""
for i, stmt in enumerate(self.statements):
print("%s: %s" % (i... |
def _find_player_id(self, row):
"""
Find the player's ID.
Find the player's ID as embedded in the 'data-append-csv' attribute,
such as 'zettehe01' for Henrik Zetterberg.
Parameters
----------
row : PyQuery object
A PyQuery object representing a singl... | Find the player's ID.
Find the player's ID as embedded in the 'data-append-csv' attribute,
such as 'zettehe01' for Henrik Zetterberg.
Parameters
----------
row : PyQuery object
A PyQuery object representing a single row in a boxscore table for
a single p... | Below is the the instruction that describes the task:
### Input:
Find the player's ID.
Find the player's ID as embedded in the 'data-append-csv' attribute,
such as 'zettehe01' for Henrik Zetterberg.
Parameters
----------
row : PyQuery object
A PyQuery object rep... |
def update(self, *others):
"""
Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
is performed completely... | Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
is performed completely in Redis. Otherwise, values are retrieved
... | Below is the the instruction that describes the task:
### Input:
Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
i... |
def generate_token(key, user_id, action_id='', when=None):
"""Generates a URL-safe token for the given user, action, time tuple.
Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
a... | Generates a URL-safe token for the given user, action, time tuple.
Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
when: the time in seconds since the epoc... | Below is the the instruction that describes the task:
### Input:
Generates a URL-safe token for the given user, action, time tuple.
Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
... |
def create(self, name, hwaddr=None, network=None, nat=False, settings={}):
"""
Create a bridge with the given name, hwaddr and networking setup
:param name: name of the bridge (must be unique), 15 characters or less, and not equal to "default".
:param hwaddr: MAC address of the bridge. I... | Create a bridge with the given name, hwaddr and networking setup
:param name: name of the bridge (must be unique), 15 characters or less, and not equal to "default".
:param hwaddr: MAC address of the bridge. If none, a one will be created for u
:param network: Networking mode, options are none, ... | Below is the the instruction that describes the task:
### Input:
Create a bridge with the given name, hwaddr and networking setup
:param name: name of the bridge (must be unique), 15 characters or less, and not equal to "default".
:param hwaddr: MAC address of the bridge. If none, a one will be crea... |
def user_id(self):
"""Who created the event (:class:`~hangups.user.UserID`)."""
return user.UserID(chat_id=self._event.sender_id.chat_id,
gaia_id=self._event.sender_id.gaia_id) | Who created the event (:class:`~hangups.user.UserID`). | Below is the the instruction that describes the task:
### Input:
Who created the event (:class:`~hangups.user.UserID`).
### Response:
def user_id(self):
"""Who created the event (:class:`~hangups.user.UserID`)."""
return user.UserID(chat_id=self._event.sender_id.chat_id,
... |
def list_locks(account_id, resource_type=None, resource_id=None):
"""Show extant locks and unlocks.
"""
locks = Client(BASE_URL, account_id).list_locks().json()
for r in locks:
if 'LockDate' in r:
r['LockDate'] = datetime.fromtimestamp(r['LockDate'])
if 'RevisionDate' in r:
... | Show extant locks and unlocks. | Below is the the instruction that describes the task:
### Input:
Show extant locks and unlocks.
### Response:
def list_locks(account_id, resource_type=None, resource_id=None):
"""Show extant locks and unlocks.
"""
locks = Client(BASE_URL, account_id).list_locks().json()
for r in locks:
if ... |
def wait_for_server(pbclient=None, dc_id=None, serverid=None,
indicator='state', state='AVAILABLE', timeout=300):
'''
wait for a server/VM to reach a defined state for a specified time
indicator := {state|vmstate} specifies if server or VM stat is tested
state specifies the status th... | wait for a server/VM to reach a defined state for a specified time
indicator := {state|vmstate} specifies if server or VM stat is tested
state specifies the status the indicator should have | Below is the the instruction that describes the task:
### Input:
wait for a server/VM to reach a defined state for a specified time
indicator := {state|vmstate} specifies if server or VM stat is tested
state specifies the status the indicator should have
### Response:
def wait_for_server(pbclient=None, dc_... |
def match_blocks(hash_func, old_children, new_children):
"""Use difflib to find matching blocks."""
sm = difflib.SequenceMatcher(
_is_junk,
a=[hash_func(c) for c in old_children],
b=[hash_func(c) for c in new_children],
)
return sm | Use difflib to find matching blocks. | Below is the the instruction that describes the task:
### Input:
Use difflib to find matching blocks.
### Response:
def match_blocks(hash_func, old_children, new_children):
"""Use difflib to find matching blocks."""
sm = difflib.SequenceMatcher(
_is_junk,
a=[hash_func(c) for c in old_childr... |
def get_value(self, field_name):
""" returns a value for a given field name """
if field_name in self.fields:
return self._dict['attributes'][field_name]
elif field_name.upper() in ['SHAPE', 'SHAPE@', "GEOMETRY"]:
return self._dict['geometry']
return None | returns a value for a given field name | Below is the the instruction that describes the task:
### Input:
returns a value for a given field name
### Response:
def get_value(self, field_name):
""" returns a value for a given field name """
if field_name in self.fields:
return self._dict['attributes'][field_name]
elif fi... |
def action_set(method_name):
"""
Creates a setter that will call the action method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the action.
@type method_name: str
"""
def action_set(value, context, **_para... | Creates a setter that will call the action method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the action.
@type method_name: str | Below is the the instruction that describes the task:
### Input:
Creates a setter that will call the action method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the action.
@type method_name: str
### Response:
def acti... |
def to_valueset(self, state):
"""
Convert to a ValueSet instance
:param state: A state
:return: The converted ValueSet instance
"""
return state.solver.VS(state.arch.bits, self.region, self.region_base_addr, self.address) | Convert to a ValueSet instance
:param state: A state
:return: The converted ValueSet instance | Below is the the instruction that describes the task:
### Input:
Convert to a ValueSet instance
:param state: A state
:return: The converted ValueSet instance
### Response:
def to_valueset(self, state):
"""
Convert to a ValueSet instance
:param state: A state
:retu... |
def expect(self, pattern, timeout=-1):
"""Waits on the given pattern to appear in std_out"""
if self.blocking:
raise RuntimeError("expect can only be used on non-blocking commands.")
try:
self.subprocess.expect(pattern=pattern, timeout=timeout)
except pexpect.EO... | Waits on the given pattern to appear in std_out | Below is the the instruction that describes the task:
### Input:
Waits on the given pattern to appear in std_out
### Response:
def expect(self, pattern, timeout=-1):
"""Waits on the given pattern to appear in std_out"""
if self.blocking:
raise RuntimeError("expect can only be used on n... |
def n1qlQueryAll(self, *args, **kwargs):
"""
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This metho... | Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query`
... | Below is the the instruction that describes the task:
### Input:
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
Th... |
def _pump(self):
'''
Attempts to process the next command in the queue if one exists and the
driver is not currently busy.
'''
while (not self._busy) and len(self._queue):
cmd = self._queue.pop(0)
self._name = cmd[2]
try:
cmd[0]... | Attempts to process the next command in the queue if one exists and the
driver is not currently busy. | Below is the the instruction that describes the task:
### Input:
Attempts to process the next command in the queue if one exists and the
driver is not currently busy.
### Response:
def _pump(self):
'''
Attempts to process the next command in the queue if one exists and the
driver is... |
def precision(self):
"""
Inverse of posterior covariance
"""
if self._precision is None:
cov = np.atleast_3d(self.covariance)
self._precision = np.zeros(cov.shape) # if one covariance per dimension
for p in range(cov.shape[-1]):
self._... | Inverse of posterior covariance | Below is the the instruction that describes the task:
### Input:
Inverse of posterior covariance
### Response:
def precision(self):
"""
Inverse of posterior covariance
"""
if self._precision is None:
cov = np.atleast_3d(self.covariance)
self._precision = np.z... |
def handle_simple_sequencing(func):
"""decorator, deal with simple sequencing cases"""
from .assessment import assessment_utilities
def wrapper(*args, **kwargs):
# re-order these things because have to delete the part after
# removing it from the parent sequence map
if 'create_asses... | decorator, deal with simple sequencing cases | Below is the the instruction that describes the task:
### Input:
decorator, deal with simple sequencing cases
### Response:
def handle_simple_sequencing(func):
"""decorator, deal with simple sequencing cases"""
from .assessment import assessment_utilities
def wrapper(*args, **kwargs):
# re-ord... |
def optional_service_connections(self):
'''Finds all service connections in which one or more components are
not required.
If all the components involved in a connection are required, that
connection is also required. If one or more are not required, that
connection is optional.... | Finds all service connections in which one or more components are
not required.
If all the components involved in a connection are required, that
connection is also required. If one or more are not required, that
connection is optional.
Example:
>>> s = RtsProfile(xml_s... | Below is the the instruction that describes the task:
### Input:
Finds all service connections in which one or more components are
not required.
If all the components involved in a connection are required, that
connection is also required. If one or more are not required, that
conne... |
def get_variant(variant_handle, context=None):
"""Create a variant given its handle (or serialized dict equivalent)
Args:
variant_handle (`ResourceHandle` or dict): Resource handle, or
equivalent serialized dict representation from
ResourceHandle.to_dict
context (`Resolv... | Create a variant given its handle (or serialized dict equivalent)
Args:
variant_handle (`ResourceHandle` or dict): Resource handle, or
equivalent serialized dict representation from
ResourceHandle.to_dict
context (`ResolvedContext`): The context this variant is associated
... | Below is the the instruction that describes the task:
### Input:
Create a variant given its handle (or serialized dict equivalent)
Args:
variant_handle (`ResourceHandle` or dict): Resource handle, or
equivalent serialized dict representation from
ResourceHandle.to_dict
c... |
def replace_event_annotations(event, newanns):
"""Replace event annotations with the provided ones."""
_humilis = event.get("_humilis", {})
if not _humilis:
event["_humilis"] = {"annotation": newanns}
else:
event["_humilis"]["annotation"] = newanns | Replace event annotations with the provided ones. | Below is the the instruction that describes the task:
### Input:
Replace event annotations with the provided ones.
### Response:
def replace_event_annotations(event, newanns):
"""Replace event annotations with the provided ones."""
_humilis = event.get("_humilis", {})
if not _humilis:
event["_h... |
def list_networks(kwargs=None, call=None):
'''
List all the standard networks for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_networks my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_networks functio... | List all the standard networks for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_networks my-vmware-config | Below is the the instruction that describes the task:
### Input:
List all the standard networks for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_networks my-vmware-config
### Response:
def list_networks(kwargs=None, call=None):
'''
List all the standard ne... |
def _string_to_record_type(string):
'''
Return a string representation of a DNS record type to a
libcloud RecordType ENUM.
:param string: A record type, e.g. A, TXT, NS
:type string: ``str``
:rtype: :class:`RecordType`
'''
string = string.upper()
record_type = getattr(RecordType, ... | Return a string representation of a DNS record type to a
libcloud RecordType ENUM.
:param string: A record type, e.g. A, TXT, NS
:type string: ``str``
:rtype: :class:`RecordType` | Below is the the instruction that describes the task:
### Input:
Return a string representation of a DNS record type to a
libcloud RecordType ENUM.
:param string: A record type, e.g. A, TXT, NS
:type string: ``str``
:rtype: :class:`RecordType`
### Response:
def _string_to_record_type(string):
... |
def extract_flac (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress a FLAC archive to a WAV file."""
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
cmdlist = [cmd, '--decode', archive, '--output-name', outfile]
return cmdlist | Decompress a FLAC archive to a WAV file. | Below is the the instruction that describes the task:
### Input:
Decompress a FLAC archive to a WAV file.
### Response:
def extract_flac (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress a FLAC archive to a WAV file."""
outfile = util.get_single_outfile(outdir, archive, extension="... |
def relabel(self, i):
'''
API: relabel(self, i)
Description:
Used by max_flow_preflowpush() method for relabelling node i.
Input:
i: Node that is being relabelled.
Post:
'distance' attribute of node i is updated.
'''
min_distance = ... | API: relabel(self, i)
Description:
Used by max_flow_preflowpush() method for relabelling node i.
Input:
i: Node that is being relabelled.
Post:
'distance' attribute of node i is updated. | Below is the the instruction that describes the task:
### Input:
API: relabel(self, i)
Description:
Used by max_flow_preflowpush() method for relabelling node i.
Input:
i: Node that is being relabelled.
Post:
'distance' attribute of node i is updated.
### Resp... |
def _get(self, *rules):
# type: (Iterable[Type[Rule]]) -> Generator[Type[Rule]]
"""
Get rules representing parameters.
The return rules can be different from parameters, in case parameter define multiple rules in one class.
:param rules: For which rules get the representation.
... | Get rules representing parameters.
The return rules can be different from parameters, in case parameter define multiple rules in one class.
:param rules: For which rules get the representation.
:return: List of rules representing parameters.
:raise NotRuleException: If the parameter does... | Below is the the instruction that describes the task:
### Input:
Get rules representing parameters.
The return rules can be different from parameters, in case parameter define multiple rules in one class.
:param rules: For which rules get the representation.
:return: List of rules representi... |
def set_packet_headers(self, headers):
""" Set packet header.
The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet
header byte sequence specified with PS_PACKETHEADER.
This is mainly for information purposes, and the stream will tran... | Set packet header.
The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet
header byte sequence specified with PS_PACKETHEADER.
This is mainly for information purposes, and the stream will transmit the packet header bytes even if no
pro... | Below is the the instruction that describes the task:
### Input:
Set packet header.
The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet
header byte sequence specified with PS_PACKETHEADER.
This is mainly for information purposes, and th... |
def validate(name, # type: str
value, # type: Any
enforce_not_none=True, # type: bool
equals=None, # type: Any
instance_of=None, # type: Union[Type, Tuple[Type]]
subclass_of=None, # type: Union[Ty... | A validation function for quick inline validation of `value`, with minimal capabilities:
* None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
* Type validation: `value` should be an instance of any of `var_types` if provided
* Value validation:
... | Below is the the instruction that describes the task:
### Input:
A validation function for quick inline validation of `value`, with minimal capabilities:
* None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
* Type validation: `value` should be an i... |
def AuthorizeGroup(self, group, subject):
"""Allow given group access to a given subject."""
# Add the subject to the dict if is isn't present, so it will get checked in
# CheckPermissions
self.authorized_users.setdefault(subject, set())
self.group_access_manager.AuthorizeGroup(group, subject) | Allow given group access to a given subject. | Below is the the instruction that describes the task:
### Input:
Allow given group access to a given subject.
### Response:
def AuthorizeGroup(self, group, subject):
"""Allow given group access to a given subject."""
# Add the subject to the dict if is isn't present, so it will get checked in
# CheckP... |
def _logging_callback(level, domain, message, data):
""" Callback that outputs libgphoto2's logging message via
Python's standard logging facilities.
:param level: libgphoto2 logging level
:param domain: component the message originates from
:param message: logging message
:param data: ... | Callback that outputs libgphoto2's logging message via
Python's standard logging facilities.
:param level: libgphoto2 logging level
:param domain: component the message originates from
:param message: logging message
:param data: Other data in the logging record (unused) | Below is the the instruction that describes the task:
### Input:
Callback that outputs libgphoto2's logging message via
Python's standard logging facilities.
:param level: libgphoto2 logging level
:param domain: component the message originates from
:param message: logging message
:param... |
def setMimeTypeByName(self, name):
" Guess the mime type "
mimetype = mimetypes.guess_type(name)[0]
if mimetype is not None:
self.mimetype = mimetypes.guess_type(name)[0].split(";")[0] | Guess the mime type | Below is the the instruction that describes the task:
### Input:
Guess the mime type
### Response:
def setMimeTypeByName(self, name):
" Guess the mime type "
mimetype = mimetypes.guess_type(name)[0]
if mimetype is not None:
self.mimetype = mimetypes.guess_type(name)[0].split(";"... |
def write_pickle(self, path, compress=False):
"""Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Ret... | Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Returns
-------
None
Notes
... | Below is the the instruction that describes the task:
### Input:
Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
... |
def extract_replacements(self, trajectory):
"""Extracts the wildcards and file replacements from the `trajectory`"""
self.env_name = trajectory.v_environment_name
self.traj_name = trajectory.v_name
self.set_name = trajectory.f_wildcard('$set')
self.run_name = trajectory.f_wildca... | Extracts the wildcards and file replacements from the `trajectory` | Below is the the instruction that describes the task:
### Input:
Extracts the wildcards and file replacements from the `trajectory`
### Response:
def extract_replacements(self, trajectory):
"""Extracts the wildcards and file replacements from the `trajectory`"""
self.env_name = trajectory.v_environ... |
def main(argv):
"""This function sets up a command-line option parser and then calls
to do all of the real work.
"""
import argparse
import codecs
# have to be ready to deal with utf-8 names
out = codecs.getwriter('utf-8')(sys.stdout)
description = '''Takes a series of at least 2 OTT ids... | This function sets up a command-line option parser and then calls
to do all of the real work. | Below is the the instruction that describes the task:
### Input:
This function sets up a command-line option parser and then calls
to do all of the real work.
### Response:
def main(argv):
"""This function sets up a command-line option parser and then calls
to do all of the real work.
"""
impor... |
def apache_config(config, outputfile):
'''
Generate a valid Apache configuration file, based on the given settings.
'''
if os.path.exists(outputfile):
os.rename(outputfile, outputfile + ".old")
print("Renamed existing Apache config file to " + outputfile + ".old")
from django.co... | Generate a valid Apache configuration file, based on the given settings. | Below is the the instruction that describes the task:
### Input:
Generate a valid Apache configuration file, based on the given settings.
### Response:
def apache_config(config, outputfile):
'''
Generate a valid Apache configuration file, based on the given settings.
'''
if os.path.exists(outpu... |
def internal_error(exception, template_path, is_admin, db=None):
"""
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whethe... | Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whether to wrap the error message in a pre
As well as rendering the error mess... | Below is the the instruction that describes the task:
### Input:
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whether to wra... |
def additionalAssignment(MobileAllocation_presence=0,
StartingTime_presence=0):
"""ADDITIONAL ASSIGNMENT Section 9.1.1"""
# Mandatory
a = TpPd(pd=0x6)
b = MessageType(mesType=0x3B) # 00111011
c = ChannelDescription()
packet = a / b / c
# Not Mandatory
if MobileA... | ADDITIONAL ASSIGNMENT Section 9.1.1 | Below is the the instruction that describes the task:
### Input:
ADDITIONAL ASSIGNMENT Section 9.1.1
### Response:
def additionalAssignment(MobileAllocation_presence=0,
StartingTime_presence=0):
"""ADDITIONAL ASSIGNMENT Section 9.1.1"""
# Mandatory
a = TpPd(pd=0x6)
b = Mess... |
def get_member_profile(self, member_id):
''' a method to retrieve member profile details
:param member_id: integer with member id from member profile
:return: dictionary with member profile details inside [json] key
profile_details = self.objects.profile.schema
'''
... | a method to retrieve member profile details
:param member_id: integer with member id from member profile
:return: dictionary with member profile details inside [json] key
profile_details = self.objects.profile.schema | Below is the the instruction that describes the task:
### Input:
a method to retrieve member profile details
:param member_id: integer with member id from member profile
:return: dictionary with member profile details inside [json] key
profile_details = self.objects.profile.schema
###... |
def encodeValue(self, value, toBeAdded=True):
"""Value is encoded as a sdr using the encoding parameters of the Field"""
encodedValue = np.array(self.encoder.encode(value), dtype=realDType)
if toBeAdded:
self.encodings.append(encodedValue)
self.numEncodings+=1
return encodedValue | Value is encoded as a sdr using the encoding parameters of the Field | Below is the the instruction that describes the task:
### Input:
Value is encoded as a sdr using the encoding parameters of the Field
### Response:
def encodeValue(self, value, toBeAdded=True):
"""Value is encoded as a sdr using the encoding parameters of the Field"""
encodedValue = np.array(self.encoder.... |
def resolve(label):
'''
composite mapping
given f(x) and g(x) here: GLOBALTT & LOCALTT respectivly
in order of preference
return g(f(x))|f(x)|g(x) | x
TODO consider returning x on fall through
: return label's mapping
'''
term_id = label
if label is not None and label in LOC... | composite mapping
given f(x) and g(x) here: GLOBALTT & LOCALTT respectivly
in order of preference
return g(f(x))|f(x)|g(x) | x
TODO consider returning x on fall through
: return label's mapping | Below is the the instruction that describes the task:
### Input:
composite mapping
given f(x) and g(x) here: GLOBALTT & LOCALTT respectivly
in order of preference
return g(f(x))|f(x)|g(x) | x
TODO consider returning x on fall through
: return label's mapping
### Response:
def resolve(label)... |
def compare_digest(a, b):
"""
PyJWT expects hmac.compare_digest to exist for all Python 3.x, however it was added in Python > 3.3
It has a fallback for Python 2.x but not for Pythons between 2.x and 3.3
Copied from: https://github.com/python/cpython/commit/6cea65555caf2716b4633827715004ab0291a282#diff-c... | PyJWT expects hmac.compare_digest to exist for all Python 3.x, however it was added in Python > 3.3
It has a fallback for Python 2.x but not for Pythons between 2.x and 3.3
Copied from: https://github.com/python/cpython/commit/6cea65555caf2716b4633827715004ab0291a282#diff-c49659257ec1b129707ce47a98adc96eL16
... | Below is the the instruction that describes the task:
### Input:
PyJWT expects hmac.compare_digest to exist for all Python 3.x, however it was added in Python > 3.3
It has a fallback for Python 2.x but not for Pythons between 2.x and 3.3
Copied from: https://github.com/python/cpython/commit/6cea65555caf2716... |
def _handle_status(self, key, value):
"""Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown.
"""
if key in ("DELETE_PROBLEM", "KEY_CONSIDERED"):
self.status = self.problem_reason.get(value, "Unknown er... | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. | Below is the the instruction that describes the task:
### Input:
Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown.
### Response:
def _handle_status(self, key, value):
"""Parse a status code from the attached GnuPG process.... |
def delete_mapping(self, index, doc_type):
"""
Delete a typed JSON document type from a specific index.
(See :ref:`es-guide-reference-api-admin-indices-delete-mapping`)
"""
path = make_path(index, doc_type)
return self.conn._send_request('DELETE', path) | Delete a typed JSON document type from a specific index.
(See :ref:`es-guide-reference-api-admin-indices-delete-mapping`) | Below is the the instruction that describes the task:
### Input:
Delete a typed JSON document type from a specific index.
(See :ref:`es-guide-reference-api-admin-indices-delete-mapping`)
### Response:
def delete_mapping(self, index, doc_type):
"""
Delete a typed JSON document type from a sp... |
def run_check(self, template_name=None, service_dir=None):
" Run checking scripts. "
print_header('Check requirements', sep='-')
map(lambda cmd: call("bash %s" % cmd), self._gen_scripts(
'check', template_name=template_name, service_dir=service_dir))
return True | Run checking scripts. | Below is the the instruction that describes the task:
### Input:
Run checking scripts.
### Response:
def run_check(self, template_name=None, service_dir=None):
" Run checking scripts. "
print_header('Check requirements', sep='-')
map(lambda cmd: call("bash %s" % cmd), self._gen_scripts(
... |
def __update(self, task_source):
""" Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
"""
next_start = task_source.next_start()
if next_start is not None:
if next_start.tzinfo is None or next_start.tzinfo != timezone.utc:
raise ValueError('Inval... | Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None | Below is the the instruction that describes the task:
### Input:
Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
### Response:
def __update(self, task_source):
""" Recheck next start of tasks from the given one only
:param task_source: source to chec... |
def calculate_new_length(gene_split, gene_results, hit):
''' Function for calcualting new length if the gene is split on several
contigs
'''
# Looping over splitted hits and calculate new length
first = 1
for split in gene_split[hit['sbjct_header']]:
new_start = int(gene_results[split]['sbjct_st... | Function for calcualting new length if the gene is split on several
contigs | Below is the the instruction that describes the task:
### Input:
Function for calcualting new length if the gene is split on several
contigs
### Response:
def calculate_new_length(gene_split, gene_results, hit):
''' Function for calcualting new length if the gene is split on several
contigs
'''
# Lo... |
def set_start(self,time,pass_to_command_line=True):
"""
Set the GPS start time of the analysis node by setting a --gps-start-time
option to the node when it is executed.
@param time: GPS start time of job.
@bool pass_to_command_line: add gps-start-time as variable option.
"""
if pass_to_comm... | Set the GPS start time of the analysis node by setting a --gps-start-time
option to the node when it is executed.
@param time: GPS start time of job.
@bool pass_to_command_line: add gps-start-time as variable option. | Below is the the instruction that describes the task:
### Input:
Set the GPS start time of the analysis node by setting a --gps-start-time
option to the node when it is executed.
@param time: GPS start time of job.
@bool pass_to_command_line: add gps-start-time as variable option.
### Response:
def set... |
def query_text():
"""Get a list of DDOs that match with the given text.
---
tags:
- ddo
parameters:
- name: text
in: query
description: ID of the asset.
required: true
type: string
- name: sort
in: query
type: object
description: ... | Get a list of DDOs that match with the given text.
---
tags:
- ddo
parameters:
- name: text
in: query
description: ID of the asset.
required: true
type: string
- name: sort
in: query
type: object
description: Key or list of keys to so... | Below is the the instruction that describes the task:
### Input:
Get a list of DDOs that match with the given text.
---
tags:
- ddo
parameters:
- name: text
in: query
description: ID of the asset.
required: true
type: string
- name: sort
in: quer... |
def geo_max_distance(left, right):
"""Returns the 2-dimensional maximum distance between two geometries in
projected units. If g1 and g2 is the same geometry the function will
return the distance between the two vertices most far from each other
in that geometry
Parameters
----------
left :... | Returns the 2-dimensional maximum distance between two geometries in
projected units. If g1 and g2 is the same geometry the function will
return the distance between the two vertices most far from each other
in that geometry
Parameters
----------
left : geometry
right : geometry
Return... | Below is the the instruction that describes the task:
### Input:
Returns the 2-dimensional maximum distance between two geometries in
projected units. If g1 and g2 is the same geometry the function will
return the distance between the two vertices most far from each other
in that geometry
Parameter... |
def register(self, event, callable, priority=10):
"""Register interest in an event.
event: name of the event (str)
callable: the callable to be used as a callback function
Returns an EventReceiver object. To unregister interest, simply
delete the object."""
... | Register interest in an event.
event: name of the event (str)
callable: the callable to be used as a callback function
Returns an EventReceiver object. To unregister interest, simply
delete the object. | Below is the the instruction that describes the task:
### Input:
Register interest in an event.
event: name of the event (str)
callable: the callable to be used as a callback function
Returns an EventReceiver object. To unregister interest, simply
delete the obje... |
async def on_raw_notice(self, message):
""" Modify NOTICE to redirect CTCP messages. """
nick, metadata = self._parse_user(message.source)
target, msg = message.params
if is_ctcp(msg):
self._sync_user(nick, metadata)
type, response = parse_ctcp(msg)
... | Modify NOTICE to redirect CTCP messages. | Below is the the instruction that describes the task:
### Input:
Modify NOTICE to redirect CTCP messages.
### Response:
async def on_raw_notice(self, message):
""" Modify NOTICE to redirect CTCP messages. """
nick, metadata = self._parse_user(message.source)
target, msg = message.params
... |
def remove_service_checks(self, service_id):
"""
Remove all checks from a service.
"""
from hypermap.aggregator.models import Service
service = Service.objects.get(id=service_id)
service.check_set.all().delete()
layer_to_process = service.layer_set.all()
for layer in layer_to_process:
... | Remove all checks from a service. | Below is the the instruction that describes the task:
### Input:
Remove all checks from a service.
### Response:
def remove_service_checks(self, service_id):
"""
Remove all checks from a service.
"""
from hypermap.aggregator.models import Service
service = Service.objects.get(id=service_id)
... |
def validate(cls, partial=True, **kwargs):
"""
Validate kwargs before setting attributes on the model
"""
data = kwargs
if not partial:
data = dict(**kwargs, **{col.name: None for col in cls.__table__.c
if col.name not in kwargs})
... | Validate kwargs before setting attributes on the model | Below is the the instruction that describes the task:
### Input:
Validate kwargs before setting attributes on the model
### Response:
def validate(cls, partial=True, **kwargs):
"""
Validate kwargs before setting attributes on the model
"""
data = kwargs
if not partial:
... |
def write_user(user):
"""Write an user ot the database.
:param User user: User to write
"""
udata = {}
for f in USER_FIELDS:
udata[f] = getattr(user, f)
for p in PERMISSIONS:
udata[p] = '1' if getattr(user, p) else '0'
db.hmset('user:{0}'.format(user.uid), udata) | Write an user ot the database.
:param User user: User to write | Below is the the instruction that describes the task:
### Input:
Write an user ot the database.
:param User user: User to write
### Response:
def write_user(user):
"""Write an user ot the database.
:param User user: User to write
"""
udata = {}
for f in USER_FIELDS:
udata[f] = g... |
def copy(self, items=None):
"""Return a new NGram object with the same settings, and
referencing the same items. Copy is shallow in that
each item is not recursively copied. Optionally specify
alternate items to populate the copy.
>>> from ngram import NGram
>>> from ... | Return a new NGram object with the same settings, and
referencing the same items. Copy is shallow in that
each item is not recursively copied. Optionally specify
alternate items to populate the copy.
>>> from ngram import NGram
>>> from copy import deepcopy
>>> n = NG... | Below is the the instruction that describes the task:
### Input:
Return a new NGram object with the same settings, and
referencing the same items. Copy is shallow in that
each item is not recursively copied. Optionally specify
alternate items to populate the copy.
>>> from ngram ... |
def _generic_mixer(slice1, slice2, mixer_name, **kwargs):
"""
Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed.
"""
mixer_name = mixer_name.lower()
if mixer_name in ['color_mix', 'rgb']:
mixed = _mix_color(slice1, slice2, **kwargs)
... | Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed. | Below is the the instruction that describes the task:
### Input:
Generic mixer to process two slices with appropriate mixer
and return the composite to be displayed.
### Response:
def _generic_mixer(slice1, slice2, mixer_name, **kwargs):
"""
Generic mixer to process two slices with appropriate mixe... |
def create_interface_method_ref(self, class_: str, if_method: str,
descriptor: str) -> InterfaceMethodRef:
"""
Creates a new :class:`ConstantInterfaceMethodRef`, adding it to the
pool and returning it.
:param class_: The name of the class to which `if... | Creates a new :class:`ConstantInterfaceMethodRef`, adding it to the
pool and returning it.
:param class_: The name of the class to which `if_method` belongs.
:param if_method: The name of the interface method.
:param descriptor: The descriptor for `if_method`. | Below is the the instruction that describes the task:
### Input:
Creates a new :class:`ConstantInterfaceMethodRef`, adding it to the
pool and returning it.
:param class_: The name of the class to which `if_method` belongs.
:param if_method: The name of the interface method.
:param d... |
def create_authz_decision_query_using_assertion(self, destination,
assertion, action=None,
resource=None,
subject=None, message_id=0,
consent=None,
extensions=None,
sign=False, nsprefix=None):
""" Makes an authz decision query based on a pr... | Makes an authz decision query based on a previously received
Assertion.
:param destination: The IdP endpoint to send the request to
:param assertion: An Assertion instance
:param action: The action you want to perform (has to be at least one)
:param resource: The resource you wa... | Below is the the instruction that describes the task:
### Input:
Makes an authz decision query based on a previously received
Assertion.
:param destination: The IdP endpoint to send the request to
:param assertion: An Assertion instance
:param action: The action you want to perform ... |
def find_frametype(channel, gpstime=None, frametype_match=None,
host=None, port=None, return_all=False, allow_tape=False,
connection=None, on_gaps='error'):
"""Find the frametype(s) that hold data for a given channel
Parameters
----------
channel : `str`, `~gwpy.de... | Find the frametype(s) that hold data for a given channel
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the channel to be found
gpstime : `int`, optional
target GPS time at which to find correct type
frametype_match : `str`, optional
regular expression to ... | Below is the the instruction that describes the task:
### Input:
Find the frametype(s) that hold data for a given channel
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the channel to be found
gpstime : `int`, optional
target GPS time at which to find correct type
... |
def apply(self, spectrum, plot=False):
"""
Apply the filter to the given [W, F], or [W, F, E] spectrum
Parameters
----------
spectrum: array-like
The wavelength [um] and flux of the spectrum
to apply the filter to
plot: bool
Plot the o... | Apply the filter to the given [W, F], or [W, F, E] spectrum
Parameters
----------
spectrum: array-like
The wavelength [um] and flux of the spectrum
to apply the filter to
plot: bool
Plot the original and filtered spectrum
Returns
----... | Below is the the instruction that describes the task:
### Input:
Apply the filter to the given [W, F], or [W, F, E] spectrum
Parameters
----------
spectrum: array-like
The wavelength [um] and flux of the spectrum
to apply the filter to
plot: bool
... |
def create_engine(url, con=None, header=True, show_progress=5.0, clear_progress=True):
'''Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.com)
HT... | Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.com)
HTTP_PROXY HTTP proxy (optional)
Parameters
----------
url : string
Eng... | Below is the the instruction that describes the task:
### Input:
Create a handler for query engine based on a URL.
The following environment variables are used for default connection:
TD_API_KEY API key
TD_API_SERVER API server (default: api.treasuredata.com)
HTTP_PROXY HTTP proxy (... |
def get_cg_volumes(self, group_id):
""" return all non snapshots volumes in cg """
for volume in self.xcli_client.cmd.vol_list(cg=group_id):
if volume.snapshot_of == '':
yield volume.name | return all non snapshots volumes in cg | Below is the the instruction that describes the task:
### Input:
return all non snapshots volumes in cg
### Response:
def get_cg_volumes(self, group_id):
""" return all non snapshots volumes in cg """
for volume in self.xcli_client.cmd.vol_list(cg=group_id):
if volume.snapshot_of == ... |
def _index(self, name):
'''Returns index transforms for ``name``.
:type name: unicode
:rtype: ``{ create |--> function, transform |--> function }``
'''
name = name.decode('utf-8')
try:
return self._indexes[name]
except KeyError:
raise KeyE... | Returns index transforms for ``name``.
:type name: unicode
:rtype: ``{ create |--> function, transform |--> function }`` | Below is the the instruction that describes the task:
### Input:
Returns index transforms for ``name``.
:type name: unicode
:rtype: ``{ create |--> function, transform |--> function }``
### Response:
def _index(self, name):
'''Returns index transforms for ``name``.
:type name: uni... |
def daemonize_if(opts):
'''
Daemonize a module function process if multiprocessing is True and the
process is not being called by salt-call
'''
if 'salt-call' in sys.argv[0]:
return
if not opts.get('multiprocessing', True):
return
if sys.platform.startswith('win'):
re... | Daemonize a module function process if multiprocessing is True and the
process is not being called by salt-call | Below is the the instruction that describes the task:
### Input:
Daemonize a module function process if multiprocessing is True and the
process is not being called by salt-call
### Response:
def daemonize_if(opts):
'''
Daemonize a module function process if multiprocessing is True and the
process i... |
def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
"""Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string... | Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string.
If not a string and content_type is not provided, then this
function assumes the payload is a JSON-able Python obje... | Below is the the instruction that describes the task:
### Input:
Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string.
If not a string and content_type is not provided, then thi... |
def issues(self, **kwargs):
"""List issues related to this milestone.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_... | List issues related to this milestone.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False and no pag... | Below is the the instruction that describes the task:
### Input:
List issues related to this milestone.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (start... |
def _query(self, query_str, query_args=None, **query_options):
"""
**query_options -- dict
ignore_result -- boolean -- true to not attempt to fetch results
fetchone -- boolean -- true to only fetch one result
count_result -- boolean -- true to return the int count of ... | **query_options -- dict
ignore_result -- boolean -- true to not attempt to fetch results
fetchone -- boolean -- true to only fetch one result
count_result -- boolean -- true to return the int count of rows affected | Below is the the instruction that describes the task:
### Input:
**query_options -- dict
ignore_result -- boolean -- true to not attempt to fetch results
fetchone -- boolean -- true to only fetch one result
count_result -- boolean -- true to return the int count of rows affected
... |
def connect(
creator, maxusage=None, setsession=None,
failures=None, ping=1, closeable=True, *args, **kwargs):
"""A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 c... | A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 compliant database module
maxusage: maximum usage limit for the underlying DB-API 2 connection
(number of database operatio... | Below is the the instruction that describes the task:
### Input:
A tough version of the connection constructor of a DB-API 2 module.
creator: either an arbitrary function returning new DB-API 2 compliant
connection objects or a DB-API 2 compliant database module
maxusage: maximum usage limit for th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.