code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def write_sig(self):
'''Write signature to sig store'''
if not self._md5:
self._md5 = fileMD5(self)
with open(self.sig_file(), 'w') as sig:
sig.write(
f'{os.path.getmtime(self)}\t{os.path.getsize(self)}\t{self._md5}'
) | Write signature to sig store | Below is the the instruction that describes the task:
### Input:
Write signature to sig store
### Response:
def write_sig(self):
'''Write signature to sig store'''
if not self._md5:
self._md5 = fileMD5(self)
with open(self.sig_file(), 'w') as sig:
sig.write(
... |
def get_balance():
"""
Get the latest balance(s) for a single User.
Currently no search parameters are supported. All balances returned.
---
responses:
'200':
description: the User's balance(s)
schema:
items:
$ref: '#/definitions/Balance'
type: a... | Get the latest balance(s) for a single User.
Currently no search parameters are supported. All balances returned.
---
responses:
'200':
description: the User's balance(s)
schema:
items:
$ref: '#/definitions/Balance'
type: array
default:
des... | Below is the the instruction that describes the task:
### Input:
Get the latest balance(s) for a single User.
Currently no search parameters are supported. All balances returned.
---
responses:
'200':
description: the User's balance(s)
schema:
items:
$ref: '#/... |
def initialize(self, training_info, model, environment, device):
""" Initialize policy gradient from reinforcer settings """
self.target_model = self.model_factory.instantiate(action_space=environment.action_space).to(device)
self.target_model.load_state_dict(model.state_dict())
self.tar... | Initialize policy gradient from reinforcer settings | Below is the the instruction that describes the task:
### Input:
Initialize policy gradient from reinforcer settings
### Response:
def initialize(self, training_info, model, environment, device):
""" Initialize policy gradient from reinforcer settings """
self.target_model = self.model_factory.inst... |
def filepath( self, validated = False ):
"""
Returns the filepath for this widget. If the validated flag is set \
then this method will only return if the file or folder actually \
exists for this path. In the case of a SaveFile, only the base folder \
needs to exist on the sys... | Returns the filepath for this widget. If the validated flag is set \
then this method will only return if the file or folder actually \
exists for this path. In the case of a SaveFile, only the base folder \
needs to exist on the system, in other modes the actual filepath must \
exist.... | Below is the the instruction that describes the task:
### Input:
Returns the filepath for this widget. If the validated flag is set \
then this method will only return if the file or folder actually \
exists for this path. In the case of a SaveFile, only the base folder \
needs to exist on... |
def build_param_schema(schema, param_type):
"""Turn a swagger endpoint schema into an equivalent one to validate our
request.
As an example, this would take this swagger schema:
{
"paramType": "query",
"name": "query",
"description": "Location to query",
... | Turn a swagger endpoint schema into an equivalent one to validate our
request.
As an example, this would take this swagger schema:
{
"paramType": "query",
"name": "query",
"description": "Location to query",
"type": "string",
"required": true
... | Below is the the instruction that describes the task:
### Input:
Turn a swagger endpoint schema into an equivalent one to validate our
request.
As an example, this would take this swagger schema:
{
"paramType": "query",
"name": "query",
"description": "Location t... |
def process_task(self):
"""This function is called when something has taken too long."""
if _debug: ClientSSM._debug("process_task")
if self.state == SEGMENTED_REQUEST:
self.segmented_request_timeout()
elif self.state == AWAIT_CONFIRMATION:
self.await_confirmatio... | This function is called when something has taken too long. | Below is the the instruction that describes the task:
### Input:
This function is called when something has taken too long.
### Response:
def process_task(self):
"""This function is called when something has taken too long."""
if _debug: ClientSSM._debug("process_task")
if self.state == SE... |
def copy(self):
"""Correctly copies the `Record`
# Returns
`Record`
> A completely decoupled copy of the original
"""
c = copy.copy(self)
c._fieldDict = c._fieldDict.copy()
return c | Correctly copies the `Record`
# Returns
`Record`
> A completely decoupled copy of the original | Below is the the instruction that describes the task:
### Input:
Correctly copies the `Record`
# Returns
`Record`
> A completely decoupled copy of the original
### Response:
def copy(self):
"""Correctly copies the `Record`
# Returns
`Record`
> A complet... |
def Ctrl_c(self, dl = 0):
"""Ctrl + c 复制
"""
self.Delay(dl)
self.keyboard.press_key(self.keyboard.control_key)
self.keyboard.tap_key("c")
self.keyboard.release_key(self.keyboard.control_key) | Ctrl + c 复制 | Below is the the instruction that describes the task:
### Input:
Ctrl + c 复制
### Response:
def Ctrl_c(self, dl = 0):
"""Ctrl + c 复制
"""
self.Delay(dl)
self.keyboard.press_key(self.keyboard.control_key)
self.keyboard.tap_key("c")
self.keyboard.release_key(self.keyboar... |
def pnum_to_group(mesh_shape, group_dims, pnum):
"""Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer
"""
coord = pnum_to_processor_coordinates(mesh_shape, pnum)
remaining_shape = ... | Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer | Below is the the instruction that describes the task:
### Input:
Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer
### Response:
def pnum_to_group(mesh_shape, group_dims, pnum):
"""... |
def get_branching_nodes(self):
"""
Returns all nodes that has an out degree >= 2
"""
nodes = set()
for n in self.graph.nodes():
if self.graph.out_degree(n) >= 2:
nodes.add(n)
return nodes | Returns all nodes that has an out degree >= 2 | Below is the the instruction that describes the task:
### Input:
Returns all nodes that has an out degree >= 2
### Response:
def get_branching_nodes(self):
"""
Returns all nodes that has an out degree >= 2
"""
nodes = set()
for n in self.graph.nodes():
if self.gr... |
def _daemon_thread(*a, **kw):
"""
Create a `threading.Thread`, but always set ``daemon``.
"""
thread = Thread(*a, **kw)
thread.daemon = True
return thread | Create a `threading.Thread`, but always set ``daemon``. | Below is the the instruction that describes the task:
### Input:
Create a `threading.Thread`, but always set ``daemon``.
### Response:
def _daemon_thread(*a, **kw):
"""
Create a `threading.Thread`, but always set ``daemon``.
"""
thread = Thread(*a, **kw)
thread.daemon = True
return thread |
def _load_hardware_key(keyfile):
""" Load a 256-bit key, similar to stored in efuse, from a file
192-bit keys will be extended to 256-bit using the same algorithm used
by hardware if 3/4 Coding Scheme is set.
"""
key = keyfile.read()
if len(key) not in [24, 32]:
raise esptool.FatalError... | Load a 256-bit key, similar to stored in efuse, from a file
192-bit keys will be extended to 256-bit using the same algorithm used
by hardware if 3/4 Coding Scheme is set. | Below is the the instruction that describes the task:
### Input:
Load a 256-bit key, similar to stored in efuse, from a file
192-bit keys will be extended to 256-bit using the same algorithm used
by hardware if 3/4 Coding Scheme is set.
### Response:
def _load_hardware_key(keyfile):
""" Load a 256-bit... |
def update(self):
"""
Stops and starts the framework, if the framework is active.
:raise BundleException: Something wrong occurred while stopping or
starting the framework.
"""
with self._lock:
if self._state == Bundle.ACTIVE:
... | Stops and starts the framework, if the framework is active.
:raise BundleException: Something wrong occurred while stopping or
starting the framework. | Below is the the instruction that describes the task:
### Input:
Stops and starts the framework, if the framework is active.
:raise BundleException: Something wrong occurred while stopping or
starting the framework.
### Response:
def update(self):
"""
Stops ... |
def query(self, session=None):
'''Returns a new :class:`Query` for :attr:`Manager.model`.'''
if session is None or session.router is not self.router:
session = self.session()
return session.query(self.model) | Returns a new :class:`Query` for :attr:`Manager.model`. | Below is the the instruction that describes the task:
### Input:
Returns a new :class:`Query` for :attr:`Manager.model`.
### Response:
def query(self, session=None):
'''Returns a new :class:`Query` for :attr:`Manager.model`.'''
if session is None or session.router is not self.router:
... |
def get_chains(self):
"""Return an ordered list of the `Chain_#` directories in the db
directory."""
chains = []
try:
content = os.listdir(self._directory)
for c in content:
if os.path.isdir(os.path.join(self._directory, c)) and c.startswith(
... | Return an ordered list of the `Chain_#` directories in the db
directory. | Below is the the instruction that describes the task:
### Input:
Return an ordered list of the `Chain_#` directories in the db
directory.
### Response:
def get_chains(self):
"""Return an ordered list of the `Chain_#` directories in the db
directory."""
chains = []
try:
... |
def MatchRouter(self, request):
"""Returns a router for a given HTTP request."""
router = api_auth_manager.API_AUTH_MGR.GetRouterForUser(request.user)
routing_map = self._GetRoutingMap(router)
matcher = routing_map.bind(
"%s:%s" %
(request.environ["SERVER_NAME"], request.environ["SERVER... | Returns a router for a given HTTP request. | Below is the the instruction that describes the task:
### Input:
Returns a router for a given HTTP request.
### Response:
def MatchRouter(self, request):
"""Returns a router for a given HTTP request."""
router = api_auth_manager.API_AUTH_MGR.GetRouterForUser(request.user)
routing_map = self._GetRouting... |
def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Loan (or your own itemclass) object for each
one, initializing them one at a time, and changing the attrs
... | The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Loan (or your own itemclass) object for each
one, initializing them one at a time, and changing the attrs
attribute (which just holds a list of plain dicti... | Below is the the instruction that describes the task:
### Input:
The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Loan (or your own itemclass) object for each
one, initializing them one at a time, and changin... |
def xml_equal(xml_file1, xml_file2):
"""
Parse xml and convert to a canonical string representation so we don't
have to worry about semantically meaningless differences
"""
def canonical(xml_file):
# poor man's canonicalization, since we don't want to install
# external packages jus... | Parse xml and convert to a canonical string representation so we don't
have to worry about semantically meaningless differences | Below is the the instruction that describes the task:
### Input:
Parse xml and convert to a canonical string representation so we don't
have to worry about semantically meaningless differences
### Response:
def xml_equal(xml_file1, xml_file2):
"""
Parse xml and convert to a canonical string representat... |
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
"""
Perform a reduction operation.
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
"""
delegate = self._v... | Perform a reduction operation.
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object. | Below is the the instruction that describes the task:
### Input:
Perform a reduction operation.
If we have an ndarray as a value, then simply perform the operation,
otherwise delegate to the object.
### Response:
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
f... |
def update(self, message, content, branch=None, committer=None,
author=None):
"""Update this file.
:param str message: (required), commit message to describe the update
:param str content: (required), content to update the file with
:param str branch: (optional), branch w... | Update this file.
:param str message: (required), commit message to describe the update
:param str content: (required), content to update the file with
:param str branch: (optional), branch where the file exists.
Defaults to the default branch of the repository.
:param dict ... | Below is the the instruction that describes the task:
### Input:
Update this file.
:param str message: (required), commit message to describe the update
:param str content: (required), content to update the file with
:param str branch: (optional), branch where the file exists.
D... |
def update_route53(self):
"""Update list of Route53 DNS Zones and their records for the account
Returns:
`None`
"""
self.log.debug('Updating Route53 information for {}'.format(self.account))
# region Update zones
existing_zones = DNSZone.get_all(self.account... | Update list of Route53 DNS Zones and their records for the account
Returns:
`None` | Below is the the instruction that describes the task:
### Input:
Update list of Route53 DNS Zones and their records for the account
Returns:
`None`
### Response:
def update_route53(self):
"""Update list of Route53 DNS Zones and their records for the account
Returns:
... |
def set_hyperparameters(self, hyperparameters):
"""Set new hyperparameters.
Only the specified hyperparameters are modified, so any other
hyperparameter keeps the value that had been previously given.
If necessary, a new instance of the primitive is created.
Args:
... | Set new hyperparameters.
Only the specified hyperparameters are modified, so any other
hyperparameter keeps the value that had been previously given.
If necessary, a new instance of the primitive is created.
Args:
hyperparameters (dict): Dictionary containing as keys the n... | Below is the the instruction that describes the task:
### Input:
Set new hyperparameters.
Only the specified hyperparameters are modified, so any other
hyperparameter keeps the value that had been previously given.
If necessary, a new instance of the primitive is created.
Args:
... |
def __print(self, msg):
"""Shortcut for printing with the distutils logger."""
self.announce(msg, level=distutils.log.INFO) | Shortcut for printing with the distutils logger. | Below is the the instruction that describes the task:
### Input:
Shortcut for printing with the distutils logger.
### Response:
def __print(self, msg):
"""Shortcut for printing with the distutils logger."""
self.announce(msg, level=distutils.log.INFO) |
def save_coeffs(coeffs, out_dir=''):
'''Save calibration coefficients to HDF5 files.'''
for platform in coeffs.keys():
fname = os.path.join(out_dir, "%s_calibration_data.h5" % platform)
fid = h5py.File(fname, 'w')
for chan in coeffs[platform].keys():
fid.create_group... | Save calibration coefficients to HDF5 files. | Below is the the instruction that describes the task:
### Input:
Save calibration coefficients to HDF5 files.
### Response:
def save_coeffs(coeffs, out_dir=''):
'''Save calibration coefficients to HDF5 files.'''
for platform in coeffs.keys():
fname = os.path.join(out_dir, "%s_calibration_data.h5" %... |
def get(self, *args, **kwargs):
"""
Checks the cache to see if there's a cached entry for this pk. If not, fetches
using super then stores the result in cache.
Most of the logic here was gathered from a careful reading of
``django.db.models.sql.query.add_filter``
"""
... | Checks the cache to see if there's a cached entry for this pk. If not, fetches
using super then stores the result in cache.
Most of the logic here was gathered from a careful reading of
``django.db.models.sql.query.add_filter`` | Below is the the instruction that describes the task:
### Input:
Checks the cache to see if there's a cached entry for this pk. If not, fetches
using super then stores the result in cache.
Most of the logic here was gathered from a careful reading of
``django.db.models.sql.query.add_filt... |
def make_id(self):
"""Create a new URL id that is unique to the parent container"""
if self.url_id is None: # Set id only if empty
self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)],
self.__class__.parent == self.parent) | Create a new URL id that is unique to the parent container | Below is the the instruction that describes the task:
### Input:
Create a new URL id that is unique to the parent container
### Response:
def make_id(self):
"""Create a new URL id that is unique to the parent container"""
if self.url_id is None: # Set id only if empty
self.url_id = sel... |
def delete(self, obj):
"""
Returns
object: full copy of new obj
"""
full = deepcopy(obj)
frag = full
parts, last = self.parts[:-1], self.parts[-1]
for part in parts:
if isinstance(frag, dict):
frag = frag[part]
e... | Returns
object: full copy of new obj | Below is the the instruction that describes the task:
### Input:
Returns
object: full copy of new obj
### Response:
def delete(self, obj):
"""
Returns
object: full copy of new obj
"""
full = deepcopy(obj)
frag = full
parts, last = self.parts[:... |
def new_dcos_user(user_id, password):
""" Provides a context with a newly created user.
"""
o_token = dcos_acs_token()
shakedown.add_user(user_id, password, user_id)
token = shakedown.authenticate(user_id, password)
dcos.config.set_val('core.dcos_acs_token', token)
yield
dcos.config.set... | Provides a context with a newly created user. | Below is the the instruction that describes the task:
### Input:
Provides a context with a newly created user.
### Response:
def new_dcos_user(user_id, password):
""" Provides a context with a newly created user.
"""
o_token = dcos_acs_token()
shakedown.add_user(user_id, password, user_id)
tok... |
def expand_specializations(session, class_names):
"""
Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names.
"""
result = []
for class_name in class_names:
specialization = Specializatio... | Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names. | Below is the the instruction that describes the task:
### Input:
Checks whether any given name is not a class but a specialization.
If it's a specialization, expand the list of class names with the child
class names.
### Response:
def expand_specializations(session, class_names):
"""
Checks whethe... |
async def request(self):
'''Perform the Http request to the upstream server
'''
request_headers = self.request_headers()
environ = self.environ
method = environ['REQUEST_METHOD']
data = None
if method in ENCODE_BODY_METHODS:
data = DataIterator(self)
... | Perform the Http request to the upstream server | Below is the the instruction that describes the task:
### Input:
Perform the Http request to the upstream server
### Response:
async def request(self):
'''Perform the Http request to the upstream server
'''
request_headers = self.request_headers()
environ = self.environ
meth... |
def mass_send_message(self, msg):
"""Send a message to all connected clients.
Notes
-----
This method can only be called in the IOLoop thread.
"""
for stream in self._connections.keys():
if not stream.closed():
# Don't cause noise by trying t... | Send a message to all connected clients.
Notes
-----
This method can only be called in the IOLoop thread. | Below is the the instruction that describes the task:
### Input:
Send a message to all connected clients.
Notes
-----
This method can only be called in the IOLoop thread.
### Response:
def mass_send_message(self, msg):
"""Send a message to all connected clients.
Notes
... |
def create_examples(candidate_dialog_paths, examples_num, creator_function):
"""
Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example.
:param candidate_dialog_paths:
:param creator_function:
:return:
"""
i = 0
examples = []
un... | Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example.
:param candidate_dialog_paths:
:param creator_function:
:return: | Below is the the instruction that describes the task:
### Input:
Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example.
:param candidate_dialog_paths:
:param creator_function:
:return:
### Response:
def create_examples(candidate_dialog_paths, exa... |
def discover_group(group, separator="/", exclude=None):
"""Produce a list of all services and their addresses in a group
A group is an optional form of namespace within the discovery mechanism.
If an advertised name has the form <group><sep><name> it is deemed to
belong to <group>. Note that the se... | Produce a list of all services and their addresses in a group
A group is an optional form of namespace within the discovery mechanism.
If an advertised name has the form <group><sep><name> it is deemed to
belong to <group>. Note that the service's name is still the full
string <group><sep><name>. T... | Below is the the instruction that describes the task:
### Input:
Produce a list of all services and their addresses in a group
A group is an optional form of namespace within the discovery mechanism.
If an advertised name has the form <group><sep><name> it is deemed to
belong to <group>. Note that ... |
def shuffle_and_batch_data(dataset,
target_names,
features_info,
training,
num_devices,
shuffle_buffer_size=1024,
preprocess_fun=no_preprocess):
"""Shuffle ... | Shuffle and batch the given dataset. | Below is the the instruction that describes the task:
### Input:
Shuffle and batch the given dataset.
### Response:
def shuffle_and_batch_data(dataset,
target_names,
features_info,
training,
num_devices,
... |
def get_form(self, form_class):
"""Returns an instance of the form to be used in this view."""
if not hasattr(self, '_form'):
kwargs = self.get_form_kwargs()
self._form = form_class(instance=self.object, **kwargs)
return self._form | Returns an instance of the form to be used in this view. | Below is the the instruction that describes the task:
### Input:
Returns an instance of the form to be used in this view.
### Response:
def get_form(self, form_class):
"""Returns an instance of the form to be used in this view."""
if not hasattr(self, '_form'):
kwargs = self.get_form_kw... |
def get_data_ttl(self, use_cached=True):
"""Retrieve the dataTTL for this stream
The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream.
A data point expires after the configured amount of time and is automatically deleted.
:param bool use_cached: If... | Retrieve the dataTTL for this stream
The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream.
A data point expires after the configured amount of time and is automatically deleted.
:param bool use_cached: If False, the function will always request the latest ... | Below is the the instruction that describes the task:
### Input:
Retrieve the dataTTL for this stream
The dataTtl is the time to live (TTL) in seconds for data points stored in the data stream.
A data point expires after the configured amount of time and is automatically deleted.
:param bo... |
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
'''
content = open(filename).read()
return re.sub(r'\.\.\s? code-block::\s*(\w|\+)+', '::', content) | Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive | Below is the the instruction that describes the task:
### Input:
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
### Response:
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directi... |
def create_many(
project: 'projects.Project',
include_paths: typing.List[str]
) -> COMPONENT:
"""
Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of re... | Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or
directories that should be included in the project
:retu... | Below is the the instruction that describes the task:
### Input:
Creates a single COMPONENT instance for all of the specified project
include paths
:param project:
Project where the components reside
:param include_paths:
A list of relative paths within the project directory to files or... |
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
"""Return a list of nics comprising a given bridge on the system."""
brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge)
return [x.split('/')[-1] for x in glob.glob(brif_regex)] | Return a list of nics comprising a given bridge on the system. | Below is the the instruction that describes the task:
### Input:
Return a list of nics comprising a given bridge on the system.
### Response:
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'):
"""Return a list of nics comprising a given bridge on the system."""
brif_regex = "%s/%s/brif/*" % ... |
def pack(self, value=None):
"""Pack the value as a binary representation.
:attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
After that, :attr:`data`'s value is restored.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.ex... | Pack the value as a binary representation.
:attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
After that, :attr:`data`'s value is restored.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.exceptions.PackException`: If pack fails. | Below is the the instruction that describes the task:
### Input:
Pack the value as a binary representation.
:attr:`data` is packed before the calling :meth:`.GenericMessage.pack`.
After that, :attr:`data`'s value is restored.
Returns:
bytes: The binary representation.
... |
def open(self, mode='r', buffering=-1, encoding=None,
errors=None, newline=None):
"""
Open the given Artifactory URI and return a file-like object
HTTPResponse, as if it was a regular filesystem object.
The only difference is that this object doesn't support seek()
"... | Open the given Artifactory URI and return a file-like object
HTTPResponse, as if it was a regular filesystem object.
The only difference is that this object doesn't support seek() | Below is the the instruction that describes the task:
### Input:
Open the given Artifactory URI and return a file-like object
HTTPResponse, as if it was a regular filesystem object.
The only difference is that this object doesn't support seek()
### Response:
def open(self, mode='r', buffering=-1, e... |
def get_neighbors_in_shell(self, origin, r, dr, include_index=False, include_image=False):
"""
Returns all sites in a shell centered on origin (coords) between radii
r-dr and r+dr.
Args:
origin (3x1 array): Cartesian coordinates of center of sphere.
r (float): In... | Returns all sites in a shell centered on origin (coords) between radii
r-dr and r+dr.
Args:
origin (3x1 array): Cartesian coordinates of center of sphere.
r (float): Inner radius of shell.
dr (float): Width of shell.
include_index (bool): Whether to inclu... | Below is the the instruction that describes the task:
### Input:
Returns all sites in a shell centered on origin (coords) between radii
r-dr and r+dr.
Args:
origin (3x1 array): Cartesian coordinates of center of sphere.
r (float): Inner radius of shell.
dr (float... |
def _write_strain_functional_genes(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False):
"""Create strain functional genes json file"""
func_genes_path = op.join(self.model_dir, '{}_funcgenes.json'.format(strain_id))
if ssbio.utils.force_rerun(flag=force_rerun, outfile=func_ge... | Create strain functional genes json file | Below is the the instruction that describes the task:
### Input:
Create strain functional genes json file
### Response:
def _write_strain_functional_genes(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False):
"""Create strain functional genes json file"""
func_genes_path = op.join... |
def subnet2block(subnet):
"""Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.0.0', '127.255.255.255')
>>> sub... | Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.0.0', '127.255.255.255')
>>> subnet2block('127.0.1/255.255')
... | Below is the the instruction that describes the task:
### Input:
Convert a dotted-quad ip address including a netmask into a tuple
containing the network block start and end addresses.
>>> subnet2block('127.0.0.1/255.255.255.255')
('127.0.0.1', '127.0.0.1')
>>> subnet2block('127/255')
('127.0.... |
def edit_poll(args):
"""Edits a poll."""
if not args.isadmin:
return "Nope, not gonna do it."
msg = args.msg.split(maxsplit=1)
if len(msg) < 2:
return "Syntax: !vote edit <pollnum> <question>"
if not msg[0].isdigit():
return "Not A Valid Positive Integer."
pid = int(msg[0... | Edits a poll. | Below is the the instruction that describes the task:
### Input:
Edits a poll.
### Response:
def edit_poll(args):
"""Edits a poll."""
if not args.isadmin:
return "Nope, not gonna do it."
msg = args.msg.split(maxsplit=1)
if len(msg) < 2:
return "Syntax: !vote edit <pollnum> <question... |
def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any:
"""Logs the time spent while running the task."""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
start = monotonic()
try:
return task.apply(*args, **kwargs)
... | Logs the time spent while running the task. | Below is the the instruction that describes the task:
### Input:
Logs the time spent while running the task.
### Response:
def _apply_task(task: Task, args: Tuple, kwargs: Dict[str, Any]) -> Any:
"""Logs the time spent while running the task."""
if args is None:
args = ()
if kwa... |
async def update_flags(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
flag_set: FrozenSet[Flag],
mode: FlagOp = FlagOp.REPLACE) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
"""Update... | Update the flags for the given set of messages.
See Also:
`RFC 3501 6.4.6.
<https://tools.ietf.org/html/rfc3501#section-6.4.6>`_
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
flag_set: ... | Below is the the instruction that describes the task:
### Input:
Update the flags for the given set of messages.
See Also:
`RFC 3501 6.4.6.
<https://tools.ietf.org/html/rfc3501#section-6.4.6>`_
Args:
selected: The selected mailbox session.
sequence_s... |
def _inverse_permutation_indices(positions):
"""Like inverse_permutation, but also handles slices.
Parameters
----------
positions : list of np.ndarray or slice objects.
If slice objects, all are assumed to be slices.
Returns
-------
np.ndarray of indices or None, if no permutation... | Like inverse_permutation, but also handles slices.
Parameters
----------
positions : list of np.ndarray or slice objects.
If slice objects, all are assumed to be slices.
Returns
-------
np.ndarray of indices or None, if no permutation is necessary. | Below is the the instruction that describes the task:
### Input:
Like inverse_permutation, but also handles slices.
Parameters
----------
positions : list of np.ndarray or slice objects.
If slice objects, all are assumed to be slices.
Returns
-------
np.ndarray of indices or None, ... |
def make_witness_input_and_witness(outpoint, sequence,
stack=None, **kwargs):
'''
Outpoint, int, list(bytearray) -> (Input, InputWitness)
'''
if 'decred' in riemann.get_current_network_name():
return(make_witness_input(outpoint, sequence),
make_d... | Outpoint, int, list(bytearray) -> (Input, InputWitness) | Below is the the instruction that describes the task:
### Input:
Outpoint, int, list(bytearray) -> (Input, InputWitness)
### Response:
def make_witness_input_and_witness(outpoint, sequence,
stack=None, **kwargs):
'''
Outpoint, int, list(bytearray) -> (Input, InputWitness)... |
def getBlock(self, block_identifier, full_transactions=False):
"""
`eth_getBlockByHash`
`eth_getBlockByNumber`
"""
method = select_method_for_block_identifier(
block_identifier,
if_predefined='eth_getBlockByNumber',
if_hash='eth_getBlockByHash'... | `eth_getBlockByHash`
`eth_getBlockByNumber` | Below is the the instruction that describes the task:
### Input:
`eth_getBlockByHash`
`eth_getBlockByNumber`
### Response:
def getBlock(self, block_identifier, full_transactions=False):
"""
`eth_getBlockByHash`
`eth_getBlockByNumber`
"""
method = select_method_for_bl... |
def _set_pegasus_profile_options(self):
"""Set the pegasus-profile settings for this Executable.
These are a property of the Executable and not of nodes that it will
spawn. Therefore it *cannot* be updated without also changing values
for nodes that might already have been created. Ther... | Set the pegasus-profile settings for this Executable.
These are a property of the Executable and not of nodes that it will
spawn. Therefore it *cannot* be updated without also changing values
for nodes that might already have been created. Therefore this is
only called once in __init__.... | Below is the the instruction that describes the task:
### Input:
Set the pegasus-profile settings for this Executable.
These are a property of the Executable and not of nodes that it will
spawn. Therefore it *cannot* be updated without also changing values
for nodes that might already have ... |
def timeit(self, metric, func, *args, **kwargs):
"""Time execution of callable and emit metric then return result."""
return metrics.timeit(metric, func, *args, **kwargs) | Time execution of callable and emit metric then return result. | Below is the the instruction that describes the task:
### Input:
Time execution of callable and emit metric then return result.
### Response:
def timeit(self, metric, func, *args, **kwargs):
"""Time execution of callable and emit metric then return result."""
return metrics.timeit(metric, func, *ar... |
def send_report(self, report_parts):
"""
Publish the report parts to local files. Each report part is a text
with a title and specific extension. For html and plaintext sending
the report part is unique, for csv send also the stats and unparsed
string are plain text and report it... | Publish the report parts to local files. Each report part is a text
with a title and specific extension. For html and plaintext sending
the report part is unique, for csv send also the stats and unparsed
string are plain text and report items are csv texts. | Below is the the instruction that describes the task:
### Input:
Publish the report parts to local files. Each report part is a text
with a title and specific extension. For html and plaintext sending
the report part is unique, for csv send also the stats and unparsed
string are plain text a... |
def screenshot(filename, width=None, height=None):
'''Make a screenshot of the current view. You can tweak the
resolution up to what your GPU memory supports.
By defaults it uses the current window resolution.
Example::
screenshot('screen.png', 1200, 1200)
'''
width = width... | Make a screenshot of the current view. You can tweak the
resolution up to what your GPU memory supports.
By defaults it uses the current window resolution.
Example::
screenshot('screen.png', 1200, 1200) | Below is the the instruction that describes the task:
### Input:
Make a screenshot of the current view. You can tweak the
resolution up to what your GPU memory supports.
By defaults it uses the current window resolution.
Example::
screenshot('screen.png', 1200, 1200)
### Response:
def ... |
def mass_loss_loon05(L,Teff):
'''
mass loss rate van Loon etal (2005).
Parameters
----------
L : float
L in L_sun.
Teff : float
Teff in K.
Returns
-------
Mdot
Mdot in Msun/yr
Notes
-----
ref: van Loon etal 2005, A&A 438, 273
... | mass loss rate van Loon etal (2005).
Parameters
----------
L : float
L in L_sun.
Teff : float
Teff in K.
Returns
-------
Mdot
Mdot in Msun/yr
Notes
-----
ref: van Loon etal 2005, A&A 438, 273 | Below is the the instruction that describes the task:
### Input:
mass loss rate van Loon etal (2005).
Parameters
----------
L : float
L in L_sun.
Teff : float
Teff in K.
Returns
-------
Mdot
Mdot in Msun/yr
Notes
-----
ref: van Loon etal... |
def pastml_pipeline(tree, data, data_sep='\t', id_index=0,
columns=None, prediction_method=MPPA, model=F81, parameters=None,
name_column=None, date_column=None, tip_size_threshold=REASONABLE_NUMBER_OF_TIPS,
out_data=None, html_compressed=None, html=None, work_... | Applies PASTML to the given tree with the specified states and visualizes the result (as html maps).
:param tree: path to the input tree in newick format (must be rooted).
:type tree: str
:param data: path to the annotation file in tab/csv format with the first row containing the column names.
:type d... | Below is the the instruction that describes the task:
### Input:
Applies PASTML to the given tree with the specified states and visualizes the result (as html maps).
:param tree: path to the input tree in newick format (must be rooted).
:type tree: str
:param data: path to the annotation file in tab/c... |
def from_pandas(cls, index):
"""Create baloo Index from pandas Index.
Parameters
----------
index : pandas.base.Index
Returns
-------
Index
"""
from pandas import Index as PandasIndex
check_type(index, PandasIndex)
return Index(... | Create baloo Index from pandas Index.
Parameters
----------
index : pandas.base.Index
Returns
-------
Index | Below is the the instruction that describes the task:
### Input:
Create baloo Index from pandas Index.
Parameters
----------
index : pandas.base.Index
Returns
-------
Index
### Response:
def from_pandas(cls, index):
"""Create baloo Index from pandas Index.
... |
def swap(self, key, items):
"""Set key to a copy of items and return the list that was previously
stored if the key was set. If not key was set, returns an empty list.
"""
if not isinstance(items, list):
raise ValueError("items must be a list")
return_value = []
... | Set key to a copy of items and return the list that was previously
stored if the key was set. If not key was set, returns an empty list. | Below is the the instruction that describes the task:
### Input:
Set key to a copy of items and return the list that was previously
stored if the key was set. If not key was set, returns an empty list.
### Response:
def swap(self, key, items):
"""Set key to a copy of items and return the list that ... |
def delete_group(self, group_id, **kwargs): # noqa: E501
"""Delete a group. # noqa: E501
An endpoint for deleting a group. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a... | Delete a group. # noqa: E501
An endpoint for deleting a group. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous... | Below is the the instruction that describes the task:
### Input:
Delete a group. # noqa: E501
An endpoint for deleting a group. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a... |
def cst_now():
"""
This will return a datetime of utcnow - 6 hours for
Central Standard Time
:return: Datetime
"""
try:
ret = datetime.utcnow() + timedelta(hours=DEFAULT_TIMEZONE)
if DEFAULT_TIMEZONE_AWARE:
ret = ret.replace(
tzinfo=psycopg2.tz... | This will return a datetime of utcnow - 6 hours for
Central Standard Time
:return: Datetime | Below is the the instruction that describes the task:
### Input:
This will return a datetime of utcnow - 6 hours for
Central Standard Time
:return: Datetime
### Response:
def cst_now():
"""
This will return a datetime of utcnow - 6 hours for
Central Standard Time
:return: Dateti... |
def match_taking_agent_id(self, agent_id, match):
"""Sets the agent ``Id`` for this query.
arg: agent_id (osid.id.Id): an agent ``Id``
arg: match (boolean): ``true`` for a positive match,
``false`` for a negative match
raise: NullArgument - ``agent_id`` is ``null`... | Sets the agent ``Id`` for this query.
arg: agent_id (osid.id.Id): an agent ``Id``
arg: match (boolean): ``true`` for a positive match,
``false`` for a negative match
raise: NullArgument - ``agent_id`` is ``null``
*compliance: mandatory -- This method must be imple... | Below is the the instruction that describes the task:
### Input:
Sets the agent ``Id`` for this query.
arg: agent_id (osid.id.Id): an agent ``Id``
arg: match (boolean): ``true`` for a positive match,
``false`` for a negative match
raise: NullArgument - ``agent_id`` is... |
def define_hardware_breakpoint(self, dwThreadId, address,
triggerFlag = BP_BREAK_ON_ACCESS,
sizeFlag = BP_WATCH_DWORD,
condition = True,
... | Creates a disabled hardware breakpoint at the given address.
@see:
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint},
L{erase_hardw... | Below is the the instruction that describes the task:
### Input:
Creates a disabled hardware breakpoint at the given address.
@see:
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
... |
def path_to_url(path):
"""
Convert a path to a file: URL. The path will be made absolute.
"""
path = os.path.normcase(os.path.abspath(path))
if _drive_re.match(path):
path = path[0] + '|' + path[2:]
url = urllib.quote(path)
url = url.replace(os.path.sep, '/')
url = url.lstrip('/... | Convert a path to a file: URL. The path will be made absolute. | Below is the the instruction that describes the task:
### Input:
Convert a path to a file: URL. The path will be made absolute.
### Response:
def path_to_url(path):
"""
Convert a path to a file: URL. The path will be made absolute.
"""
path = os.path.normcase(os.path.abspath(path))
if _drive_... |
def update_entity(namespace, workspace, etype, ename, updates):
""" Update entity attributes in a workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
etype (str): Entity type
ename (str): Entity name
updates (lis... | Update entity attributes in a workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
etype (str): Entity type
ename (str): Entity name
updates (list(dict)): List of updates to entity from _attr_set, e.g.
Swagger:
... | Below is the the instruction that describes the task:
### Input:
Update entity attributes in a workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
etype (str): Entity type
ename (str): Entity name
updates (list(d... |
def get_server_group(self):
"""Finds the most recently deployed server group for the application.
This is the server group that the scaling policy will be applied to.
Returns:
server_group (str): Name of the newest server group
"""
api_url = "{0}/applications/{1}".fo... | Finds the most recently deployed server group for the application.
This is the server group that the scaling policy will be applied to.
Returns:
server_group (str): Name of the newest server group | Below is the the instruction that describes the task:
### Input:
Finds the most recently deployed server group for the application.
This is the server group that the scaling policy will be applied to.
Returns:
server_group (str): Name of the newest server group
### Response:
def get_se... |
def _cleanup(self):
"""Remove any stale files from the session storage directory"""
for filename in os.listdir(self._storage_dir):
file_path = path.join(self._storage_dir, filename)
file_stat = os.stat(file_path)
evaluate = max(file_stat.st_ctime, file_stat.st_mtime)
... | Remove any stale files from the session storage directory | Below is the the instruction that describes the task:
### Input:
Remove any stale files from the session storage directory
### Response:
def _cleanup(self):
"""Remove any stale files from the session storage directory"""
for filename in os.listdir(self._storage_dir):
file_path = path.jo... |
def Encrypt(self, data, iv=None):
"""Symmetrically encrypt the data using the optional iv."""
if iv is None:
iv = rdf_crypto.EncryptionKey.GenerateKey(length=128)
cipher = rdf_crypto.AES128CBCCipher(self.cipher.key, iv)
return iv, cipher.Encrypt(data) | Symmetrically encrypt the data using the optional iv. | Below is the the instruction that describes the task:
### Input:
Symmetrically encrypt the data using the optional iv.
### Response:
def Encrypt(self, data, iv=None):
"""Symmetrically encrypt the data using the optional iv."""
if iv is None:
iv = rdf_crypto.EncryptionKey.GenerateKey(length=128)
c... |
def get_path_and_qs(self):
"""
Parse and obtain the path and query values.
We don't care about fragments.
Return {'path': ..., 'qs_values': ...} on success
Return {'error': ...} on error
"""
path_parts = self.path.split("?", 1)
if len(path_parts) > 1:
... | Parse and obtain the path and query values.
We don't care about fragments.
Return {'path': ..., 'qs_values': ...} on success
Return {'error': ...} on error | Below is the the instruction that describes the task:
### Input:
Parse and obtain the path and query values.
We don't care about fragments.
Return {'path': ..., 'qs_values': ...} on success
Return {'error': ...} on error
### Response:
def get_path_and_qs(self):
"""
Parse an... |
def _save_or_update(self):
"""Save or update the private state needed by the cloud provider.
"""
with self._resource_lock:
if not self._config or not self._config._storage_path:
raise Exception("self._config._storage path is undefined")
if not self._config... | Save or update the private state needed by the cloud provider. | Below is the the instruction that describes the task:
### Input:
Save or update the private state needed by the cloud provider.
### Response:
def _save_or_update(self):
"""Save or update the private state needed by the cloud provider.
"""
with self._resource_lock:
if not self._c... |
def make_outdir():
"""Make the output directory, if required.
This is a little involved. If the output directory already exists,
we take the safe option by default, and stop with an error. We can,
however, choose to force the program to go on, in which case we can
either clobber the existing dire... | Make the output directory, if required.
This is a little involved. If the output directory already exists,
we take the safe option by default, and stop with an error. We can,
however, choose to force the program to go on, in which case we can
either clobber the existing directory, or not. The option... | Below is the the instruction that describes the task:
### Input:
Make the output directory, if required.
This is a little involved. If the output directory already exists,
we take the safe option by default, and stop with an error. We can,
however, choose to force the program to go on, in which case ... |
def call_audit(func):
"""Print a detailed audit of all calls to this function."""
def audited_func(*args, **kwargs):
import traceback
stack = traceback.extract_stack()
r = func(*args, **kwargs)
func_name = func.__name__
print("@depth %d, trace %s -> %s(*%r, **%r) => %r" ... | Print a detailed audit of all calls to this function. | Below is the the instruction that describes the task:
### Input:
Print a detailed audit of all calls to this function.
### Response:
def call_audit(func):
"""Print a detailed audit of all calls to this function."""
def audited_func(*args, **kwargs):
import traceback
stack = traceback.extrac... |
def add_note(
self,
note):
"""*Add a note to this taskpaper object*
**Key Arguments:**
- ``note`` -- the note (string)
**Return:**
- None
**Usage:**
To add a note to a document, project or task object:
.. code-b... | *Add a note to this taskpaper object*
**Key Arguments:**
- ``note`` -- the note (string)
**Return:**
- None
**Usage:**
To add a note to a document, project or task object:
.. code-block:: python
newNote = doc.add_note(And anot... | Below is the the instruction that describes the task:
### Input:
*Add a note to this taskpaper object*
**Key Arguments:**
- ``note`` -- the note (string)
**Return:**
- None
**Usage:**
To add a note to a document, project or task object:
..... |
def filters_from_args(self, args):
'''take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments'''
filters = dict()
remainder = []
for arg in args:
try:
equals = arg.index('=')
# anything ofthe fo... | take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments | Below is the the instruction that describes the task:
### Input:
take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments
### Response:
def filters_from_args(self, args):
'''take any argument of the form name=value anmd put it into a dict; return that and th... |
def _print_refs(self, refs, total, prefix=' ',
level=1, minsize=0, minpct=0.1):
"""
Print individual referents recursively.
"""
lrefs = list(refs)
lrefs.sort(key=lambda x: x.size)
lrefs.reverse()
for ref in lrefs:
if ref.size > m... | Print individual referents recursively. | Below is the the instruction that describes the task:
### Input:
Print individual referents recursively.
### Response:
def _print_refs(self, refs, total, prefix=' ',
level=1, minsize=0, minpct=0.1):
"""
Print individual referents recursively.
"""
lrefs = list(... |
def data(self, index, role):
"""Return role specific data for the item referred by
index.column()."""
if not index.isValid():
return
item = self.item(index)
column = index.column()
value = item.getItemData(column)
if role == Qt.DisplayRole:
... | Return role specific data for the item referred by
index.column(). | Below is the the instruction that describes the task:
### Input:
Return role specific data for the item referred by
index.column().
### Response:
def data(self, index, role):
"""Return role specific data for the item referred by
index.column()."""
if not index.isValid():
... |
def run_process(path: Union[Path, str], target: Callable, *,
args: Tuple=(),
kwargs: Dict[str, Any]=None,
callback: Callable[[Set[Tuple[Change, str]]], None]=None,
watcher_cls: Type[AllWatcher]=PythonWatcher,
debounce=400,
m... | Run a function in a subprocess using multiprocessing.Process, restart it whenever files change in path. | Below is the the instruction that describes the task:
### Input:
Run a function in a subprocess using multiprocessing.Process, restart it whenever files change in path.
### Response:
def run_process(path: Union[Path, str], target: Callable, *,
args: Tuple=(),
kwargs: Dict[str, Any]=... |
def readObject(self):
"""
Reads an object from the stream.
"""
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
obj = self.context.getObject(ref >> 1)
if obj is None:
raise pyamf.ReferenceError('Unknown reference %d' % (ref >> 1... | Reads an object from the stream. | Below is the the instruction that describes the task:
### Input:
Reads an object from the stream.
### Response:
def readObject(self):
"""
Reads an object from the stream.
"""
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
obj = self.context.getObject... |
def pprint_jobject(obj, **kwargs):
'''Pretty-print a jobject.
Parameters
----------
obj : jams.JObject
kwargs
additional parameters to `json.dumps`
Returns
-------
string
A simplified display of `obj` contents.
'''
obj_simple = {k: v for k, v in six.iteritems(... | Pretty-print a jobject.
Parameters
----------
obj : jams.JObject
kwargs
additional parameters to `json.dumps`
Returns
-------
string
A simplified display of `obj` contents. | Below is the the instruction that describes the task:
### Input:
Pretty-print a jobject.
Parameters
----------
obj : jams.JObject
kwargs
additional parameters to `json.dumps`
Returns
-------
string
A simplified display of `obj` contents.
### Response:
def pprint_jobje... |
def create_repro(self):
"""Return a Repro instance for capturing a repro of the current workspace state.
:return: a Repro instance, or None if no repro was requested.
:rtype: `pants.bin.repro.Repro`
"""
path = self.get_options().capture
if path is None:
return None
buildroot = get_bui... | Return a Repro instance for capturing a repro of the current workspace state.
:return: a Repro instance, or None if no repro was requested.
:rtype: `pants.bin.repro.Repro` | Below is the the instruction that describes the task:
### Input:
Return a Repro instance for capturing a repro of the current workspace state.
:return: a Repro instance, or None if no repro was requested.
:rtype: `pants.bin.repro.Repro`
### Response:
def create_repro(self):
"""Return a Repro instance ... |
def try_pop(d, key, default):
"""
>>> d = {"a": "b", "c": "d", "e": "f"}
>>> try_pop(d, "g", "default")
'default'
>>> d
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> try_pop(d, "c", "default")
'd'
>>> d
{'a': 'b', 'e': 'f'}
"""
value = d.get(key, default)
if key in d:
d.... | >>> d = {"a": "b", "c": "d", "e": "f"}
>>> try_pop(d, "g", "default")
'default'
>>> d
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> try_pop(d, "c", "default")
'd'
>>> d
{'a': 'b', 'e': 'f'} | Below is the the instruction that describes the task:
### Input:
>>> d = {"a": "b", "c": "d", "e": "f"}
>>> try_pop(d, "g", "default")
'default'
>>> d
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> try_pop(d, "c", "default")
'd'
>>> d
{'a': 'b', 'e': 'f'}
### Response:
def try_pop(d, key, defau... |
def itemsize(obj, **opts):
'''Return the item size of an object (in bytes).
See function **basicsize** for a description of
the options.
'''
v = _typedefof(obj, **opts)
if v:
v = v.item
return v | Return the item size of an object (in bytes).
See function **basicsize** for a description of
the options. | Below is the the instruction that describes the task:
### Input:
Return the item size of an object (in bytes).
See function **basicsize** for a description of
the options.
### Response:
def itemsize(obj, **opts):
'''Return the item size of an object (in bytes).
See function **basicsize**... |
def permissions(self):
"""
Retrieve the permissions for this engine instance.
::
>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for x in engine.permissions:
... print(x)
...
AccessControlLis... | Retrieve the permissions for this engine instance.
::
>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for x in engine.permissions:
... print(x)
...
AccessControlList(name=ALL Elements)
AccessCont... | Below is the the instruction that describes the task:
### Input:
Retrieve the permissions for this engine instance.
::
>>> from smc.core.engine import Engine
>>> engine = Engine('myfirewall')
>>> for x in engine.permissions:
... print(x)
...
... |
def poll(self):
"""Retrieves older requests that may not make it back quick
enough"""
if self.redis_connected:
json_item = request.get_json()
result = None
try:
key = "rest:poll:{u}".format(u=json_item['poll_id'])
result = self.... | Retrieves older requests that may not make it back quick
enough | Below is the the instruction that describes the task:
### Input:
Retrieves older requests that may not make it back quick
enough
### Response:
def poll(self):
"""Retrieves older requests that may not make it back quick
enough"""
if self.redis_connected:
json_item = reque... |
def add_auto_increment(self, table, name):
"""Modify an existing column."""
# Get current column definition and add auto_incrementing
definition = self.get_column_definition(table, name) + ' AUTO_INCREMENT'
# Concatenate and execute modify statement
self.execute("ALTER TABLE {0}... | Modify an existing column. | Below is the the instruction that describes the task:
### Input:
Modify an existing column.
### Response:
def add_auto_increment(self, table, name):
"""Modify an existing column."""
# Get current column definition and add auto_incrementing
definition = self.get_column_definition(table, name... |
def mapper_init(self):
""" Download counties geojson from S3 and build spatial index and cache """
self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION)
self.extractor = WordExtractor() | Download counties geojson from S3 and build spatial index and cache | Below is the the instruction that describes the task:
### Input:
Download counties geojson from S3 and build spatial index and cache
### Response:
def mapper_init(self):
""" Download counties geojson from S3 and build spatial index and cache """
self.counties = CachedCountyLookup(precision=GEOHASH_... |
def items(self):
"""Get an iter of VenvDirs and VenvFiles within the directory."""
contents = self.paths
contents = (
VenvFile(path.path) if path.is_file else VenvDir(path.path)
for path in contents
)
return contents | Get an iter of VenvDirs and VenvFiles within the directory. | Below is the the instruction that describes the task:
### Input:
Get an iter of VenvDirs and VenvFiles within the directory.
### Response:
def items(self):
"""Get an iter of VenvDirs and VenvFiles within the directory."""
contents = self.paths
contents = (
VenvFile(path.path) if... |
def run_fastqc(credentials, instance_config, instance_name,
script_dir, input_file, output_dir, self_destruct=True,
**kwargs):
"""Run FASTQC.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('fastqc.sh')
startup_script = template.render(
script_dir=script_d... | Run FASTQC.
TODO: docstring | Below is the the instruction that describes the task:
### Input:
Run FASTQC.
TODO: docstring
### Response:
def run_fastqc(credentials, instance_config, instance_name,
script_dir, input_file, output_dir, self_destruct=True,
**kwargs):
"""Run FASTQC.
TODO: docstring"""
... |
def flatten_template_loaders(templates):
"""
Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression
"""
for loader in templates:
if not... | Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression | Below is the the instruction that describes the task:
### Input:
Given a collection of template loaders, unwrap them into one flat iterable.
:param templates: template loaders to unwrap
:return: template loaders as an iterable of strings.
:rtype: generator expression
### Response:
def flatten_template... |
def window(featurestream, seqid, start=None, end=None, strict=True):
"""
Pull features out of the designated genomic interval.
This function uses 0-based half-open intervals, not the 1-based closed
intervals used by GFF3.
:param featurestream: a stream of feature entries
:param seqid: ID of th... | Pull features out of the designated genomic interval.
This function uses 0-based half-open intervals, not the 1-based closed
intervals used by GFF3.
:param featurestream: a stream of feature entries
:param seqid: ID of the sequence from which to select features
:param start: start of the genomic i... | Below is the the instruction that describes the task:
### Input:
Pull features out of the designated genomic interval.
This function uses 0-based half-open intervals, not the 1-based closed
intervals used by GFF3.
:param featurestream: a stream of feature entries
:param seqid: ID of the sequence f... |
def create_routes_and_handler(transmute_func, context):
"""
return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to.
"""
@wraps(transmute_func.raw_func)
def handler():
exc, result = None, None
try:
args... | return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to. | Below is the the instruction that describes the task:
### Input:
return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to.
### Response:
def create_routes_and_handler(transmute_func, context):
"""
return back a handler that is the api gen... |
def type(self):
"""Enum type used for field."""
if self.__type is None:
found_type = find_definition(
self.__type_name, self.message_definition())
if not (found_type is not Enum and
isinstance(found_type, type) and
issubclas... | Enum type used for field. | Below is the the instruction that describes the task:
### Input:
Enum type used for field.
### Response:
def type(self):
"""Enum type used for field."""
if self.__type is None:
found_type = find_definition(
self.__type_name, self.message_definition())
if not ... |
def generate_upload_token(self, token, item_id, filename, checksum=None):
"""
Generate a token to use for upload.
Midas Server uses a individual token for each upload. The token
corresponds to the file specified and that file only. Passing the MD5
checksum allows the server to d... | Generate a token to use for upload.
Midas Server uses a individual token for each upload. The token
corresponds to the file specified and that file only. Passing the MD5
checksum allows the server to determine if the file is already in the
asset store.
If :param:`checksum` is p... | Below is the the instruction that describes the task:
### Input:
Generate a token to use for upload.
Midas Server uses a individual token for each upload. The token
corresponds to the file specified and that file only. Passing the MD5
checksum allows the server to determine if the file is a... |
def handle(self):
"""
Handles a TCP client
"""
_logger.info(
"RemoteConsole client connected: [%s]:%d",
self.client_address[0],
self.client_address[1],
)
# Prepare the session
session = beans.ShellSession(
beans.IOH... | Handles a TCP client | Below is the the instruction that describes the task:
### Input:
Handles a TCP client
### Response:
def handle(self):
"""
Handles a TCP client
"""
_logger.info(
"RemoteConsole client connected: [%s]:%d",
self.client_address[0],
self.client_address... |
def get_me(self):
"""Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant.
"""
response = self.request_json(self.config['me'])
user = objects.Redditor(self, response['name'], response)
user.__... | Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant. | Below is the the instruction that describes the task:
### Input:
Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant.
### Response:
def get_me(self):
"""Return a LoggedInRedditor object.
Note: This function is... |
def _get_auth_from_keyring(self):
"""Try to get credentials using `keyring <https://github.com/jaraco/keyring>`_."""
if not keyring:
return None
# Take user from URL if available, else the OS login name
password = self._get_password_from_keyring(self.user or getpass.getuser(... | Try to get credentials using `keyring <https://github.com/jaraco/keyring>`_. | Below is the the instruction that describes the task:
### Input:
Try to get credentials using `keyring <https://github.com/jaraco/keyring>`_.
### Response:
def _get_auth_from_keyring(self):
"""Try to get credentials using `keyring <https://github.com/jaraco/keyring>`_."""
if not keyring:
... |
def re(self, event_property, value):
"""A regular expression filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.re('path', '[^A-Za-z0-9+]')
>>> print(filtered)
request(elapsed_ms).re(path, "[^A-Za-z0-9+]")
"""
c ... | A regular expression filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.re('path', '[^A-Za-z0-9+]')
>>> print(filtered)
request(elapsed_ms).re(path, "[^A-Za-z0-9+]") | Below is the the instruction that describes the task:
### Input:
A regular expression filter chain.
>>> request_time = EventExpression('request', 'elapsed_ms')
>>> filtered = request_time.re('path', '[^A-Za-z0-9+]')
>>> print(filtered)
request(elapsed_ms).re(path, "[^A-Za-z0-9+]")
#... |
def __get_gp_plan(self, gp):
"""
Request the planner a search plan for a given gp and returns the plan as a graph.
:param gp:
:return:
"""
query = urlencode({'gp': gp})
response = requests.get('{}/plan?'.format(self.__planner) + query, headers={'Accept': 'text/tur... | Request the planner a search plan for a given gp and returns the plan as a graph.
:param gp:
:return: | Below is the the instruction that describes the task:
### Input:
Request the planner a search plan for a given gp and returns the plan as a graph.
:param gp:
:return:
### Response:
def __get_gp_plan(self, gp):
"""
Request the planner a search plan for a given gp and returns the plan... |
def setup_multiifo_interval_coinc(workflow, hdfbank, trig_files, stat_files,
veto_files, veto_names, out_dir, pivot_ifo, fixed_ifo, tags=None):
"""
This function sets up exact match multiifo coincidence
"""
if tags is None:
tags = []
make_analysis_dir(out_dir)
lo... | This function sets up exact match multiifo coincidence | Below is the the instruction that describes the task:
### Input:
This function sets up exact match multiifo coincidence
### Response:
def setup_multiifo_interval_coinc(workflow, hdfbank, trig_files, stat_files,
veto_files, veto_names, out_dir, pivot_ifo, fixed_ifo, tags=None):
"""
... |
def _get_contents(self):
"""Create strings from glob strings."""
def files():
for value in super(GlobBundle, self)._get_contents():
for path in glob.glob(value):
yield path
return list(files()) | Create strings from glob strings. | Below is the the instruction that describes the task:
### Input:
Create strings from glob strings.
### Response:
def _get_contents(self):
"""Create strings from glob strings."""
def files():
for value in super(GlobBundle, self)._get_contents():
for path in glob.glob(valu... |
def infer_gaps_in_tree(df_seq, tree, id_col='id', sequence_col='sequence'):
"""Adds a character matrix to DendroPy tree and infers gaps using
Fitch's algorithm.
Infer gaps in sequences at ancestral nodes.
"""
taxa = tree.taxon_namespace
# Get alignment as fasta
alignment = df_seq.phylo.to_... | Adds a character matrix to DendroPy tree and infers gaps using
Fitch's algorithm.
Infer gaps in sequences at ancestral nodes. | Below is the the instruction that describes the task:
### Input:
Adds a character matrix to DendroPy tree and infers gaps using
Fitch's algorithm.
Infer gaps in sequences at ancestral nodes.
### Response:
def infer_gaps_in_tree(df_seq, tree, id_col='id', sequence_col='sequence'):
"""Adds a character m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.