code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def takef(d,l,val=None):
'''take(f) a list of keys and fill in others with val'''
return {i:(d[i] if i in d else val)
for i in l}; | take(f) a list of keys and fill in others with val | Below is the the instruction that describes the task:
### Input:
take(f) a list of keys and fill in others with val
### Response:
def takef(d,l,val=None):
'''take(f) a list of keys and fill in others with val'''
return {i:(d[i] if i in d else val)
for i in l}; |
def sample_stats_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.coor... | Extract sample_stats from fit. | Below is the the instruction that describes the task:
### Input:
Extract sample_stats from fit.
### Response:
def sample_stats_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
... |
def setup_sfr_obs(sfr_out_file,seg_group_dict=None,ins_file=None,model=None,
include_path=False):
"""setup observations using the sfr ASCII output file. Setups
the ability to aggregate flows for groups of segments. Applies
only flow to aquier and flow out.
Parameters
----------
... | setup observations using the sfr ASCII output file. Setups
the ability to aggregate flows for groups of segments. Applies
only flow to aquier and flow out.
Parameters
----------
sft_out_file : str
the existing SFR output file
seg_group_dict : dict
a dictionary of SFR segements... | Below is the the instruction that describes the task:
### Input:
setup observations using the sfr ASCII output file. Setups
the ability to aggregate flows for groups of segments. Applies
only flow to aquier and flow out.
Parameters
----------
sft_out_file : str
the existing SFR output... |
def log_paths():
'''Returns tuple (logdir, telemetry_log_filepath, raw_telemetry_log_filepath)'''
if opts.aircraft is not None:
dirname = ""
if opts.mission is not None:
print(opts.mission)
dirname += "%s/logs/%s/Mission%s" % (opts.aircraft, time.strftime("%Y-%m-%d"), opt... | Returns tuple (logdir, telemetry_log_filepath, raw_telemetry_log_filepath) | Below is the the instruction that describes the task:
### Input:
Returns tuple (logdir, telemetry_log_filepath, raw_telemetry_log_filepath)
### Response:
def log_paths():
'''Returns tuple (logdir, telemetry_log_filepath, raw_telemetry_log_filepath)'''
if opts.aircraft is not None:
dirname = ""
... |
def emit(self):
""" Serialize response.
:return response: Instance of django.http.Response
"""
# Skip serialize
if not isinstance(self.response, SerializedHttpResponse):
return self.response
self.response.content = self.serialize(self.response.response)
... | Serialize response.
:return response: Instance of django.http.Response | Below is the the instruction that describes the task:
### Input:
Serialize response.
:return response: Instance of django.http.Response
### Response:
def emit(self):
""" Serialize response.
:return response: Instance of django.http.Response
"""
# Skip serialize
if... |
def run_async(**kwargs):
'''
Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.
This uses the same parameters as :py:func:`ansible_runner.interface.run`
:returns: A tuple containing a :py:class:`threading.Thread` object and a :py:... | Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.
This uses the same parameters as :py:func:`ansible_runner.interface.run`
:returns: A tuple containing a :py:class:`threading.Thread` object and a :py:class:`ansible_runner.runner.Runner` ... | Below is the the instruction that describes the task:
### Input:
Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.
This uses the same parameters as :py:func:`ansible_runner.interface.run`
:returns: A tuple containing a :py:class:`thr... |
def add_accounts_to_project(accounts_query, project):
""" Add accounts to project. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
add_account_to_project(account, project) | Add accounts to project. | Below is the the instruction that describes the task:
### Input:
Add accounts to project.
### Response:
def add_accounts_to_project(accounts_query, project):
""" Add accounts to project. """
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
add_account_to_project(... |
def startup(self):
"""Start the instance
This is mainly use to start the proxy
"""
self.runner.info_log("Startup")
if self.browser_config.config.get('enable_proxy'):
self.start_proxy() | Start the instance
This is mainly use to start the proxy | Below is the the instruction that describes the task:
### Input:
Start the instance
This is mainly use to start the proxy
### Response:
def startup(self):
"""Start the instance
This is mainly use to start the proxy
"""
self.runner.info_log("Startup")
if self.brows... |
def get_command_class_from_apps(name, apps, exclude_packages=None, exclude_command_class=None):
"""
Searches through the given apps to find the named command class. Skips
over any packages specified by exclude_packages and any command class
specified by exclude_command_class. Returns the last command cl... | Searches through the given apps to find the named command class. Skips
over any packages specified by exclude_packages and any command class
specified by exclude_command_class. Returns the last command class found
or None if the command class could not be found.
Django's command searching behavior ... | Below is the the instruction that describes the task:
### Input:
Searches through the given apps to find the named command class. Skips
over any packages specified by exclude_packages and any command class
specified by exclude_command_class. Returns the last command class found
or None if the command cl... |
def PyParseJoinList(string, location, tokens):
"""Return a joined token from a list of tokens.
This is a callback method for pyparsing setParseAction that modifies
the returned token list to join all the elements in the list to a single
token.
Args:
string (str): original string.
location (int): loc... | Return a joined token from a list of tokens.
This is a callback method for pyparsing setParseAction that modifies
the returned token list to join all the elements in the list to a single
token.
Args:
string (str): original string.
location (int): location in the string where the match was made.
to... | Below is the the instruction that describes the task:
### Input:
Return a joined token from a list of tokens.
This is a callback method for pyparsing setParseAction that modifies
the returned token list to join all the elements in the list to a single
token.
Args:
string (str): original string.
lo... |
def exitcode(self):
"""
Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet.
"""
if self._process is None:
... | Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet. | Below is the the instruction that describes the task:
### Input:
Process exit code. :const:`0` when process exited successfully,
positive number when exception was occurred, negative number when
process was signaled and :data:`None` when process has not exited
yet.
### Response:
def exitcod... |
def get_pypi_auth(configfile='~/.pypirc'):
"""Read auth from pip config."""
pypi_cfg = ConfigParser()
if pypi_cfg.read(os.path.expanduser(configfile)):
try:
user = pypi_cfg.get('pypi', 'username')
pwd = pypi_cfg.get('pypi', 'password')
return user, pwd
exc... | Read auth from pip config. | Below is the the instruction that describes the task:
### Input:
Read auth from pip config.
### Response:
def get_pypi_auth(configfile='~/.pypirc'):
"""Read auth from pip config."""
pypi_cfg = ConfigParser()
if pypi_cfg.read(os.path.expanduser(configfile)):
try:
user = pypi_cfg.get(... |
def cost(self, logits, target):
"""Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
"""
logits = tf.reshape(logi... | Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time. | Below is the the instruction that describes the task:
### Input:
Returns cost.
Args:
logits: model output.
target: target.
Returns:
Cross-entropy loss for a sequence of logits. The loss will be averaged
across time steps if time_average_cost was enabled at construction time.
### Re... |
def load_from_xml(self, path):
"""Load all objects from XML file and return as dict.
The dict returned will have keys named the same as the
JSSObject classes contained, and the values will be
JSSObjectLists of all full objects of that class (for example,
the equivalent of my_jss... | Load all objects from XML file and return as dict.
The dict returned will have keys named the same as the
JSSObject classes contained, and the values will be
JSSObjectLists of all full objects of that class (for example,
the equivalent of my_jss.Computer().retrieve_all()).
This... | Below is the the instruction that describes the task:
### Input:
Load all objects from XML file and return as dict.
The dict returned will have keys named the same as the
JSSObject classes contained, and the values will be
JSSObjectLists of all full objects of that class (for example,
... |
def remove_xml_element_string(name, content):
""" Remove XML elements from a string """
ET.register_namespace("", "http://soap.sforce.com/2006/04/metadata")
tree = ET.fromstring(content)
tree = remove_xml_element(name, tree)
clean_content = ET.tostring(tree, encoding=UTF8)
return clean_content | Remove XML elements from a string | Below is the the instruction that describes the task:
### Input:
Remove XML elements from a string
### Response:
def remove_xml_element_string(name, content):
""" Remove XML elements from a string """
ET.register_namespace("", "http://soap.sforce.com/2006/04/metadata")
tree = ET.fromstring(content)
... |
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None, with_namespace=False):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tup... | Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only`... | Below is the the instruction that describes the task:
### Input:
Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to ... |
def rotate_slaves(self):
"Round-robin slave balancer"
slaves = self.sentinel_manager.discover_slaves(self.service_name)
if slaves:
if self.slave_rr_counter is None:
self.slave_rr_counter = random.randint(0, len(slaves) - 1)
for _ in xrange(len(slaves)):
... | Round-robin slave balancer | Below is the the instruction that describes the task:
### Input:
Round-robin slave balancer
### Response:
def rotate_slaves(self):
"Round-robin slave balancer"
slaves = self.sentinel_manager.discover_slaves(self.service_name)
if slaves:
if self.slave_rr_counter is None:
... |
def read_gtfsr(path, *, from_json=False):
"""
Given a path (string or Path object) to a GTFSR feed file,
return the corresponding GTFS feed (FeedMessage instance).
If ``from_json``, then assume the feed file is in JSON format;
otherwise, assume the feed file is in Protocol Buffer format.
"""
... | Given a path (string or Path object) to a GTFSR feed file,
return the corresponding GTFS feed (FeedMessage instance).
If ``from_json``, then assume the feed file is in JSON format;
otherwise, assume the feed file is in Protocol Buffer format. | Below is the the instruction that describes the task:
### Input:
Given a path (string or Path object) to a GTFSR feed file,
return the corresponding GTFS feed (FeedMessage instance).
If ``from_json``, then assume the feed file is in JSON format;
otherwise, assume the feed file is in Protocol Buffer form... |
def estimate_max_mapq(in_bam, nreads=1e6):
"""Guess maximum MAPQ in a BAM file of reads with alignments
"""
with pysam.Samfile(in_bam, "rb") as work_bam:
reads = tz.take(int(nreads), work_bam)
return max([x.mapq for x in reads if not x.is_unmapped]) | Guess maximum MAPQ in a BAM file of reads with alignments | Below is the the instruction that describes the task:
### Input:
Guess maximum MAPQ in a BAM file of reads with alignments
### Response:
def estimate_max_mapq(in_bam, nreads=1e6):
"""Guess maximum MAPQ in a BAM file of reads with alignments
"""
with pysam.Samfile(in_bam, "rb") as work_bam:
read... |
def schedule(self):
"""
Given a a list of functions and a schedule to execute them,
setup up regular execution.
"""
events = self.stage_config.get('events', [])
if events:
if not isinstance(events, list): # pragma: no cover
print("Events must... | Given a a list of functions and a schedule to execute them,
setup up regular execution. | Below is the the instruction that describes the task:
### Input:
Given a a list of functions and a schedule to execute them,
setup up regular execution.
### Response:
def schedule(self):
"""
Given a a list of functions and a schedule to execute them,
setup up regular execution.
... |
def pull(self):
"""
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
"""
sock = self.__sock(zmq.PULL)
return self.... | Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator | Below is the the instruction that describes the task:
### Input:
Returns an iterable that can be used to iterate over incoming messages,
that were pushed by a push socket. Note that the iterable returns as
many parts as sent by pushers.
:rtype: generator
### Response:
def pull(self):
... |
def remove_member(self, user, api=None):
"""
Remove a member from the automation
:param user: Member username
:param api: sevenbridges Api instance
:return: None
"""
api = api or self._API
AutomationMember.remove(automation=self.id, user=user, api=api) | Remove a member from the automation
:param user: Member username
:param api: sevenbridges Api instance
:return: None | Below is the the instruction that describes the task:
### Input:
Remove a member from the automation
:param user: Member username
:param api: sevenbridges Api instance
:return: None
### Response:
def remove_member(self, user, api=None):
"""
Remove a member from the automatio... |
def async_send(self, url, data, headers, success_cb, failure_cb):
"""
Spawn an async request to a remote webserver.
"""
# this can be optimized by making a custom self.send that does not
# read the response since we don't use it.
self._lock.acquire()
return gevent... | Spawn an async request to a remote webserver. | Below is the the instruction that describes the task:
### Input:
Spawn an async request to a remote webserver.
### Response:
def async_send(self, url, data, headers, success_cb, failure_cb):
"""
Spawn an async request to a remote webserver.
"""
# this can be optimized by making a cu... |
def loadSVcols(fname, usecols=None, excludecols=None, valuefixer=None,
colfixer=None, missingvalues=None, fillingvalues=None,
typeinferer=None, **kwargs):
"""
Load a separated value text file to a list of column arrays.
Basically, this function calls loadSVrecs, and transpose... | Load a separated value text file to a list of column arrays.
Basically, this function calls loadSVrecs, and transposes the string-valued
row data returned by that function into a Python list of numpy arrays
corresponding to columns, each a uniform Python type (int, float, str).
Also uses and return... | Below is the the instruction that describes the task:
### Input:
Load a separated value text file to a list of column arrays.
Basically, this function calls loadSVrecs, and transposes the string-valued
row data returned by that function into a Python list of numpy arrays
corresponding to columns, eac... |
def download_file(url, destination, **kwargs):
"""
Download file process:
- Open the url
- Check if it has been downloaded and it hanged.
- Download it to the destination folder.
Args:
:urls: url to take the file.
:destionation: place to store the downloaded file.
... | Download file process:
- Open the url
- Check if it has been downloaded and it hanged.
- Download it to the destination folder.
Args:
:urls: url to take the file.
:destionation: place to store the downloaded file. | Below is the the instruction that describes the task:
### Input:
Download file process:
- Open the url
- Check if it has been downloaded and it hanged.
- Download it to the destination folder.
Args:
:urls: url to take the file.
:destionation: place to store the downloa... |
def establish_ssh_connection(ip,
ssh_private_key_file,
ssh_user,
port,
attempts=5,
timeout=None):
"""
Establish ssh connection and return paramiko client.
Raises:... | Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts. | Below is the the instruction that describes the task:
### Input:
Establish ssh connection and return paramiko client.
Raises:
IpaSSHException: If connection cannot be established
in given number of attempts.
### Response:
def establish_ssh_connection(ip,
ssh_pr... |
def _get_notmuch_message(self, mid):
"""returns :class:`notmuch.database.Message` with given id"""
mode = Database.MODE.READ_ONLY
db = Database(path=self.path, mode=mode)
try:
return db.find_message(mid)
except:
errmsg = 'no message with id %s exists!' % m... | returns :class:`notmuch.database.Message` with given id | Below is the the instruction that describes the task:
### Input:
returns :class:`notmuch.database.Message` with given id
### Response:
def _get_notmuch_message(self, mid):
"""returns :class:`notmuch.database.Message` with given id"""
mode = Database.MODE.READ_ONLY
db = Database(path=self.pa... |
def V_from_h(self, h, method='full'):
r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `se... | r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameter... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are... |
def suggest_spelling(q, wait=10, asynchronous=False, cached=False):
""" Returns list of suggested spelling corrections for the given query.
"""
return YahooSpelling(q, wait, asynchronous, cached) | Returns list of suggested spelling corrections for the given query. | Below is the the instruction that describes the task:
### Input:
Returns list of suggested spelling corrections for the given query.
### Response:
def suggest_spelling(q, wait=10, asynchronous=False, cached=False):
""" Returns list of suggested spelling corrections for the given query.
"""
re... |
def optimal_t_compressed(self, seq_pair, multiplicity, profiles=False, tol=1e-10):
"""
Find the optimal distance between the two sequences, for compressed sequences
Parameters
----------
seq_pair : compressed_sequence_pair
Compressed representation of sequences alo... | Find the optimal distance between the two sequences, for compressed sequences
Parameters
----------
seq_pair : compressed_sequence_pair
Compressed representation of sequences along a branch, either
as tuple of state pairs or as tuple of profiles.
multiplicity... | Below is the the instruction that describes the task:
### Input:
Find the optimal distance between the two sequences, for compressed sequences
Parameters
----------
seq_pair : compressed_sequence_pair
Compressed representation of sequences along a branch, either
as... |
def tileserver_optimized_raster(src, dest):
""" This method converts a raster to a tileserver optimized raster.
The method will reproject the raster to align to the xyz system, in resolution and projection
It will also create overviews
And finally it will arragne the raster in a cog way.
... | This method converts a raster to a tileserver optimized raster.
The method will reproject the raster to align to the xyz system, in resolution and projection
It will also create overviews
And finally it will arragne the raster in a cog way.
You could take the dest file upload it to a web... | Below is the the instruction that describes the task:
### Input:
This method converts a raster to a tileserver optimized raster.
The method will reproject the raster to align to the xyz system, in resolution and projection
It will also create overviews
And finally it will arragne the raster ... |
def filedet(name, fobj=None, suffix=None):
"""
Detect file type by filename.
:param name: file name
:param fobj: file object
:param suffix: file suffix like ``py``, ``.py``
:return: file type full name, such as ``python``, ``bash``
"""
name = name or (fobj and fobj.name) or suffix
s... | Detect file type by filename.
:param name: file name
:param fobj: file object
:param suffix: file suffix like ``py``, ``.py``
:return: file type full name, such as ``python``, ``bash`` | Below is the the instruction that describes the task:
### Input:
Detect file type by filename.
:param name: file name
:param fobj: file object
:param suffix: file suffix like ``py``, ``.py``
:return: file type full name, such as ``python``, ``bash``
### Response:
def filedet(name, fobj=None, suffi... |
def get_csbi(filehandle=None):
"""
Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout
"""
if filehandle is None:
filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno())
csbi = ConsoleScreenBufferInfo()
KERNEL32.GetConsoleScreenBufferInfo(filehandle, ctype... | Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout | Below is the the instruction that describes the task:
### Input:
Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout
### Response:
def get_csbi(filehandle=None):
"""
Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout
"""
if filehandle is None:... |
def _substitute(self, var_map, safe=False):
"""Implementation of :meth:`substitute`.
For internal use, the `safe` keyword argument allows to perform a
substitution on the `args` and `kwargs` of the expression only,
guaranteeing that the type of the expression does not change, at the
... | Implementation of :meth:`substitute`.
For internal use, the `safe` keyword argument allows to perform a
substitution on the `args` and `kwargs` of the expression only,
guaranteeing that the type of the expression does not change, at the
cost of possibly not returning a maximally simplif... | Below is the the instruction that describes the task:
### Input:
Implementation of :meth:`substitute`.
For internal use, the `safe` keyword argument allows to perform a
substitution on the `args` and `kwargs` of the expression only,
guaranteeing that the type of the expression does not chan... |
def deposit(
self,
beneficiary: Address,
total_deposit: TokenAmount,
block_identifier: BlockSpecification,
) -> None:
""" Deposit provided amount into the user-deposit contract
to the beneficiary's account. """
token_address = self.token_addre... | Deposit provided amount into the user-deposit contract
to the beneficiary's account. | Below is the the instruction that describes the task:
### Input:
Deposit provided amount into the user-deposit contract
to the beneficiary's account.
### Response:
def deposit(
self,
beneficiary: Address,
total_deposit: TokenAmount,
block_identifier: BlockSpe... |
def DeserializeFromDB(buffer):
"""
Deserialize full object.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
StorageItem:
"""
m = StreamManager.GetStream(buffer)
reader = BinaryReader(m)
... | Deserialize full object.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
StorageItem: | Below is the the instruction that describes the task:
### Input:
Deserialize full object.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
Returns:
StorageItem:
### Response:
def DeserializeFromDB(buffer):
"""
Deserialize... |
def fix_multi_T1w_source_name(in_files):
"""
Make up a generic source name when there are multiple T1s
>>> fix_multi_T1w_source_name([
... '/path/to/sub-045_ses-test_T1w.nii.gz',
... '/path/to/sub-045_ses-retest_T1w.nii.gz'])
'/path/to/sub-045_T1w.nii.gz'
"""
import os
from... | Make up a generic source name when there are multiple T1s
>>> fix_multi_T1w_source_name([
... '/path/to/sub-045_ses-test_T1w.nii.gz',
... '/path/to/sub-045_ses-retest_T1w.nii.gz'])
'/path/to/sub-045_T1w.nii.gz' | Below is the the instruction that describes the task:
### Input:
Make up a generic source name when there are multiple T1s
>>> fix_multi_T1w_source_name([
... '/path/to/sub-045_ses-test_T1w.nii.gz',
... '/path/to/sub-045_ses-retest_T1w.nii.gz'])
'/path/to/sub-045_T1w.nii.gz'
### Response:
... |
def _normalize_params(self, *paths, **query_kwargs):
"""a lot of the helper methods are very similar, this handles their arguments"""
kwargs = {}
if paths:
fragment = paths[-1]
if fragment:
if fragment.startswith("#"):
kwargs["fragment... | a lot of the helper methods are very similar, this handles their arguments | Below is the the instruction that describes the task:
### Input:
a lot of the helper methods are very similar, this handles their arguments
### Response:
def _normalize_params(self, *paths, **query_kwargs):
"""a lot of the helper methods are very similar, this handles their arguments"""
kwargs = {}... |
def setParams(self,params):
"""
set hyperParams
"""
self.params = params
self.clear_all()
self._notify() | set hyperParams | Below is the the instruction that describes the task:
### Input:
set hyperParams
### Response:
def setParams(self,params):
"""
set hyperParams
"""
self.params = params
self.clear_all()
self._notify() |
def stats(args):
"""
%prog stats agpfile
Print out a report for length of gaps and components.
"""
from jcvi.utils.table import tabulate
p = OptionParser(stats.__doc__)
p.add_option("--warn", default=False, action="store_true",
help="Warnings on small component spans [defa... | %prog stats agpfile
Print out a report for length of gaps and components. | Below is the the instruction that describes the task:
### Input:
%prog stats agpfile
Print out a report for length of gaps and components.
### Response:
def stats(args):
"""
%prog stats agpfile
Print out a report for length of gaps and components.
"""
from jcvi.utils.table import tabulate... |
def get_stats(self):
"""
Returns some statistics.
:returns: a tuple containing bytes send, received, send errors, recv errors
"""
sent = ctypes.c_uint32()
recv = ctypes.c_uint32()
send_errors = ctypes.c_uint32()
recv_errors = ctypes.c_uint32()
res... | Returns some statistics.
:returns: a tuple containing bytes send, received, send errors, recv errors | Below is the the instruction that describes the task:
### Input:
Returns some statistics.
:returns: a tuple containing bytes send, received, send errors, recv errors
### Response:
def get_stats(self):
"""
Returns some statistics.
:returns: a tuple containing bytes send, received, ... |
def _normalize(c):
"""
Convert a byte-like value into a canonical byte (a value of type 'bytes' of len 1)
:param c:
:return:
"""
if isinstance(c, int):
return bytes([c])
elif isinstance(c, str):
return bytes([ord(c)])
else:
return c | Convert a byte-like value into a canonical byte (a value of type 'bytes' of len 1)
:param c:
:return: | Below is the the instruction that describes the task:
### Input:
Convert a byte-like value into a canonical byte (a value of type 'bytes' of len 1)
:param c:
:return:
### Response:
def _normalize(c):
"""
Convert a byte-like value into a canonical byte (a value of type 'bytes' of len 1)
:param... |
def format(self):
''' Format table to print out
'''
self.max_lengths = []
for row in self.rows:
if len(self.max_lengths) < len(row):
self.max_lengths += [0] * (len(row) - len(self.max_lengths))
for idx, val in enumerate(row):
len_ce... | Format table to print out | Below is the the instruction that describes the task:
### Input:
Format table to print out
### Response:
def format(self):
''' Format table to print out
'''
self.max_lengths = []
for row in self.rows:
if len(self.max_lengths) < len(row):
self.max_lengths ... |
def create_pipfile(self, python=None):
"""Creates the Pipfile, filled with juicy defaults."""
from .vendor.pip_shims.shims import (
ConfigOptionParser, make_option_group, index_group
)
config_parser = ConfigOptionParser(name=self.name)
config_parser.add_option_group(... | Creates the Pipfile, filled with juicy defaults. | Below is the the instruction that describes the task:
### Input:
Creates the Pipfile, filled with juicy defaults.
### Response:
def create_pipfile(self, python=None):
"""Creates the Pipfile, filled with juicy defaults."""
from .vendor.pip_shims.shims import (
ConfigOptionParser, make_op... |
def _pick_statement(self, block_address, stmt_idx):
"""
Include a statement in the final slice.
:param int block_address: Address of the basic block.
:param int stmt_idx: Statement ID.
"""
# TODO: Support context-sensitivity
# Sanity check
if n... | Include a statement in the final slice.
:param int block_address: Address of the basic block.
:param int stmt_idx: Statement ID. | Below is the the instruction that describes the task:
### Input:
Include a statement in the final slice.
:param int block_address: Address of the basic block.
:param int stmt_idx: Statement ID.
### Response:
def _pick_statement(self, block_address, stmt_idx):
"""
Include a... |
def rfind(values, value):
""" :return: the highest index in values where value is found, or -1 """
if isinstance(values, STRING_TYPES):
try:
return values.rfind(value)
except TypeError:
# Python 3 compliance: search for str values in bytearray
return values.r... | :return: the highest index in values where value is found, or -1 | Below is the the instruction that describes the task:
### Input:
:return: the highest index in values where value is found, or -1
### Response:
def rfind(values, value):
""" :return: the highest index in values where value is found, or -1 """
if isinstance(values, STRING_TYPES):
try:
r... |
def dms2dec(dms):
"""
Convert latitude from degrees,minutes,seconds in string or 3-array
format to decimal degrees.
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
# Be careful here, degree needs to be a float so that negative zero
# can have its signbit set:
# http:... | Convert latitude from degrees,minutes,seconds in string or 3-array
format to decimal degrees. | Below is the the instruction that describes the task:
### Input:
Convert latitude from degrees,minutes,seconds in string or 3-array
format to decimal degrees.
### Response:
def dms2dec(dms):
"""
Convert latitude from degrees,minutes,seconds in string or 3-array
format to decimal degrees.
"""
... |
def ApproximateDistanceBetweenStops(stop1, stop2):
"""Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere."""
if (stop1.stop_lat is None or stop1.stop_lon is None or
stop2.stop_lat is None or stop2.stop_lon is None):
return None
return ApproximateDistance(stop1.stop... | Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere. | Below is the the instruction that describes the task:
### Input:
Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere.
### Response:
def ApproximateDistanceBetweenStops(stop1, stop2):
"""Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere... |
def pdf_merge(inputs: [str], output: str, delete: bool = False):
"""
Merge multiple Pdf input files in one output file.
:param inputs: input files
:param output: output file
:param delete: delete input files after completion if true
"""
writer = PdfFileWriter()
if os.path.isfile(output)... | Merge multiple Pdf input files in one output file.
:param inputs: input files
:param output: output file
:param delete: delete input files after completion if true | Below is the the instruction that describes the task:
### Input:
Merge multiple Pdf input files in one output file.
:param inputs: input files
:param output: output file
:param delete: delete input files after completion if true
### Response:
def pdf_merge(inputs: [str], output: str, delete: bool = Fal... |
def to_ansi_24bit(self):
"""
Convert to ANSI 24-bit
:return:
"""
res = []
for i in self.parts:
res.append(i.to_ansi_24bit())
return ''.join(res).encode('utf8') | Convert to ANSI 24-bit
:return: | Below is the the instruction that describes the task:
### Input:
Convert to ANSI 24-bit
:return:
### Response:
def to_ansi_24bit(self):
"""
Convert to ANSI 24-bit
:return:
"""
res = []
for i in self.parts:
res.append(i.to_ansi_24bit())
ret... |
def save(self):
"""
Write data to user config file.
"""
with open(self._user_config_file, 'w', encoding='utf-8') as f:
self.write(f) | Write data to user config file. | Below is the the instruction that describes the task:
### Input:
Write data to user config file.
### Response:
def save(self):
"""
Write data to user config file.
"""
with open(self._user_config_file, 'w', encoding='utf-8') as f:
self.write(f) |
def get_message(message, *args, **kwargs):
"""Helper to get internal messages outside this instance"""
msg = current_app.extensions['simplelogin'].messages.get(message)
if msg and (args or kwargs):
return msg.format(*args, **kwargs)
return msg | Helper to get internal messages outside this instance | Below is the the instruction that describes the task:
### Input:
Helper to get internal messages outside this instance
### Response:
def get_message(message, *args, **kwargs):
"""Helper to get internal messages outside this instance"""
msg = current_app.extensions['simplelogin'].messages.get(messag... |
def load_bernoulli_mnist_dataset(directory, split_name):
"""Returns Hugo Larochelle's binary static MNIST tf.data.Dataset."""
amat_file = download(directory, FILE_TEMPLATE.format(split=split_name))
dataset = tf.data.TextLineDataset(amat_file)
str_to_arr = lambda string: np.array([c == b"1" for c in string.split... | Returns Hugo Larochelle's binary static MNIST tf.data.Dataset. | Below is the the instruction that describes the task:
### Input:
Returns Hugo Larochelle's binary static MNIST tf.data.Dataset.
### Response:
def load_bernoulli_mnist_dataset(directory, split_name):
"""Returns Hugo Larochelle's binary static MNIST tf.data.Dataset."""
amat_file = download(directory, FILE_TEMPLA... |
def _find_max_beta_token_len():
"""
Finds the maximum length of a single betacode token.
Returns:
The length of the longest key in the betacode map, which corresponds to the
longest single betacode token.
"""
max_beta_len = -1
for beta, uni in _map.BETACODE_MAP.items():
if len(b... | Finds the maximum length of a single betacode token.
Returns:
The length of the longest key in the betacode map, which corresponds to the
longest single betacode token. | Below is the the instruction that describes the task:
### Input:
Finds the maximum length of a single betacode token.
Returns:
The length of the longest key in the betacode map, which corresponds to the
longest single betacode token.
### Response:
def _find_max_beta_token_len():
"""
Finds the ... |
def seq_2_DbDevExportInfos(seq, vec=None):
"""Converts a python sequence<DbDevExportInfo> object to a :class:`tango.DbDevExportInfos`
:param seq: the sequence of DbDevExportInfo
:type seq: sequence<DbDevExportInfo>
:param vec: (optional, default is None) an :class:`tango.DbDevExportInfos`
... | Converts a python sequence<DbDevExportInfo> object to a :class:`tango.DbDevExportInfos`
:param seq: the sequence of DbDevExportInfo
:type seq: sequence<DbDevExportInfo>
:param vec: (optional, default is None) an :class:`tango.DbDevExportInfos`
to be filled. If None is given,... | Below is the the instruction that describes the task:
### Input:
Converts a python sequence<DbDevExportInfo> object to a :class:`tango.DbDevExportInfos`
:param seq: the sequence of DbDevExportInfo
:type seq: sequence<DbDevExportInfo>
:param vec: (optional, default is None) an :class:`tango.... |
def remove_namespaces(self, rpc_reply):
"""remove xmlns attributes from rpc reply"""
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=True)
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser)
self.__transform = etree.XSLT(self... | remove xmlns attributes from rpc reply | Below is the the instruction that describes the task:
### Input:
remove xmlns attributes from rpc reply
### Response:
def remove_namespaces(self, rpc_reply):
"""remove xmlns attributes from rpc reply"""
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=Tru... |
def travis_permissions(cls):
"""
Set permissions in order to avoid issues before commiting.
"""
if PyFunceble.CONFIGURATION["travis"]:
try:
build_dir = PyFunceble.environ["TRAVIS_BUILD_DIR"]
commands = [
"sudo chown -R trav... | Set permissions in order to avoid issues before commiting. | Below is the the instruction that describes the task:
### Input:
Set permissions in order to avoid issues before commiting.
### Response:
def travis_permissions(cls):
"""
Set permissions in order to avoid issues before commiting.
"""
if PyFunceble.CONFIGURATION["travis"]:
... |
def dev_tools_installer(cv, ctx, site):
"""
Installer factory
@param cv: Current version (The version of Developer Tools we are installing)
@type cv: ips_vagrant.common.version.Version
@return: Installer instance
@rtype: ips_vagrant.installer.dev_tools.latest.DevToolsInstaller
"""
... | Installer factory
@param cv: Current version (The version of Developer Tools we are installing)
@type cv: ips_vagrant.common.version.Version
@return: Installer instance
@rtype: ips_vagrant.installer.dev_tools.latest.DevToolsInstaller | Below is the the instruction that describes the task:
### Input:
Installer factory
@param cv: Current version (The version of Developer Tools we are installing)
@type cv: ips_vagrant.common.version.Version
@return: Installer instance
@rtype: ips_vagrant.installer.dev_tools.latest.DevToolsI... |
def are_imaging_dicoms(dicom_input):
"""
This function will check the dicom headers to see which type of series it is
Possibilities are fMRI, DTI, Anatomical (if no clear type is found anatomical is used)
:param dicom_input: directory with dicom files or a list of dicom objects
"""
# if it is ... | This function will check the dicom headers to see which type of series it is
Possibilities are fMRI, DTI, Anatomical (if no clear type is found anatomical is used)
:param dicom_input: directory with dicom files or a list of dicom objects | Below is the the instruction that describes the task:
### Input:
This function will check the dicom headers to see which type of series it is
Possibilities are fMRI, DTI, Anatomical (if no clear type is found anatomical is used)
:param dicom_input: directory with dicom files or a list of dicom objects
### ... |
def matrix_height(self, zoom):
"""
Tile matrix height (number of rows) at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
height = int(math.ceil(self.grid.shape.height * 2**(zoom) / self.metatiling))
return 1 if height < 1 else height | Tile matrix height (number of rows) at zoom level.
- zoom: zoom level | Below is the the instruction that describes the task:
### Input:
Tile matrix height (number of rows) at zoom level.
- zoom: zoom level
### Response:
def matrix_height(self, zoom):
"""
Tile matrix height (number of rows) at zoom level.
- zoom: zoom level
"""
validat... |
def create_config_files(directory):
"""
Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return:
"""
# Some constant strings
config_zip_url = "https://s3-us-west-1.amazonaws.com/heartbleed/linux/linux-files.zip"
if not os.path.exists(di... | Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return: | Below is the the instruction that describes the task:
### Input:
Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return:
### Response:
def create_config_files(directory):
"""
Initialize directory ready for vpn walker
:param directory: the path... |
def order_limit(self, timeInForce=TIME_IN_FORCE_GTC, **params):
"""Send in a new limit order
Any order with an icebergQty MUST have timeInForce set to GTC.
:param symbol: required
:type symbol: str
:param side: required
:type side: str
:param quantity: required
... | Send in a new limit order
Any order with an icebergQty MUST have timeInForce set to GTC.
:param symbol: required
:type symbol: str
:param side: required
:type side: str
:param quantity: required
:type quantity: decimal
:param price: required
:typ... | Below is the the instruction that describes the task:
### Input:
Send in a new limit order
Any order with an icebergQty MUST have timeInForce set to GTC.
:param symbol: required
:type symbol: str
:param side: required
:type side: str
:param quantity: required
... |
def int_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the integral flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
"""
ebins = 10**np.linspace(np.log10(self.ebins[0]),
np.log10(self.eb... | Compute the integral flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``. | Below is the the instruction that describes the task:
### Input:
Compute the integral flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
### Response:
def int_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the integral flux threshold... |
def adjust_weights_recfile(self, recfile=None,original_ceiling=True):
"""adjusts the weights by group of the observations based on the phi components
in a pest record file so that total phi is equal to the number of
non-zero weighted observations
Parameters
----------
re... | adjusts the weights by group of the observations based on the phi components
in a pest record file so that total phi is equal to the number of
non-zero weighted observations
Parameters
----------
recfile : str
record file name. If None, try to use a record file
... | Below is the the instruction that describes the task:
### Input:
adjusts the weights by group of the observations based on the phi components
in a pest record file so that total phi is equal to the number of
non-zero weighted observations
Parameters
----------
recfile : str
... |
def append_minidom_xml_to_elementtree_xml(parent, xml, recursive=False, attributes=None):
"""
Recursively,
Given an ElementTree.Element as parent, and a minidom instance as xml,
append the tags and content from xml to parent
Used primarily for adding a snippet of XML with <italic> tags
attribute... | Recursively,
Given an ElementTree.Element as parent, and a minidom instance as xml,
append the tags and content from xml to parent
Used primarily for adding a snippet of XML with <italic> tags
attributes: a list of attribute names to copy | Below is the the instruction that describes the task:
### Input:
Recursively,
Given an ElementTree.Element as parent, and a minidom instance as xml,
append the tags and content from xml to parent
Used primarily for adding a snippet of XML with <italic> tags
attributes: a list of attribute names to c... |
def before_render(self):
"""Before template render hook
"""
# Render the Add button if the user has the AddClient permission
if check_permission(AddClient, self.context):
self.context_actions[_("Add")] = {
"url": "createObject?type_name=Client",
... | Before template render hook | Below is the the instruction that describes the task:
### Input:
Before template render hook
### Response:
def before_render(self):
"""Before template render hook
"""
# Render the Add button if the user has the AddClient permission
if check_permission(AddClient, self.context):
... |
def terminate(self, signal_chain=KILL_CHAIN, kill_wait=KILL_WAIT_SEC, purge=True):
"""Ensure a process is terminated by sending a chain of kill signals (SIGTERM, SIGKILL)."""
alive = self.is_alive()
if alive:
logger.debug('terminating {}'.format(self._name))
for signal_type in signal_chain:
... | Ensure a process is terminated by sending a chain of kill signals (SIGTERM, SIGKILL). | Below is the the instruction that describes the task:
### Input:
Ensure a process is terminated by sending a chain of kill signals (SIGTERM, SIGKILL).
### Response:
def terminate(self, signal_chain=KILL_CHAIN, kill_wait=KILL_WAIT_SEC, purge=True):
"""Ensure a process is terminated by sending a chain of kill si... |
def on_configurationdone_request(self, py_db, request):
'''
:param ConfigurationDoneRequest request:
'''
self.api.run(py_db)
configuration_done_response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True... | :param ConfigurationDoneRequest request: | Below is the the instruction that describes the task:
### Input:
:param ConfigurationDoneRequest request:
### Response:
def on_configurationdone_request(self, py_db, request):
'''
:param ConfigurationDoneRequest request:
'''
self.api.run(py_db)
configuration_done_response = ... |
def parse_flask_section(self):
'''Parse the [flask] section of your config and hand off the config
to the app in context.
Config vars should have the same name as their flask equivalent except
in all lower-case.'''
if self.has_section('flask'):
for item in self.items... | Parse the [flask] section of your config and hand off the config
to the app in context.
Config vars should have the same name as their flask equivalent except
in all lower-case. | Below is the the instruction that describes the task:
### Input:
Parse the [flask] section of your config and hand off the config
to the app in context.
Config vars should have the same name as their flask equivalent except
in all lower-case.
### Response:
def parse_flask_section(self):
... |
def post(self, request, *args, **kwargs):
""" Triggers the task that sends invitation messages
"""
status = 201
accepted = {"accepted": True}
send_invite_messages.apply_async()
return Response(accepted, status=status) | Triggers the task that sends invitation messages | Below is the the instruction that describes the task:
### Input:
Triggers the task that sends invitation messages
### Response:
def post(self, request, *args, **kwargs):
""" Triggers the task that sends invitation messages
"""
status = 201
accepted = {"accepted": True}
send_... |
def regularization(variables, regtype, regcoef, name="regularization"):
"""Compute the regularization tensor.
Parameters
----------
variables : list of tf.Variable
List of model variables.
regtype : str
Type of regularization. Can be ["none", "l1", "l2"... | Compute the regularization tensor.
Parameters
----------
variables : list of tf.Variable
List of model variables.
regtype : str
Type of regularization. Can be ["none", "l1", "l2"]
regcoef : float,
Regularization coefficient.
name :... | Below is the the instruction that describes the task:
### Input:
Compute the regularization tensor.
Parameters
----------
variables : list of tf.Variable
List of model variables.
regtype : str
Type of regularization. Can be ["none", "l1", "l2"]
reg... |
def camera_position(self):
""" Returns camera position of active render window """
return [self.camera.GetPosition(),
self.camera.GetFocalPoint(),
self.camera.GetViewUp()] | Returns camera position of active render window | Below is the the instruction that describes the task:
### Input:
Returns camera position of active render window
### Response:
def camera_position(self):
""" Returns camera position of active render window """
return [self.camera.GetPosition(),
self.camera.GetFocalPoint(),
... |
def set_namespace_view_settings(self):
"""Set the namespace view settings"""
if self.namespacebrowser:
settings = to_text_string(
self.namespacebrowser.get_view_settings())
code =(u"get_ipython().kernel.namespace_view_settings = %s" %
settings)
... | Set the namespace view settings | Below is the the instruction that describes the task:
### Input:
Set the namespace view settings
### Response:
def set_namespace_view_settings(self):
"""Set the namespace view settings"""
if self.namespacebrowser:
settings = to_text_string(
self.namespacebrowser.get_view... |
def require_single_root_target(self):
"""If a single target was specified on the cmd line, returns that target.
Otherwise throws TaskError.
:API: public
"""
target_roots = self.context.target_roots
if len(target_roots) == 0:
raise TaskError('No target specified.')
elif len(target_roo... | If a single target was specified on the cmd line, returns that target.
Otherwise throws TaskError.
:API: public | Below is the the instruction that describes the task:
### Input:
If a single target was specified on the cmd line, returns that target.
Otherwise throws TaskError.
:API: public
### Response:
def require_single_root_target(self):
"""If a single target was specified on the cmd line, returns that target... |
def commit_check(self, commands="", req_format="text"):
""" Execute a commit check operation.
Purpose: This method will take in string of multiple commands,
| and perform and 'commit check' on the device to ensure
| the commands are syntactically correct. The response can
... | Execute a commit check operation.
Purpose: This method will take in string of multiple commands,
| and perform and 'commit check' on the device to ensure
| the commands are syntactically correct. The response can
| be formatted as text or as xml.
@param com... | Below is the the instruction that describes the task:
### Input:
Execute a commit check operation.
Purpose: This method will take in string of multiple commands,
| and perform and 'commit check' on the device to ensure
| the commands are syntactically correct. The response can... |
def generate_s3_bucket():
"""Create the blockade bucket if not already there."""
logger.debug("[#] Setting up S3 bucket")
client = boto3.client("s3", region_name=PRIMARY_REGION)
buckets = client.list_buckets()
matches = [x for x in buckets.get('Buckets', list())
if x['Name'].startswit... | Create the blockade bucket if not already there. | Below is the the instruction that describes the task:
### Input:
Create the blockade bucket if not already there.
### Response:
def generate_s3_bucket():
"""Create the blockade bucket if not already there."""
logger.debug("[#] Setting up S3 bucket")
client = boto3.client("s3", region_name=PRIMARY_REGIO... |
def _annotate(ax, annotate, height, left, width):
"""Annotate axis with labels.
"""
annotate_yrange_factor = 0.010
xticks = np.array(left) + width / 2.0
ymin, ymax = ax.get_ylim()
yrange = ymax - ymin
# Reset ymax and ymin so there's enough room to see the annotation of
# the top-most
... | Annotate axis with labels. | Below is the the instruction that describes the task:
### Input:
Annotate axis with labels.
### Response:
def _annotate(ax, annotate, height, left, width):
"""Annotate axis with labels.
"""
annotate_yrange_factor = 0.010
xticks = np.array(left) + width / 2.0
ymin, ymax = ax.get_ylim()
yrang... |
def pjelpl(elin, plane):
"""
Project an ellipse onto a plane, orthogonally.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pjelpl_c.html
:param elin: A SPICE ellipse to be projected.
:type elin: spiceypy.utils.support_types.Ellipse
:param plane: A plane onto which elin is to be projec... | Project an ellipse onto a plane, orthogonally.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pjelpl_c.html
:param elin: A SPICE ellipse to be projected.
:type elin: spiceypy.utils.support_types.Ellipse
:param plane: A plane onto which elin is to be projected.
:type plane: supporttypes.Pl... | Below is the the instruction that describes the task:
### Input:
Project an ellipse onto a plane, orthogonally.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pjelpl_c.html
:param elin: A SPICE ellipse to be projected.
:type elin: spiceypy.utils.support_types.Ellipse
:param plane: A plane... |
def grok_keys(config):
"""Will retrieve a GPG key from either Keybase or GPG directly"""
key_ids = []
for key in config['pgp_keys']:
if key.startswith('keybase:'):
key_id = from_keybase(key[8:])
LOG.debug("Encrypting for keybase user %s", key[8:])
else:
if... | Will retrieve a GPG key from either Keybase or GPG directly | Below is the the instruction that describes the task:
### Input:
Will retrieve a GPG key from either Keybase or GPG directly
### Response:
def grok_keys(config):
"""Will retrieve a GPG key from either Keybase or GPG directly"""
key_ids = []
for key in config['pgp_keys']:
if key.startswith('keyb... |
def put(self):
"""Push the info represented by this ``Metric`` to CloudWatch."""
try:
self.cloudwatch.put_metric_data(
Namespace=self.namespace,
MetricData=[{
'MetricName': self.name,
'Value': self.value,... | Push the info represented by this ``Metric`` to CloudWatch. | Below is the the instruction that describes the task:
### Input:
Push the info represented by this ``Metric`` to CloudWatch.
### Response:
def put(self):
"""Push the info represented by this ``Metric`` to CloudWatch."""
try:
self.cloudwatch.put_metric_data(
Namespace... |
def _ss(data, c=None):
"""Return sum of square deviations of sequence data.
If ``c`` is None, the mean is calculated in one pass, and the deviations
from the mean are calculated in a second pass. Otherwise, deviations are
calculated from ``c`` as given. Use the second case with care, as it can
lead... | Return sum of square deviations of sequence data.
If ``c`` is None, the mean is calculated in one pass, and the deviations
from the mean are calculated in a second pass. Otherwise, deviations are
calculated from ``c`` as given. Use the second case with care, as it can
lead to garbage results. | Below is the the instruction that describes the task:
### Input:
Return sum of square deviations of sequence data.
If ``c`` is None, the mean is calculated in one pass, and the deviations
from the mean are calculated in a second pass. Otherwise, deviations are
calculated from ``c`` as given. Use the se... |
def list_floating_ip_actions(self, ip_addr):
"""
Retrieve a list of all actions that have been executed on a Floating IP.
"""
if self.api_version == 2:
json = self.request('/floating_ips/' + ip_addr + '/actions')
return json['actions']
else:
ra... | Retrieve a list of all actions that have been executed on a Floating IP. | Below is the the instruction that describes the task:
### Input:
Retrieve a list of all actions that have been executed on a Floating IP.
### Response:
def list_floating_ip_actions(self, ip_addr):
"""
Retrieve a list of all actions that have been executed on a Floating IP.
"""
if se... |
def _get_base_component(self):
"""Returns Component protobuf message"""
comp = topology_pb2.Component()
comp.name = self.name
comp.spec = topology_pb2.ComponentObjectSpec.Value("PYTHON_CLASS_NAME")
comp.class_name = self.python_class_path
comp.config.CopyFrom(self._get_comp_config())
return ... | Returns Component protobuf message | Below is the the instruction that describes the task:
### Input:
Returns Component protobuf message
### Response:
def _get_base_component(self):
"""Returns Component protobuf message"""
comp = topology_pb2.Component()
comp.name = self.name
comp.spec = topology_pb2.ComponentObjectSpec.Value("PYTHON_... |
def get_rendition_stretch_size(spec, input_w, input_h, output_scale):
""" Determine the scale-crop size given the provided spec """
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
... | Determine the scale-crop size given the provided spec | Below is the the instruction that describes the task:
### Input:
Determine the scale-crop size given the provided spec
### Response:
def get_rendition_stretch_size(spec, input_w, input_h, output_scale):
""" Determine the scale-crop size given the provided spec """
width = input_w
height = ... |
def cookie_get(self, name):
"""
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
"""
if not hasattr(self, 'cookies'):
return None
if self.cookies.get(name):
return self.cookies.get(name)... | Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found. | Below is the the instruction that describes the task:
### Input:
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
### Response:
def cookie_get(self, name):
"""
Check for a cookie value by name.... |
def trt_pmf(matrices):
"""
Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type
"""
ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape
pmf = nu... | Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type | Below is the the instruction that describes the task:
### Input:
Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type
### Response:
def trt_pmf(matrices):
"""
... |
def setRepayments(self, *args, **kwargs):
"""Adds the repayments for this loan to a 'repayments' field.
Repayments are MambuRepayment objects.
Repayments get sorted by due date.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, is not always tr... | Adds the repayments for this loan to a 'repayments' field.
Repayments are MambuRepayment objects.
Repayments get sorted by due date.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, is not always true that
just 1 request was done. It may be ... | Below is the the instruction that describes the task:
### Input:
Adds the repayments for this loan to a 'repayments' field.
Repayments are MambuRepayment objects.
Repayments get sorted by due date.
Returns the number of requests done to Mambu.
.. todo:: since pagination logic was added, ... |
def select_window(self, target_window):
"""
Return :class:`Window` selected via ``$ tmux select-window``.
Parameters
----------
window : str
``target_window`` also 'last-window' (``-l``), 'next-window'
(``-n``), or 'previous-window' (``-p``)
Retu... | Return :class:`Window` selected via ``$ tmux select-window``.
Parameters
----------
window : str
``target_window`` also 'last-window' (``-l``), 'next-window'
(``-n``), or 'previous-window' (``-p``)
Returns
-------
:class:`Window`
Notes
... | Below is the the instruction that describes the task:
### Input:
Return :class:`Window` selected via ``$ tmux select-window``.
Parameters
----------
window : str
``target_window`` also 'last-window' (``-l``), 'next-window'
(``-n``), or 'previous-window' (``-p``)
... |
def aggregate(args):
"""
Aggregate the results from multiple analyses into a single file.
"""
_ok_to_clobber(args, [args.output_filename[0]], "")
logger.debug("Aggregating to {}".format(args.output_filename[0]))
from astropy.table import Table
# What header keys should be passed to the fi... | Aggregate the results from multiple analyses into a single file. | Below is the the instruction that describes the task:
### Input:
Aggregate the results from multiple analyses into a single file.
### Response:
def aggregate(args):
"""
Aggregate the results from multiple analyses into a single file.
"""
_ok_to_clobber(args, [args.output_filename[0]], "")
logg... |
def _nderiv(self,l,n):
"""
NAME:
_nderiv
PURPOSE:
evaluate the derivative w.r.t. nu for this potential
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal coordinate nu
OUTPUT:
derivative w.r.t. nu
... | NAME:
_nderiv
PURPOSE:
evaluate the derivative w.r.t. nu for this potential
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal coordinate nu
OUTPUT:
derivative w.r.t. nu
HISTORY:
2015-02-15 - Writ... | Below is the the instruction that describes the task:
### Input:
NAME:
_nderiv
PURPOSE:
evaluate the derivative w.r.t. nu for this potential
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal coordinate nu
OUTPUT:
... |
def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
... | Parse a template or argument at the head of the wikicode string. | Below is the the instruction that describes the task:
### Input:
Parse a template or argument at the head of the wikicode string.
### Response:
def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
wh... |
def run_pipeline_steps(steps, context):
"""Run the run_step(context) method of each step in steps.
Args:
steps: list. Sequence of Steps to execute
context: pypyr.context.Context. The pypyr context. Will mutate.
"""
logger.debug("starting")
assert isinstance(
context, dict), ... | Run the run_step(context) method of each step in steps.
Args:
steps: list. Sequence of Steps to execute
context: pypyr.context.Context. The pypyr context. Will mutate. | Below is the the instruction that describes the task:
### Input:
Run the run_step(context) method of each step in steps.
Args:
steps: list. Sequence of Steps to execute
context: pypyr.context.Context. The pypyr context. Will mutate.
### Response:
def run_pipeline_steps(steps, context):
"""... |
def _init_command(self, action, flags=None):
''' a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)... | a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)
not implemented yet. | Below is the the instruction that describes the task:
### Input:
a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e... |
def set_field(self, name, value, parse=False):
""" Set the value of a field
"""
# explicit getitem needed for ValueField
try:
item = dict.__getitem__(self, name)
item.set( item.parse(value) if parse else value )
except ValidationError as err:
... | Set the value of a field | Below is the the instruction that describes the task:
### Input:
Set the value of a field
### Response:
def set_field(self, name, value, parse=False):
""" Set the value of a field
"""
# explicit getitem needed for ValueField
try:
item = dict.__getitem__(self, name)
... |
def create_parser(default_name: str) -> argparse.ArgumentParser:
"""
Creates the default brewblox_service ArgumentParser.
Service-agnostic arguments are added.
The parser allows calling code to add additional arguments before using it in create_app()
Args:
default_name (str):
d... | Creates the default brewblox_service ArgumentParser.
Service-agnostic arguments are added.
The parser allows calling code to add additional arguments before using it in create_app()
Args:
default_name (str):
default value for the --name commandline argument.
Returns:
argpa... | Below is the the instruction that describes the task:
### Input:
Creates the default brewblox_service ArgumentParser.
Service-agnostic arguments are added.
The parser allows calling code to add additional arguments before using it in create_app()
Args:
default_name (str):
default v... |
def build_services(did, service_descriptors):
"""
Build a list of services.
:param did: DID, str
:param service_descriptors: List of tuples of length 2. The first item must be one of
ServiceTypes
and the second item is a dict of parameters and values required by the serv... | Build a list of services.
:param did: DID, str
:param service_descriptors: List of tuples of length 2. The first item must be one of
ServiceTypes
and the second item is a dict of parameters and values required by the service
:return: List of Services | Below is the the instruction that describes the task:
### Input:
Build a list of services.
:param did: DID, str
:param service_descriptors: List of tuples of length 2. The first item must be one of
ServiceTypes
and the second item is a dict of parameters and values required by the s... |
def get_instance(self, payload):
"""
Build an instance of TranscriptionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recording.transcription... | Build an instance of TranscriptionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of TranscriptionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.recording.transcription.TranscriptionInstance
:rtype: twilio.rest.api.v2010.account.recordi... |
def dijkstra(graph, start, end=None):
"""
Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the star... | Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the en... | Below is the the instruction that describes the task:
### Input:
Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest p... |
def init_app(self, app):
""" Add ourselves into the app config and setup, and add a jinja function test """
app.config.setdefault(FEATURE_FLAGS_CONFIG, {})
app.config.setdefault(RAISE_ERROR_ON_MISSING_FEATURES, False)
if hasattr(app, "add_template_test"):
# flask 0.10 and higher has a proper hoo... | Add ourselves into the app config and setup, and add a jinja function test | Below is the the instruction that describes the task:
### Input:
Add ourselves into the app config and setup, and add a jinja function test
### Response:
def init_app(self, app):
""" Add ourselves into the app config and setup, and add a jinja function test """
app.config.setdefault(FEATURE_FLAGS_CONFIG, ... |
def from_tuples_dict(pair_dict):
'''pair_dict should be a dict mapping tuple (HET code, residue ID) -> (HET code, residue ID) e.g. {('MG ', 'A 204 ') : ('MG ', 'C 221 '), ...}.
HET codes and residue IDs should respectively correspond to columns 17:20 and 21:27 of the PDB file.
'''
lm ... | pair_dict should be a dict mapping tuple (HET code, residue ID) -> (HET code, residue ID) e.g. {('MG ', 'A 204 ') : ('MG ', 'C 221 '), ...}.
HET codes and residue IDs should respectively correspond to columns 17:20 and 21:27 of the PDB file. | Below is the the instruction that describes the task:
### Input:
pair_dict should be a dict mapping tuple (HET code, residue ID) -> (HET code, residue ID) e.g. {('MG ', 'A 204 ') : ('MG ', 'C 221 '), ...}.
HET codes and residue IDs should respectively correspond to columns 17:20 and 21:27 of the PDB file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.