code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def make_server(function, port, authkey, qsize=None):
"""Create a manager containing input and output queues, and a function
to map inputs over. A connecting client can read the stored function,
apply it to items in the input queue and post back to the output
queue
:param function: function to appl... | Create a manager containing input and output queues, and a function
to map inputs over. A connecting client can read the stored function,
apply it to items in the input queue and post back to the output
queue
:param function: function to apply to inputs
:param port: port over which to server
:p... | Below is the the instruction that describes the task:
### Input:
Create a manager containing input and output queues, and a function
to map inputs over. A connecting client can read the stored function,
apply it to items in the input queue and post back to the output
queue
:param function: function... |
def save_as(self, info):
""" Handles saving the current model to file.
"""
if not info.initialized:
return
# retval = self.edit_traits(parent=info.ui.control, view="file_view")
dlg = FileDialog( action = "save as",
wildcard = "Graphviz Files (*.dot, *.xdo... | Handles saving the current model to file. | Below is the the instruction that describes the task:
### Input:
Handles saving the current model to file.
### Response:
def save_as(self, info):
""" Handles saving the current model to file.
"""
if not info.initialized:
return
# retval = self.edit_traits(parent=info.ui.... |
def get_system_flags() -> FrozenSet[Flag]:
"""Return the set of implemented system flags."""
return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft}) | Return the set of implemented system flags. | Below is the the instruction that describes the task:
### Input:
Return the set of implemented system flags.
### Response:
def get_system_flags() -> FrozenSet[Flag]:
"""Return the set of implemented system flags."""
return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft}) |
def removeChild(self, position):
""" Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
"""
assert 0 <= position <= len(self.childItems), \
"position should be 0 < {} <= {}".format(position, len(self.child... | Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it. | Below is the the instruction that describes the task:
### Input:
Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
### Response:
def removeChild(self, position):
""" Removes the child at the position 'position'
Call... |
def expand_env_var(env_var):
"""
Expands (potentially nested) env vars by repeatedly applying
`expandvars` and `expanduser` until interpolation stops having
any effect.
"""
if not env_var:
return env_var
while True:
interpolated = os.path.expanduser(os.path.expandvars(str(env... | Expands (potentially nested) env vars by repeatedly applying
`expandvars` and `expanduser` until interpolation stops having
any effect. | Below is the the instruction that describes the task:
### Input:
Expands (potentially nested) env vars by repeatedly applying
`expandvars` and `expanduser` until interpolation stops having
any effect.
### Response:
def expand_env_var(env_var):
"""
Expands (potentially nested) env vars by repeatedly... |
def _handle_offset_response(self, future, response):
"""Callback for the response of the list offset call above.
Arguments:
future (Future): the future to update based on response
response (OffsetResponse): response from the server
Raises:
AssertionError: if... | Callback for the response of the list offset call above.
Arguments:
future (Future): the future to update based on response
response (OffsetResponse): response from the server
Raises:
AssertionError: if response does not match partition | Below is the the instruction that describes the task:
### Input:
Callback for the response of the list offset call above.
Arguments:
future (Future): the future to update based on response
response (OffsetResponse): response from the server
Raises:
AssertionErro... |
def create_index(self, model, waiting_models):
"""
Creates search indexes.
Args:
model: model to execute
waiting_models: if riak can't return response immediately, model is taken to queue.
After first execution session, method is executed with waiting models ... | Creates search indexes.
Args:
model: model to execute
waiting_models: if riak can't return response immediately, model is taken to queue.
After first execution session, method is executed with waiting models and controlled.
And be ensured that all given models ar... | Below is the the instruction that describes the task:
### Input:
Creates search indexes.
Args:
model: model to execute
waiting_models: if riak can't return response immediately, model is taken to queue.
After first execution session, method is executed with waiting model... |
def wrap(cls, root, refobjinter, refobjects):
"""Wrap the given refobjects in a :class:`Reftrack` instance
and set the right parents
This is the preferred method for creating refobjects. Because you cannot set
the parent of a :class:`Reftrack` before the parent has been wrapped itselfed... | Wrap the given refobjects in a :class:`Reftrack` instance
and set the right parents
This is the preferred method for creating refobjects. Because you cannot set
the parent of a :class:`Reftrack` before the parent has been wrapped itselfed.
:param root: the root that groups all reftrack... | Below is the the instruction that describes the task:
### Input:
Wrap the given refobjects in a :class:`Reftrack` instance
and set the right parents
This is the preferred method for creating refobjects. Because you cannot set
the parent of a :class:`Reftrack` before the parent has been wrap... |
def paragraph(
self,
nb_sentences=3,
variable_nb_sentences=True,
ext_word_list=None):
"""
:returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut
pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.'
... | :returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut
pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.'
Keyword arguments:
:param nb_sentences: around how many sentences the paragraph should contain
:param variable_nb_sentences: set to false ... | Below is the the instruction that describes the task:
### Input:
:returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut
pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.'
Keyword arguments:
:param nb_sentences: around how many sentences the paragra... |
def commit_and_push(local_root, remote, versions):
"""Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config ... | Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config for commits.
:param str local_root: Local path to git... | Below is the the instruction that describes the task:
### Input:
Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad ... |
def _get_python_cmd(self):
"""
return the python executable in the virtualenv.
Try first sys.executable but use fallbacks.
"""
file_names = ["pypy.exe", "python.exe", "python"]
executable = sys.executable
if executable is not None:
executable = os.path... | return the python executable in the virtualenv.
Try first sys.executable but use fallbacks. | Below is the the instruction that describes the task:
### Input:
return the python executable in the virtualenv.
Try first sys.executable but use fallbacks.
### Response:
def _get_python_cmd(self):
"""
return the python executable in the virtualenv.
Try first sys.executable but use ... |
def mk_fmtfld(nt_item, joinchr=" ", eol="\n"):
"""Given a namedtuple, return a format_field string."""
fldstrs = []
# Default formats based on fieldname
fld2fmt = {
'hdrgo' : lambda f: "{{{FLD}:1,}}".format(FLD=f),
'dcnt' : lambda f: "{{{FLD}:6,}}".format(FLD=f),
'level' : lambda... | Given a namedtuple, return a format_field string. | Below is the the instruction that describes the task:
### Input:
Given a namedtuple, return a format_field string.
### Response:
def mk_fmtfld(nt_item, joinchr=" ", eol="\n"):
"""Given a namedtuple, return a format_field string."""
fldstrs = []
# Default formats based on fieldname
fld2fmt = {
... |
def update(self, selector, update, options=None):
"""Update user data."""
# we're ignoring the `options` argument at this time
del options
user = get_object(
self.model, selector['_id'],
pk=this.user_id,
)
profile_update = self.deserialize_profile(... | Update user data. | Below is the the instruction that describes the task:
### Input:
Update user data.
### Response:
def update(self, selector, update, options=None):
"""Update user data."""
# we're ignoring the `options` argument at this time
del options
user = get_object(
self.model, sele... |
def create_exposed_session(self, session, key=None, context=None):
"""
:type session: SimpleSession
"""
# shiro ignores key and context parameters
return DelegatingSession(self, SessionKey(session.session_id)) | :type session: SimpleSession | Below is the the instruction that describes the task:
### Input:
:type session: SimpleSession
### Response:
def create_exposed_session(self, session, key=None, context=None):
"""
:type session: SimpleSession
"""
# shiro ignores key and context parameters
return DelegatingS... |
def roles(self):
"""Return a set with all roles granted to the user."""
roles = []
for ur in self.roleusers:
roles.append(ur.role)
return set(roles) | Return a set with all roles granted to the user. | Below is the the instruction that describes the task:
### Input:
Return a set with all roles granted to the user.
### Response:
def roles(self):
"""Return a set with all roles granted to the user."""
roles = []
for ur in self.roleusers:
roles.append(ur.role)
return set(r... |
def commit_state_create( self, nameop, current_block_number ):
"""
Commit a state-creation operation (works for name_registration,
namespace_reveal, name_import).
Returns the sequence of dicts of fields to serialize.
DO NOT CALL THIS DIRECTLY
"""
# have to have... | Commit a state-creation operation (works for name_registration,
namespace_reveal, name_import).
Returns the sequence of dicts of fields to serialize.
DO NOT CALL THIS DIRECTLY | Below is the the instruction that describes the task:
### Input:
Commit a state-creation operation (works for name_registration,
namespace_reveal, name_import).
Returns the sequence of dicts of fields to serialize.
DO NOT CALL THIS DIRECTLY
### Response:
def commit_state_create( self, nam... |
def find_ca_bundle():
"""Return an existing CA bundle path, or None"""
if os.name=='nt':
return get_win_certfile()
else:
for cert_path in cert_paths:
if os.path.isfile(cert_path):
return cert_path
try:
return pkg_resources.resource_filename('certifi', ... | Return an existing CA bundle path, or None | Below is the the instruction that describes the task:
### Input:
Return an existing CA bundle path, or None
### Response:
def find_ca_bundle():
"""Return an existing CA bundle path, or None"""
if os.name=='nt':
return get_win_certfile()
else:
for cert_path in cert_paths:
if ... |
def ch_handler(offset=0, length=-1, **kw):
""" Handle standard PRIMARY clipboard access. Note that offset and length
are passed as strings. This differs from CLIPBOARD. """
global _lastSel
offset = int(offset)
length = int(length)
if length < 0: length = len(_lastSel)
return _lastSel[offs... | Handle standard PRIMARY clipboard access. Note that offset and length
are passed as strings. This differs from CLIPBOARD. | Below is the the instruction that describes the task:
### Input:
Handle standard PRIMARY clipboard access. Note that offset and length
are passed as strings. This differs from CLIPBOARD.
### Response:
def ch_handler(offset=0, length=-1, **kw):
""" Handle standard PRIMARY clipboard access. Note that offs... |
def disk_pick_polar(n=1, rng=None):
"""Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, sha... | Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, shape (n, 2)
Sample vectors. | Below is the the instruction that describes the task:
### Input:
Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
... |
def contains_project_name(name, link):
"""
Checks if the given link `somewhat` contains the project name.
:param name: str, project name
:param link: str, link
:return: bool, True if the link contains the project name
"""
def unclutter(string):
# strip out all python references and r... | Checks if the given link `somewhat` contains the project name.
:param name: str, project name
:param link: str, link
:return: bool, True if the link contains the project name | Below is the the instruction that describes the task:
### Input:
Checks if the given link `somewhat` contains the project name.
:param name: str, project name
:param link: str, link
:return: bool, True if the link contains the project name
### Response:
def contains_project_name(name, link):
"""
... |
def cybox_RAW_ft_handler(self, enrichment, fact, attr_info, add_fact_kargs):
"""
Handler for facts whose content is to be written to disk rather
than stored in the database. We use it for all elements
that contain the string 'Raw_' ('Raw_Header', 'Raw_Artifact', ...)
"""
... | Handler for facts whose content is to be written to disk rather
than stored in the database. We use it for all elements
that contain the string 'Raw_' ('Raw_Header', 'Raw_Artifact', ...) | Below is the the instruction that describes the task:
### Input:
Handler for facts whose content is to be written to disk rather
than stored in the database. We use it for all elements
that contain the string 'Raw_' ('Raw_Header', 'Raw_Artifact', ...)
### Response:
def cybox_RAW_ft_handler(self, en... |
def parse_agent_interface_format(
feature_screen=None,
feature_minimap=None,
rgb_screen=None,
rgb_minimap=None,
action_space=None,
camera_width_world_units=None,
use_feature_units=False,
use_raw_units=False,
use_unit_counts=False,
use_camera_position=False):
"""Creates an Agent... | Creates an AgentInterfaceFormat object from keyword args.
Convenient when using dictionaries or command-line arguments for config.
Note that the feature_* and rgb_* properties define the respective spatial
observation dimensions and accept:
* None or 0 to disable that spatial observation.
* A single... | Below is the the instruction that describes the task:
### Input:
Creates an AgentInterfaceFormat object from keyword args.
Convenient when using dictionaries or command-line arguments for config.
Note that the feature_* and rgb_* properties define the respective spatial
observation dimensions and accept:
... |
def time_context_from_ref(self, timex):
"""Return a time context object given a timex reference entry."""
# If the timex has a value set, it means that it refers to a DCT or
# a TimeExpression e.g. "value": {"@id": "_:DCT_1"} and the parameters
# need to be taken from there
value... | Return a time context object given a timex reference entry. | Below is the the instruction that describes the task:
### Input:
Return a time context object given a timex reference entry.
### Response:
def time_context_from_ref(self, timex):
"""Return a time context object given a timex reference entry."""
# If the timex has a value set, it means that it refer... |
def S(self):
"""Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f)
"""
if self.c is None:
raise RuntimeError('Cross-spectral density requires noise '
'covariance matrix c.')
H = self.H()
# ... | Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) | Below is the the instruction that describes the task:
### Input:
Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f)
### Response:
def S(self):
"""Cross-spectral density.
.. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f)
"""
... |
def _get_vm_by_id(vmid, allDetails=False):
'''
Retrieve a VM based on the ID.
'''
for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)):
if six.text_type(vm_details['vmid']) == six.text_type(vmid):
return vm_details
log.info('VM with ID "%s" could... | Retrieve a VM based on the ID. | Below is the the instruction that describes the task:
### Input:
Retrieve a VM based on the ID.
### Response:
def _get_vm_by_id(vmid, allDetails=False):
'''
Retrieve a VM based on the ID.
'''
for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)):
if six.text_... |
def add_constraints(self):
"""
Set the base constraints on the relation query.
:rtype: None
"""
if self._constraints:
foreign_key = getattr(self._parent, self._foreign_key, None)
if foreign_key is None:
self._query = None
else:... | Set the base constraints on the relation query.
:rtype: None | Below is the the instruction that describes the task:
### Input:
Set the base constraints on the relation query.
:rtype: None
### Response:
def add_constraints(self):
"""
Set the base constraints on the relation query.
:rtype: None
"""
if self._constraints:
... |
def mkpath(filepath, permissions=0o777):
""" This function executes a mkdir command for filepath and with permissions
(octal number with leading 0 or string only)
# eg. mkpath("path/to/file", "0o775")
"""
# Converting string of octal to integer, if string is given.
if isinstance(permissions, str):
... | This function executes a mkdir command for filepath and with permissions
(octal number with leading 0 or string only)
# eg. mkpath("path/to/file", "0o775") | Below is the the instruction that describes the task:
### Input:
This function executes a mkdir command for filepath and with permissions
(octal number with leading 0 or string only)
# eg. mkpath("path/to/file", "0o775")
### Response:
def mkpath(filepath, permissions=0o777):
""" This function executes a m... |
def _calc_mod_reduc(self, strains, strain_ref, x_1, x_1_mean, x_2,
x_2_mean, x_3, x_3_mean):
"""Compute the shear modulus reduction using Equation (1)."""
ones = np.ones_like(strains)
# Predictor
x_4 = np.log(self._lab_consol_ratio) * ones
x = np.c_[ones,... | Compute the shear modulus reduction using Equation (1). | Below is the the instruction that describes the task:
### Input:
Compute the shear modulus reduction using Equation (1).
### Response:
def _calc_mod_reduc(self, strains, strain_ref, x_1, x_1_mean, x_2,
x_2_mean, x_3, x_3_mean):
"""Compute the shear modulus reduction using Equation (... |
def dict_remove_value(d, v):
"""
Recursively remove keys with a certain value from a dict
:param d: the dictionary
:param v: value which should be removed
:return: formatted dictionary
"""
dd = dict()
for key, value in d.items():
if not value == v:
if isinstance(value... | Recursively remove keys with a certain value from a dict
:param d: the dictionary
:param v: value which should be removed
:return: formatted dictionary | Below is the the instruction that describes the task:
### Input:
Recursively remove keys with a certain value from a dict
:param d: the dictionary
:param v: value which should be removed
:return: formatted dictionary
### Response:
def dict_remove_value(d, v):
"""
Recursively remove keys with a ... |
def add_event(self, event, prepend=False):
"""
Adds an event to the manager.
"""
if prepend:
self._events.insert(0, event)
else:
self._events.append(event) | Adds an event to the manager. | Below is the the instruction that describes the task:
### Input:
Adds an event to the manager.
### Response:
def add_event(self, event, prepend=False):
"""
Adds an event to the manager.
"""
if prepend:
self._events.insert(0, event)
else:
self._events.... |
def add_edge_bias(x, filter_size):
"""Pad x and concatenates an edge bias across the depth of x.
The edge bias can be thought of as a binary feature which is unity when
the filter is being convolved over an edge and zero otherwise.
Args:
x: Input tensor, shape (NHWC)
filter_size: filter_size to determ... | Pad x and concatenates an edge bias across the depth of x.
The edge bias can be thought of as a binary feature which is unity when
the filter is being convolved over an edge and zero otherwise.
Args:
x: Input tensor, shape (NHWC)
filter_size: filter_size to determine padding.
Returns:
x_pad: Input... | Below is the the instruction that describes the task:
### Input:
Pad x and concatenates an edge bias across the depth of x.
The edge bias can be thought of as a binary feature which is unity when
the filter is being convolved over an edge and zero otherwise.
Args:
x: Input tensor, shape (NHWC)
filte... |
def scale(self, scalex, scaley=None, center=(0, 0)):
"""
Scale this object.
Parameters
----------
scalex : number
Scaling factor along the first axis.
scaley : number or ``None``
Scaling factor along the second axis. If ``None``, same as
... | Scale this object.
Parameters
----------
scalex : number
Scaling factor along the first axis.
scaley : number or ``None``
Scaling factor along the second axis. If ``None``, same as
``scalex``.
center : array-like[2]
Center point f... | Below is the the instruction that describes the task:
### Input:
Scale this object.
Parameters
----------
scalex : number
Scaling factor along the first axis.
scaley : number or ``None``
Scaling factor along the second axis. If ``None``, same as
... |
def flatten(self, messages, parent_key=''):
"""
Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
... | Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
@type messages: dict
@param messages: The dict ... | Below is the the instruction that describes the task:
### Input:
Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modif... |
def run(self, port_number, number_of_procs=0):
"""
Create the server and run the IOLoop.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the applic... | Create the server and run the IOLoop.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the application's ``debug`` setting is ``True``, then we are
going to... | Below is the the instruction that describes the task:
### Input:
Create the server and run the IOLoop.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the appl... |
def rotate(self, theta, around):
"""Rotate Compound around an arbitrary vector.
Parameters
----------
theta : float
The angle by which to rotate the Compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
The vector about which to rotate the Co... | Rotate Compound around an arbitrary vector.
Parameters
----------
theta : float
The angle by which to rotate the Compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
The vector about which to rotate the Compound. | Below is the the instruction that describes the task:
### Input:
Rotate Compound around an arbitrary vector.
Parameters
----------
theta : float
The angle by which to rotate the Compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
The vector abo... |
def tell_sender_to_start(self):
'''send a start packet (if we haven't sent one in the last second)'''
now = time.time()
if now - self.time_last_start_packet_sent < 1:
return
self.time_last_start_packet_sent = now
if self.log_settings.verbose:
print("DFLog... | send a start packet (if we haven't sent one in the last second) | Below is the the instruction that describes the task:
### Input:
send a start packet (if we haven't sent one in the last second)
### Response:
def tell_sender_to_start(self):
'''send a start packet (if we haven't sent one in the last second)'''
now = time.time()
if now - self.time_last_star... |
def macaroon_ops(self, macaroons):
''' This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
:return:
'''... | This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
:return: | Below is the the instruction that describes the task:
### Input:
This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
... |
def df2list(df):
"""
Converts pandas.DataFrame values into list
:param df: pandas.DataFrame
:return: list
"""
for column in df:
df[column] = df[column].astype(object).where(df[column].notnull(), None)
return df.to_dict(orient='records') | Converts pandas.DataFrame values into list
:param df: pandas.DataFrame
:return: list | Below is the the instruction that describes the task:
### Input:
Converts pandas.DataFrame values into list
:param df: pandas.DataFrame
:return: list
### Response:
def df2list(df):
"""
Converts pandas.DataFrame values into list
:param df: pandas.DataFrame
:return: li... |
def get_parents_graph(self, item_ids, language=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'parent' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter ... | Get a subgraph of items reachable from the given set of items through
the 'parent' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the given language
... | Below is the the instruction that describes the task:
### Input:
Get a subgraph of items reachable from the given set of items through
the 'parent' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out i... |
def generate_component_annotation_miriam_match(elements, component, db):
"""
Tabulate which MIRIAM databases the element's annotation match.
If the relevant MIRIAM identifier is not in an element's annotation it is
ignored.
Parameters
----------
elements : list
Elements of a model,... | Tabulate which MIRIAM databases the element's annotation match.
If the relevant MIRIAM identifier is not in an element's annotation it is
ignored.
Parameters
----------
elements : list
Elements of a model, either metabolites or reactions.
component : {"metabolites", "reactions"}
... | Below is the the instruction that describes the task:
### Input:
Tabulate which MIRIAM databases the element's annotation match.
If the relevant MIRIAM identifier is not in an element's annotation it is
ignored.
Parameters
----------
elements : list
Elements of a model, either metaboli... |
def create_random(cls, gene_length, n=1, gene_class=BinaryGene):
"""
Create 1 or more chromosomes with randomly generated DNA.
gene_length: int (or sequence of ints) describing gene DNA length
n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromos... | Create 1 or more chromosomes with randomly generated DNA.
gene_length: int (or sequence of ints) describing gene DNA length
n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome
gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes
... | Below is the the instruction that describes the task:
### Input:
Create 1 or more chromosomes with randomly generated DNA.
gene_length: int (or sequence of ints) describing gene DNA length
n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome
gene... |
def patch(**on):
"""Globally patches certain system modules to be 'cooperaive'.
The keyword arguments afford some control over which modules are patched.
If no keyword arguments are supplied, all possible modules are patched.
If keywords are set to True, only the specified modules are patched. E.g.,
... | Globally patches certain system modules to be 'cooperaive'.
The keyword arguments afford some control over which modules are patched.
If no keyword arguments are supplied, all possible modules are patched.
If keywords are set to True, only the specified modules are patched. E.g.,
``monkey_patch(socket... | Below is the the instruction that describes the task:
### Input:
Globally patches certain system modules to be 'cooperaive'.
The keyword arguments afford some control over which modules are patched.
If no keyword arguments are supplied, all possible modules are patched.
If keywords are set to True, onl... |
def to_motevo(self):
"""Return motif formatted in MotEvo (TRANSFAC-like) format
Returns
-------
m : str
String of motif in MotEvo format.
"""
m = "//\n"
m += "NA {}\n".format(self.id)
m += "P0\tA\tC\tG\tT\n"
for i, row in enume... | Return motif formatted in MotEvo (TRANSFAC-like) format
Returns
-------
m : str
String of motif in MotEvo format. | Below is the the instruction that describes the task:
### Input:
Return motif formatted in MotEvo (TRANSFAC-like) format
Returns
-------
m : str
String of motif in MotEvo format.
### Response:
def to_motevo(self):
"""Return motif formatted in MotEvo (TRANSFAC-li... |
def _optimize_A(self, A):
"""Find optimal transformation matrix A by minimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
A : ndarray
The transformation matrix.
"""
right_eigenvector... | Find optimal transformation matrix A by minimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
A : ndarray
The transformation matrix. | Below is the the instruction that describes the task:
### Input:
Find optimal transformation matrix A by minimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
A : ndarray
The transformation matrix.
### R... |
def yield_lines(strs):
"""Yield non-empty/non-comment lines of a string or sequence"""
if isinstance(strs, string_types):
for s in strs.splitlines():
s = s.strip()
# skip blank lines/comments
if s and not s.startswith('#'):
yield s
else:
fo... | Yield non-empty/non-comment lines of a string or sequence | Below is the the instruction that describes the task:
### Input:
Yield non-empty/non-comment lines of a string or sequence
### Response:
def yield_lines(strs):
"""Yield non-empty/non-comment lines of a string or sequence"""
if isinstance(strs, string_types):
for s in strs.splitlines():
... |
def _compute_mean(self, C, rup, dists, sites, imt):
"""
Returns the mean ground motion acceleration and velocity
"""
# Convert rhypo to rrup
rrup = rhypo_to_rrup(dists.rhypo, rup.mag)
mean = (self._get_magnitude_scaling_term(C, rup.mag) +
self._get_distanc... | Returns the mean ground motion acceleration and velocity | Below is the the instruction that describes the task:
### Input:
Returns the mean ground motion acceleration and velocity
### Response:
def _compute_mean(self, C, rup, dists, sites, imt):
"""
Returns the mean ground motion acceleration and velocity
"""
# Convert rhypo to rrup
... |
def iriToURI(iri):
"""Transform an IRI to a URI by escaping unicode."""
# According to RFC 3987, section 3.1, "Mapping of IRIs to URIs"
if isinstance(iri, bytes):
iri = str(iri, encoding="utf-8")
return iri.encode('ascii', errors='oid_percent_escape').decode() | Transform an IRI to a URI by escaping unicode. | Below is the the instruction that describes the task:
### Input:
Transform an IRI to a URI by escaping unicode.
### Response:
def iriToURI(iri):
"""Transform an IRI to a URI by escaping unicode."""
# According to RFC 3987, section 3.1, "Mapping of IRIs to URIs"
if isinstance(iri, bytes):
iri = ... |
def _cts_or_stc(data):
"""Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?"""
# UDP/TCP
if data['transport']:
# TCP flags
if data['transport']['type'] == 'TCP':
flags = data['transport']['flags']
# Syn/... | Does the data look like a Client to Server (cts) or Server to Client (stc) traffic? | Below is the the instruction that describes the task:
### Input:
Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?
### Response:
def _cts_or_stc(data):
"""Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?"""
# UDP/TCP
if d... |
def _convert_date(date_string, date_format):
"""
Convert a date in a given format to epoch time. Mostly a wrapper for
datetime's strptime.
"""
if date_format != 'epoch':
return datetime.strptime(date_string, date_format).timestamp()
else:
return float(date_string) | Convert a date in a given format to epoch time. Mostly a wrapper for
datetime's strptime. | Below is the the instruction that describes the task:
### Input:
Convert a date in a given format to epoch time. Mostly a wrapper for
datetime's strptime.
### Response:
def _convert_date(date_string, date_format):
"""
Convert a date in a given format to epoch time. Mostly a wrapper for
datetime's s... |
def _validate_slices_form_uniform_grid(slice_datasets):
'''
Perform various data checks to ensure that the list of slices form a
evenly-spaced grid of data.
Some of these checks are probably not required if the data follows the
DICOM specification, however it seems pertinent to check anyway.
'''... | Perform various data checks to ensure that the list of slices form a
evenly-spaced grid of data.
Some of these checks are probably not required if the data follows the
DICOM specification, however it seems pertinent to check anyway. | Below is the the instruction that describes the task:
### Input:
Perform various data checks to ensure that the list of slices form a
evenly-spaced grid of data.
Some of these checks are probably not required if the data follows the
DICOM specification, however it seems pertinent to check anyway.
### Re... |
def main(path_dir, requirements_name):
"""Console script for imports."""
click.echo("\nWARNING: Uninstall libs it's at your own risk!")
click.echo('\nREMINDER: After uninstall libs, update your requirements '
'file.\nUse the `pip freeze > requirements.txt` command.')
click.echo('\n\nList... | Console script for imports. | Below is the the instruction that describes the task:
### Input:
Console script for imports.
### Response:
def main(path_dir, requirements_name):
"""Console script for imports."""
click.echo("\nWARNING: Uninstall libs it's at your own risk!")
click.echo('\nREMINDER: After uninstall libs, update your re... |
def tensor(x:Any, *rest)->Tensor:
"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly."
if len(rest): x = (x,)+rest
# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report
if is_listy(x) and len(x)==0: return tensor(0)
res = torch... | Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly. | Below is the the instruction that describes the task:
### Input:
Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly.
### Response:
def tensor(x:Any, *rest)->Tensor:
"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly."
if l... |
def add_line(self, sentences, line_number=None):
""" Add current line to the output.
See self.line() for more info
"""
self.bytes += self.line(sentences, line_number) | Add current line to the output.
See self.line() for more info | Below is the the instruction that describes the task:
### Input:
Add current line to the output.
See self.line() for more info
### Response:
def add_line(self, sentences, line_number=None):
""" Add current line to the output.
See self.line() for more info
"""
self.bytes += s... |
def fetch_task_to_run(self):
"""
Returns the first task that is ready to run or
None if no task can be submitted at present"
Raises:
`StopIteration` if all tasks are done.
"""
# All the tasks are done so raise an exception
# that will be handled by th... | Returns the first task that is ready to run or
None if no task can be submitted at present"
Raises:
`StopIteration` if all tasks are done. | Below is the the instruction that describes the task:
### Input:
Returns the first task that is ready to run or
None if no task can be submitted at present"
Raises:
`StopIteration` if all tasks are done.
### Response:
def fetch_task_to_run(self):
"""
Returns the first t... |
def set_port_settings(self, port_number, settings):
"""
Applies port settings to a specific port.
:param port_number: port number to set the settings
:param settings: port settings
"""
if settings["type"] == "access":
yield from self.set_access_port(port_num... | Applies port settings to a specific port.
:param port_number: port number to set the settings
:param settings: port settings | Below is the the instruction that describes the task:
### Input:
Applies port settings to a specific port.
:param port_number: port number to set the settings
:param settings: port settings
### Response:
def set_port_settings(self, port_number, settings):
"""
Applies port settings ... |
def from_dataframe(df,
source_col='source',
target_col='target',
interaction_col='interaction',
name='From DataFrame',
edge_attr_cols=[]):
"""
Utility to convert Pandas DataFrame object into Cytoscape.js JSON
:pa... | Utility to convert Pandas DataFrame object into Cytoscape.js JSON
:param df: Dataframe to convert.
:param source_col: Name of source column.
:param target_col: Name of target column.
:param interaction_col: Name of interaction column.
:param name: Name of network.
:param edge_attr_cols: List co... | Below is the the instruction that describes the task:
### Input:
Utility to convert Pandas DataFrame object into Cytoscape.js JSON
:param df: Dataframe to convert.
:param source_col: Name of source column.
:param target_col: Name of target column.
:param interaction_col: Name of interaction column.... |
def append(self, x):
"""
Append the given element to the list and synchronize the textual
representation.
"""
super(EntriesList, self).append(x)
if self.entries_collection is not None:
self.entries_collection.add_entry(self.date, x) | Append the given element to the list and synchronize the textual
representation. | Below is the the instruction that describes the task:
### Input:
Append the given element to the list and synchronize the textual
representation.
### Response:
def append(self, x):
"""
Append the given element to the list and synchronize the textual
representation.
"""
... |
def _ParseKeyWithPlugin(self, parser_mediator, registry_key, plugin):
"""Parses the Registry key with a specific plugin.
Args:
parser_mediator (ParserMediator): parser mediator.
registry_key (dfwinreg.WinRegistryKey): Windwos Registry key.
plugin (WindowsRegistryPlugin): Windows Registry plug... | Parses the Registry key with a specific plugin.
Args:
parser_mediator (ParserMediator): parser mediator.
registry_key (dfwinreg.WinRegistryKey): Windwos Registry key.
plugin (WindowsRegistryPlugin): Windows Registry plugin. | Below is the the instruction that describes the task:
### Input:
Parses the Registry key with a specific plugin.
Args:
parser_mediator (ParserMediator): parser mediator.
registry_key (dfwinreg.WinRegistryKey): Windwos Registry key.
plugin (WindowsRegistryPlugin): Windows Registry plugin.
### ... |
def guess_file_name_stream_type_header(args):
"""
Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:return: filena... | Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:return: filename, file stream, file type, file header | Below is the the instruction that describes the task:
### Input:
Guess filename, file stream, file type, file header from args.
:param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj,
contentype) or 4-tuples (filename, fileobj, contentype, custom_headers).
:ret... |
def compute_checksum(self, payload_offset: Optional[int]=None):
'''Compute and add the checksum data to the record fields.
This function also sets the content length.
'''
if not self.block_file:
self.fields['Content-Length'] = '0'
return
block_hasher = h... | Compute and add the checksum data to the record fields.
This function also sets the content length. | Below is the the instruction that describes the task:
### Input:
Compute and add the checksum data to the record fields.
This function also sets the content length.
### Response:
def compute_checksum(self, payload_offset: Optional[int]=None):
'''Compute and add the checksum data to the record fiel... |
def print_version():
"""
Print out the current version, and at least try to fetch the latest from
PyPi to print alongside it.
It may seem odd that this isn't in globus_cli.version , but it's done this
way to separate concerns over printing the version from looking it up.
"""
latest, current... | Print out the current version, and at least try to fetch the latest from
PyPi to print alongside it.
It may seem odd that this isn't in globus_cli.version , but it's done this
way to separate concerns over printing the version from looking it up. | Below is the the instruction that describes the task:
### Input:
Print out the current version, and at least try to fetch the latest from
PyPi to print alongside it.
It may seem odd that this isn't in globus_cli.version , but it's done this
way to separate concerns over printing the version from lookin... |
def update_tab_label(self, state_m):
"""Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier not in self.tabs and state_identifier ... | Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated | Below is the the instruction that describes the task:
### Input:
Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
### Response:
def update_tab_label(self, state_m):
"""Update all tab labels
:param rafcon.state_machi... |
def initialize_valid_actions(grammar: Grammar,
keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]:
"""
We initialize the valid actions with the global actions. These include the
valid actions that result from the grammar and also those that result from
the tabl... | We initialize the valid actions with the global actions. These include the
valid actions that result from the grammar and also those that result from
the tables provided. The keys represent the nonterminals in the grammar
and the values are lists of the valid actions of that nonterminal. | Below is the the instruction that describes the task:
### Input:
We initialize the valid actions with the global actions. These include the
valid actions that result from the grammar and also those that result from
the tables provided. The keys represent the nonterminals in the grammar
and the values ar... |
def gen_nop():
"""Return a NOP instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg) | Return a NOP instruction. | Below is the the instruction that describes the task:
### Input:
Return a NOP instruction.
### Response:
def gen_nop():
"""Return a NOP instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg) |
def represent_datetime(self, d):
"""
turns a given datetime obj into a string representation.
This will:
1) look if a fixed 'timestamp_format' is given in the config
2) check if a 'timestamp_format' hook is defined
3) use :func:`~alot.helper.pretty_datetime` as fallback
... | turns a given datetime obj into a string representation.
This will:
1) look if a fixed 'timestamp_format' is given in the config
2) check if a 'timestamp_format' hook is defined
3) use :func:`~alot.helper.pretty_datetime` as fallback | Below is the the instruction that describes the task:
### Input:
turns a given datetime obj into a string representation.
This will:
1) look if a fixed 'timestamp_format' is given in the config
2) check if a 'timestamp_format' hook is defined
3) use :func:`~alot.helper.pretty_dateti... |
def create_from_other( Class, other, values=None ):
"""
Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided
"""
m = Class()
m.alphabet = other.alphabet
m.sorted_alphabet = other.sorted_alphabet
m.char... | Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided | Below is the the instruction that describes the task:
### Input:
Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided
### Response:
def create_from_other( Class, other, values=None ):
"""
Create a new Matrix with attributes taken from `... |
def load_data_table(table_name, meta_file, meta):
"""Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict)
"""
... | Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict) | Below is the the instruction that describes the task:
### Input:
Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict... |
def inner_parser(self) -> BaseParser:
"""
Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain ... | Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config | Below is the the instruction that describes the task:
### Input:
Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does n... |
def url_norm (url, encoding=None):
"""Wrapper for url.url_norm() to convert UnicodeError in
LinkCheckerError."""
try:
return urlutil.url_norm(url, encoding=encoding)
except UnicodeError:
msg = _("URL has unparsable domain name: %(name)s") % \
{"name": sys.exc_info()[1]}
... | Wrapper for url.url_norm() to convert UnicodeError in
LinkCheckerError. | Below is the the instruction that describes the task:
### Input:
Wrapper for url.url_norm() to convert UnicodeError in
LinkCheckerError.
### Response:
def url_norm (url, encoding=None):
"""Wrapper for url.url_norm() to convert UnicodeError in
LinkCheckerError."""
try:
return urlutil.url_nor... |
def getvarcol(self, columnname, startrow=0, nrow=-1, rowincr=1):
"""Get the contents of a column or part of it.
It is similar to :func:`getcol`, but the result is returned as a
dict of numpy arrays.
It can deal with a column containing variable shaped arrays.
"""
return... | Get the contents of a column or part of it.
It is similar to :func:`getcol`, but the result is returned as a
dict of numpy arrays.
It can deal with a column containing variable shaped arrays. | Below is the the instruction that describes the task:
### Input:
Get the contents of a column or part of it.
It is similar to :func:`getcol`, but the result is returned as a
dict of numpy arrays.
It can deal with a column containing variable shaped arrays.
### Response:
def getvarcol(self,... |
def DataProcessorsPost(self, parameters):
"""
Create a Data processor in CommonSense.
If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string.
... | Create a Data processor in CommonSense.
If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictonary) - Dictionary containing the details... | Below is the the instruction that describes the task:
### Input:
Create a Data processor in CommonSense.
If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string.
... |
def csv(self, fh):
"""Writes the results data to `fh` in CSV format and returns `fh`.
:param fh: file to write data to
:type fh: file object
:rtype: file object
"""
self._matches.to_csv(fh, encoding='utf-8', float_format='%d',
index=False)
... | Writes the results data to `fh` in CSV format and returns `fh`.
:param fh: file to write data to
:type fh: file object
:rtype: file object | Below is the the instruction that describes the task:
### Input:
Writes the results data to `fh` in CSV format and returns `fh`.
:param fh: file to write data to
:type fh: file object
:rtype: file object
### Response:
def csv(self, fh):
"""Writes the results data to `fh` in CSV for... |
def encode(cls, value):
"""
the list it so it can be stored in redis.
:param value: list
:return: bytes
"""
try:
coerced = [str(v) for v in value]
if coerced == value:
return ",".join(coerced).encode(cls._encoding) if len(
... | the list it so it can be stored in redis.
:param value: list
:return: bytes | Below is the the instruction that describes the task:
### Input:
the list it so it can be stored in redis.
:param value: list
:return: bytes
### Response:
def encode(cls, value):
"""
the list it so it can be stored in redis.
:param value: list
:return: bytes
... |
def annotated(func, name=None):
"""Mark a function as callable from the command line.
This function is meant to be called as decorator. This function
also initializes metadata about the function's arguments that is
built up by the param decorator.
Args:
func (callable): The function that ... | Mark a function as callable from the command line.
This function is meant to be called as decorator. This function
also initializes metadata about the function's arguments that is
built up by the param decorator.
Args:
func (callable): The function that we wish to mark as callable
... | Below is the the instruction that describes the task:
### Input:
Mark a function as callable from the command line.
This function is meant to be called as decorator. This function
also initializes metadata about the function's arguments that is
built up by the param decorator.
Args:
func ... |
def read_cs_g0_contribution(self):
"""
Parse the G0 contribution of NMR chemical shielding.
Returns:
G0 contribution matrix as list of list.
"""
header_pattern = r'^\s+G\=0 CONTRIBUTION TO CHEMICAL SHIFT \(field along BDIR\)\s+$\n' \
... | Parse the G0 contribution of NMR chemical shielding.
Returns:
G0 contribution matrix as list of list. | Below is the the instruction that describes the task:
### Input:
Parse the G0 contribution of NMR chemical shielding.
Returns:
G0 contribution matrix as list of list.
### Response:
def read_cs_g0_contribution(self):
"""
Parse the G0 contribution of NMR chemical shield... |
def translate_argv(raw_args):
"""Enables conversion from system arguments.
Parameters
----------
raw_args : list
Arguments taken raw from the system input.
Returns
-------
kwargs : dict
The input arguments formatted as a kwargs dict.
To use as input, simply use `KQM... | Enables conversion from system arguments.
Parameters
----------
raw_args : list
Arguments taken raw from the system input.
Returns
-------
kwargs : dict
The input arguments formatted as a kwargs dict.
To use as input, simply use `KQMLModule(**kwargs)`. | Below is the the instruction that describes the task:
### Input:
Enables conversion from system arguments.
Parameters
----------
raw_args : list
Arguments taken raw from the system input.
Returns
-------
kwargs : dict
The input arguments formatted as a kwargs dict.
... |
def _factor_generator(n):
"""
From a given natural integer, returns the prime factors and their multiplicity
:param n: Natural integer
:return:
"""
p = prime_factors(n)
factors = {}
for p1 in p:
try:
factors[p1] += 1
except KeyError:
factors[p1] = ... | From a given natural integer, returns the prime factors and their multiplicity
:param n: Natural integer
:return: | Below is the the instruction that describes the task:
### Input:
From a given natural integer, returns the prime factors and their multiplicity
:param n: Natural integer
:return:
### Response:
def _factor_generator(n):
"""
From a given natural integer, returns the prime factors and their multiplici... |
def create_deployment(applicationName=None, deploymentGroupName=None, revision=None, deploymentConfigName=None, description=None, ignoreApplicationStopFailures=None, targetInstances=None, autoRollbackConfiguration=None, updateOutdatedInstancesOnly=None, fileExistsBehavior=None):
"""
Deploys an application revis... | Deploys an application revision through the specified deployment group.
See also: AWS API Documentation
:example: response = client.create_deployment(
applicationName='string',
deploymentGroupName='string',
revision={
'revisionType': 'S3'|'GitHub',
's3Lo... | Below is the the instruction that describes the task:
### Input:
Deploys an application revision through the specified deployment group.
See also: AWS API Documentation
:example: response = client.create_deployment(
applicationName='string',
deploymentGroupName='string',
re... |
def reverse(self, lat, lon, result_type=None, location_type=None,
language=None, sensor=None):
"""Reverse geocode with given latitude and longitude.
:param lat: latitude of queried point
:param lon: longitude of queried point
:param result_type: list of result_type for f... | Reverse geocode with given latitude and longitude.
:param lat: latitude of queried point
:param lon: longitude of queried point
:param result_type: list of result_type for filtered search.
Accepted values:
https://developers.google.com/maps/documentation/geocoding/intr... | Below is the the instruction that describes the task:
### Input:
Reverse geocode with given latitude and longitude.
:param lat: latitude of queried point
:param lon: longitude of queried point
:param result_type: list of result_type for filtered search.
Accepted values:
... |
def add_package(self, pkg, action_type="Install"):
"""Add a Package object to the policy with action=install.
Args:
pkg: A Package object to add.
action_type (str, optional): One of "Install", "Cache", or
"Install Cached". Defaults to "Install".
"""
... | Add a Package object to the policy with action=install.
Args:
pkg: A Package object to add.
action_type (str, optional): One of "Install", "Cache", or
"Install Cached". Defaults to "Install". | Below is the the instruction that describes the task:
### Input:
Add a Package object to the policy with action=install.
Args:
pkg: A Package object to add.
action_type (str, optional): One of "Install", "Cache", or
"Install Cached". Defaults to "Install".
### Respo... |
def get_results(cmd):
"""
def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
including the newline characters
... | def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
including the newline characters | Below is the the instruction that describes the task:
### Input:
def get_results(cmd: list) -> str:
return lines
Get the ping results using fping.
:param cmd: List - the fping command and its options
:return: String - raw string output containing csv fping results
includi... |
def _image_loop(self):
"""Retrieve an iterable of images either with, or without a progress bar."""
if self.progress_bar and 'tqdm' in self.progress_bar.lower():
return tqdm(self.imgs, desc='Saving PNGs as flat PDFs', total=len(self.imgs), unit='PDFs')
else:
return self.i... | Retrieve an iterable of images either with, or without a progress bar. | Below is the the instruction that describes the task:
### Input:
Retrieve an iterable of images either with, or without a progress bar.
### Response:
def _image_loop(self):
"""Retrieve an iterable of images either with, or without a progress bar."""
if self.progress_bar and 'tqdm' in self.progress_... |
def store_reg(self, value, reg_type, reg_name, name=''):
"""
Store an LLVM value inside a register
Example: store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax")
"""
ftype = types.FunctionType(types.VoidType(), [reg_type])
return self.asm(ftype, "", "{%s}" % ... | Store an LLVM value inside a register
Example: store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax") | Below is the the instruction that describes the task:
### Input:
Store an LLVM value inside a register
Example: store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax")
### Response:
def store_reg(self, value, reg_type, reg_name, name=''):
"""
Store an LLVM value inside a register... |
def deleteUnused(self):
""" Delete any old snapshots in path, if not kept. """
if self.dryrun:
self._client.listUnused()
else:
self._client.deleteUnused() | Delete any old snapshots in path, if not kept. | Below is the the instruction that describes the task:
### Input:
Delete any old snapshots in path, if not kept.
### Response:
def deleteUnused(self):
""" Delete any old snapshots in path, if not kept. """
if self.dryrun:
self._client.listUnused()
else:
self._client.d... |
def is_correct(self): # pylint: disable=too-many-branches, too-many-statements, too-many-locals
"""Check if all elements got a good configuration
:return: True if the configuration is correct else False
:rtype: bool
"""
logger.info('Running pre-flight check on configuration dat... | Check if all elements got a good configuration
:return: True if the configuration is correct else False
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if all elements got a good configuration
:return: True if the configuration is correct else False
:rtype: bool
### Response:
def is_correct(self): # pylint: disable=too-many-branches, too-many-statements, too-many-locals
... |
def _rest_request_to_json(self, url, instance, object_path, tags, *args, **kwargs):
"""
Query the given URL and return the JSON response
"""
service_check_tags = ['url:{}'.format(self._get_url_base(url))] + tags
service_check_tags = list(set(service_check_tags))
if objec... | Query the given URL and return the JSON response | Below is the the instruction that describes the task:
### Input:
Query the given URL and return the JSON response
### Response:
def _rest_request_to_json(self, url, instance, object_path, tags, *args, **kwargs):
"""
Query the given URL and return the JSON response
"""
service_check_... |
def _AcceptResponses(self, expected_header, info_cb, timeout_ms=None):
"""Accepts responses until the expected header or a FAIL.
Args:
expected_header: OKAY or DATA
info_cb: Optional callback for text sent from the bootloader.
timeout_ms: Timeout in milliseconds to wait fo... | Accepts responses until the expected header or a FAIL.
Args:
expected_header: OKAY or DATA
info_cb: Optional callback for text sent from the bootloader.
timeout_ms: Timeout in milliseconds to wait for each response.
Raises:
FastbootStateMismatch: Fastboot respon... | Below is the the instruction that describes the task:
### Input:
Accepts responses until the expected header or a FAIL.
Args:
expected_header: OKAY or DATA
info_cb: Optional callback for text sent from the bootloader.
timeout_ms: Timeout in milliseconds to wait for each respon... |
def _get_fqn(cls, path):
"""get full qualified name as list of strings
:return: (list - str) of path segments from top package to given path
"""
name_list = [path.stem]
current_path = path
# move to parent path until parent path is a python package
while cls.is_pk... | get full qualified name as list of strings
:return: (list - str) of path segments from top package to given path | Below is the the instruction that describes the task:
### Input:
get full qualified name as list of strings
:return: (list - str) of path segments from top package to given path
### Response:
def _get_fqn(cls, path):
"""get full qualified name as list of strings
:return: (list - str) of pat... |
def dimension(self):
"""Compute the dimension of the sampling space and identify the slices
belonging to each stochastic.
"""
self.dim = 0
self._slices = {}
for stochastic in self.stochastics:
if isinstance(stochastic.value, np.matrix):
p_len =... | Compute the dimension of the sampling space and identify the slices
belonging to each stochastic. | Below is the the instruction that describes the task:
### Input:
Compute the dimension of the sampling space and identify the slices
belonging to each stochastic.
### Response:
def dimension(self):
"""Compute the dimension of the sampling space and identify the slices
belonging to each stoc... |
def _is_whitelisted(self, email):
"""Check if an email is in the whitelist. If there's no whitelist,
it's assumed it's not whitelisted."""
return hasattr(settings, "SAFE_EMAIL_WHITELIST") and \
any(re.match(m, email) for m in settings.SAFE_EMAIL_WHITELIST) | Check if an email is in the whitelist. If there's no whitelist,
it's assumed it's not whitelisted. | Below is the the instruction that describes the task:
### Input:
Check if an email is in the whitelist. If there's no whitelist,
it's assumed it's not whitelisted.
### Response:
def _is_whitelisted(self, email):
"""Check if an email is in the whitelist. If there's no whitelist,
it's assumed... |
def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return "%s=%s" % (name,
":".join("%s=%s" % (k, v) for k, v in params.items())) | Build a string to call a FFMpeg filter. | Below is the the instruction that describes the task:
### Input:
Build a string to call a FFMpeg filter.
### Response:
def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return "%s=%s" % (name,
":".join("%s=%s" % (k, v) for k, v in params.items())) |
def call_api(self, request_data, service, action, idempotency=False,
**kwargs):
"""This will call the adyen api. username, password, merchant_account,
and platform are pulled from root module level and or self object.
AdyenResult will be returned on 200 response. Otherwise, an e... | This will call the adyen api. username, password, merchant_account,
and platform are pulled from root module level and or self object.
AdyenResult will be returned on 200 response. Otherwise, an exception
is raised.
Args:
request_data (dict): The dictionary of the request to... | Below is the the instruction that describes the task:
### Input:
This will call the adyen api. username, password, merchant_account,
and platform are pulled from root module level and or self object.
AdyenResult will be returned on 200 response. Otherwise, an exception
is raised.
Ar... |
def cross(self, vec):
"""Cross product with another vector"""
if not isinstance(vec, self.__class__):
raise TypeError('Cross product operand must be a vector')
return Vector3(0, 0, np.asscalar(np.cross(self, vec))) | Cross product with another vector | Below is the the instruction that describes the task:
### Input:
Cross product with another vector
### Response:
def cross(self, vec):
"""Cross product with another vector"""
if not isinstance(vec, self.__class__):
raise TypeError('Cross product operand must be a vector')
return... |
def hpx_to_axes(h, npix):
""" Generate a sequence of bin edge vectors corresponding to the
axes of a HPX object."""
x = h.ebins
z = np.arange(npix[-1] + 1)
return x, z | Generate a sequence of bin edge vectors corresponding to the
axes of a HPX object. | Below is the the instruction that describes the task:
### Input:
Generate a sequence of bin edge vectors corresponding to the
axes of a HPX object.
### Response:
def hpx_to_axes(h, npix):
""" Generate a sequence of bin edge vectors corresponding to the
axes of a HPX object."""
x = h.ebins
z = n... |
def iter_coords(obj):
"""
Returns all the coordinate tuples from a geometry or feature.
"""
if isinstance(obj, (tuple, list)):
coords = obj
elif 'features' in obj:
coords = [geom['geometry']['coordinates'] for geom in obj['features']]
elif 'geometry' in obj:
coords = obj... | Returns all the coordinate tuples from a geometry or feature. | Below is the the instruction that describes the task:
### Input:
Returns all the coordinate tuples from a geometry or feature.
### Response:
def iter_coords(obj):
"""
Returns all the coordinate tuples from a geometry or feature.
"""
if isinstance(obj, (tuple, list)):
coords = obj
elif ... |
def make_threshold_gradient(self, py3, thresholds, size=100):
"""
Given a thresholds list, creates a gradient list that covers the range
of the thresholds.
The number of colors in the gradient is limited by size.
Because of how the range is split the exact number of colors in th... | Given a thresholds list, creates a gradient list that covers the range
of the thresholds.
The number of colors in the gradient is limited by size.
Because of how the range is split the exact number of colors in the
gradient cannot be guaranteed. | Below is the the instruction that describes the task:
### Input:
Given a thresholds list, creates a gradient list that covers the range
of the thresholds.
The number of colors in the gradient is limited by size.
Because of how the range is split the exact number of colors in the
grad... |
def _record_extension(self, bank_id, key, value):
"""
To structure a record extension property bean
"""
record_bean = {
'value': value,
'displayName': self._text_bean(key),
'description': self._text_bean(key),
'displayLabel': self._text_bea... | To structure a record extension property bean | Below is the the instruction that describes the task:
### Input:
To structure a record extension property bean
### Response:
def _record_extension(self, bank_id, key, value):
"""
To structure a record extension property bean
"""
record_bean = {
'value': value,
... |
def memoizemethod(method):
"""
Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... @memoizemethod
... ... | Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... @memoizemethod
... def foo(self, x, y=0):
... prin... | Below is the the instruction that describes the task:
### Input:
Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
.... |
def or_filter(self, filter_or_string, *args, **kwargs):
"""
Convenience method to delegate to the root_filter to generate an `or`
clause.
:return: :class:`~es_fluent.builder.QueryBuilder`
"""
self.root_filter.or_filter(filter_or_string, *args, **kwargs)
return se... | Convenience method to delegate to the root_filter to generate an `or`
clause.
:return: :class:`~es_fluent.builder.QueryBuilder` | Below is the the instruction that describes the task:
### Input:
Convenience method to delegate to the root_filter to generate an `or`
clause.
:return: :class:`~es_fluent.builder.QueryBuilder`
### Response:
def or_filter(self, filter_or_string, *args, **kwargs):
"""
Convenience met... |
def get_fd(self, fd):
"""
Looks up the SimFileDescriptor associated with the given number (an AST).
If the number is concrete and does not map to anything, return None.
If the number is symbolic, constrain it to an open fd and create a new file for it.
"""
try:
... | Looks up the SimFileDescriptor associated with the given number (an AST).
If the number is concrete and does not map to anything, return None.
If the number is symbolic, constrain it to an open fd and create a new file for it. | Below is the the instruction that describes the task:
### Input:
Looks up the SimFileDescriptor associated with the given number (an AST).
If the number is concrete and does not map to anything, return None.
If the number is symbolic, constrain it to an open fd and create a new file for it.
### Resp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.