code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_queue(cls, name, priority=0, **fields_if_new):
"""
Get, or create, and return the wanted queue.
If the queue is created, fields in fields_if_new will be set for the new
queue.
"""
queue_kwargs = {'name': name, 'priority': priority}
retries = 0
whil... | Get, or create, and return the wanted queue.
If the queue is created, fields in fields_if_new will be set for the new
queue. | Below is the the instruction that describes the task:
### Input:
Get, or create, and return the wanted queue.
If the queue is created, fields in fields_if_new will be set for the new
queue.
### Response:
def get_queue(cls, name, priority=0, **fields_if_new):
"""
Get, or create, and ... |
def _to_chimera(M, N, L, q):
"Converts a qubit's linear index to chimera coordinates."
return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) | Converts a qubit's linear index to chimera coordinates. | Below is the the instruction that describes the task:
### Input:
Converts a qubit's linear index to chimera coordinates.
### Response:
def _to_chimera(M, N, L, q):
"Converts a qubit's linear index to chimera coordinates."
return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) |
def parse(
version, strict=False # type: str # type: bool
): # type:(...) -> Union[Version, LegacyVersion]
"""
Parse the given version string and return either a :class:`Version` object
or a LegacyVersion object depending on if the given version is
a valid PEP 440 version or a legacy version.
... | Parse the given version string and return either a :class:`Version` object
or a LegacyVersion object depending on if the given version is
a valid PEP 440 version or a legacy version.
If strict=True only PEP 440 versions will be accepted. | Below is the the instruction that describes the task:
### Input:
Parse the given version string and return either a :class:`Version` object
or a LegacyVersion object depending on if the given version is
a valid PEP 440 version or a legacy version.
If strict=True only PEP 440 versions will be accepted.
... |
def get_all_constants():
"""
Get list of all uppercase, non-private globals (doesn't start with ``_``).
Returns:
list: Uppercase names defined in `globals()` (variables from this \
module).
"""
return filter(
lambda key: key.upper() == key and type(globals()[key]) in _... | Get list of all uppercase, non-private globals (doesn't start with ``_``).
Returns:
list: Uppercase names defined in `globals()` (variables from this \
module). | Below is the the instruction that describes the task:
### Input:
Get list of all uppercase, non-private globals (doesn't start with ``_``).
Returns:
list: Uppercase names defined in `globals()` (variables from this \
module).
### Response:
def get_all_constants():
"""
Get list of... |
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit... | Get parameter names for the estimator | Below is the the instruction that describes the task:
### Input:
Get parameter names for the estimator
### Response:
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init ... |
def run_for_time(self, duration: float=10.0) -> None:
'''Execute the tasky/asyncio event loop for `duration` seconds.'''
Log.debug('running event loop for %.1f seconds', duration)
try:
asyncio.ensure_future(self.init())
self.loop.run_until_complete(asyncio.sleep(duration... | Execute the tasky/asyncio event loop for `duration` seconds. | Below is the the instruction that describes the task:
### Input:
Execute the tasky/asyncio event loop for `duration` seconds.
### Response:
def run_for_time(self, duration: float=10.0) -> None:
'''Execute the tasky/asyncio event loop for `duration` seconds.'''
Log.debug('running event loop for %.1... |
def openflow_controller_controller_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow")
controller_name = ET.SubElement(openflow_controller,... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def openflow_controller_controller_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
openflow_controller = ET.SubElement(config, "openflow-controller", xml... |
def run_mp(songs):
"""
Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
"""
stats = Stats()
if CONFIG['debug']:
good = open('found', 'w')
bad = open('notfound', 'w')
logger.debug('Launching a pool of %d processes\n', CONFIG['jobcount'])
chunksize =... | Concurrently calls get_lyrics to fetch the lyrics of a large list of songs. | Below is the the instruction that describes the task:
### Input:
Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
### Response:
def run_mp(songs):
"""
Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
"""
stats = Stats()
if CONFIG['debug']:
... |
def _data_is_binary(self, data):
"""Check if the data contains binary components."""
if isinstance(data, six.binary_type):
return True
elif isinstance(data, list):
return functools.reduce(
lambda a, b: a or b, [self._data_is_binary(item)
... | Check if the data contains binary components. | Below is the the instruction that describes the task:
### Input:
Check if the data contains binary components.
### Response:
def _data_is_binary(self, data):
"""Check if the data contains binary components."""
if isinstance(data, six.binary_type):
return True
elif isinstance(dat... |
def select_options(self, options_prefix):
""" Select options from this selection, that are started with the specified prefix
:param options_prefix: name prefix of options that should be selected
:return: WConfigSelection
"""
return WConfigSelection(
self.config(), self.section(), self.option_prefix() + op... | Select options from this selection, that are started with the specified prefix
:param options_prefix: name prefix of options that should be selected
:return: WConfigSelection | Below is the the instruction that describes the task:
### Input:
Select options from this selection, that are started with the specified prefix
:param options_prefix: name prefix of options that should be selected
:return: WConfigSelection
### Response:
def select_options(self, options_prefix):
""" Select o... |
def create_file_vdev(size, *vdevs):
'''
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a while to return.
... | Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a while to return. | Below is the the instruction that describes the task:
### Input:
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a w... |
def make_report(plots, settings):
'''
Creates a fat html report based on the previously created files
plots is a list of Plot objects defined by a path and title
statsfile is the file to which the stats have been saved,
which is parsed to a table (rather dodgy)
'''
logging.info("Writing html... | Creates a fat html report based on the previously created files
plots is a list of Plot objects defined by a path and title
statsfile is the file to which the stats have been saved,
which is parsed to a table (rather dodgy) | Below is the the instruction that describes the task:
### Input:
Creates a fat html report based on the previously created files
plots is a list of Plot objects defined by a path and title
statsfile is the file to which the stats have been saved,
which is parsed to a table (rather dodgy)
### Response:
... |
def sentence(self):
"""
The sentence related to this mention
:getter: returns the sentence this mention relates to
:type: corenlp_xml.document.Sentence
"""
if self._sentence is None:
sentences = self._element.xpath('sentence/text()')
if len(sente... | The sentence related to this mention
:getter: returns the sentence this mention relates to
:type: corenlp_xml.document.Sentence | Below is the the instruction that describes the task:
### Input:
The sentence related to this mention
:getter: returns the sentence this mention relates to
:type: corenlp_xml.document.Sentence
### Response:
def sentence(self):
"""
The sentence related to this mention
:gett... |
def apply(self, resource):
"""
Apply filter to resource
:param resource: Image.Image
:return: Image.Image
"""
if not isinstance(resource, Image.Image):
raise ValueError('Unknown resource format')
resource_format = resource.format
if resource.m... | Apply filter to resource
:param resource: Image.Image
:return: Image.Image | Below is the the instruction that describes the task:
### Input:
Apply filter to resource
:param resource: Image.Image
:return: Image.Image
### Response:
def apply(self, resource):
"""
Apply filter to resource
:param resource: Image.Image
:return: Image.Image
... |
def count_between(self, min_score=None, max_score=None):
"""
Returns the number of members whose score is between *min_score* and
*max_score* (inclusive).
"""
min_score = float('-inf') if min_score is None else float(min_score)
max_score = float('inf') if max_score is Non... | Returns the number of members whose score is between *min_score* and
*max_score* (inclusive). | Below is the the instruction that describes the task:
### Input:
Returns the number of members whose score is between *min_score* and
*max_score* (inclusive).
### Response:
def count_between(self, min_score=None, max_score=None):
"""
Returns the number of members whose score is between *min... |
def account_product(self, product_id):
''' a method to retrieve details about a particular account product
{
"error": "",
"code": 200,
"method": "GET",
"url": "https://...",
"headers": { },
"json": {
... | a method to retrieve details about a particular account product
{
"error": "",
"code": 200,
"method": "GET",
"url": "https://...",
"headers": { },
"json": {
"productId": "3300",
"productName": "Capital... | Below is the the instruction that describes the task:
### Input:
a method to retrieve details about a particular account product
{
"error": "",
"code": 200,
"method": "GET",
"url": "https://...",
"headers": { },
"json": {
... |
def _set_defaults(self):
"""
Set default values to fields. We assume that they are not yet populated
as this method is called just after creation of a new pk.
"""
for field_name in self._fields:
if field_name in self._init_fields:
continue
... | Set default values to fields. We assume that they are not yet populated
as this method is called just after creation of a new pk. | Below is the the instruction that describes the task:
### Input:
Set default values to fields. We assume that they are not yet populated
as this method is called just after creation of a new pk.
### Response:
def _set_defaults(self):
"""
Set default values to fields. We assume that they are... |
def dispatch(self, **changes):
"""
Patch the swarm with changes and then trigger the swarm.
"""
self.patch(**changes)
trigger_url = self._vr._build_url(self.resource_uri, 'swarm/')
resp = self._vr.session.post(trigger_url)
resp.raise_for_status()
try:
... | Patch the swarm with changes and then trigger the swarm. | Below is the the instruction that describes the task:
### Input:
Patch the swarm with changes and then trigger the swarm.
### Response:
def dispatch(self, **changes):
"""
Patch the swarm with changes and then trigger the swarm.
"""
self.patch(**changes)
trigger_url = self._v... |
def posthoc_dscf(a, val_col=None, group_col=None, sort=False):
'''Dwass, Steel, Critchlow and Fligner all-pairs comparison test for a
one-factorial layout with non-normally distributed residuals. As opposed to
the all-pairs comparison procedures that depend on Kruskal ranks, the DSCF
test is basically ... | Dwass, Steel, Critchlow and Fligner all-pairs comparison test for a
one-factorial layout with non-normally distributed residuals. As opposed to
the all-pairs comparison procedures that depend on Kruskal ranks, the DSCF
test is basically an extension of the U-test as re-ranking is conducted for
each pair... | Below is the the instruction that describes the task:
### Input:
Dwass, Steel, Critchlow and Fligner all-pairs comparison test for a
one-factorial layout with non-normally distributed residuals. As opposed to
the all-pairs comparison procedures that depend on Kruskal ranks, the DSCF
test is basically an... |
def ReadTag(buffer, pos):
"""Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decodi... | Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decoding a varint)
for work that is... | Below is the the instruction that describes the task:
### Input:
Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work tha... |
def _ParseFileEntry(self, knowledge_base, file_entry):
"""Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Rais... | Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | Below is the the instruction that describes the task:
### Input:
Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
... |
def create_function_f_c(self):
"""condition function"""
return ca.Function(
'f_c',
[self.t, self.x, self.y, self.m, self.p, self.ng, self.nu],
[self.f_c],
['t', 'x', 'y', 'm', 'p', 'ng', 'nu'], ['c'], self.func_opt) | condition function | Below is the the instruction that describes the task:
### Input:
condition function
### Response:
def create_function_f_c(self):
"""condition function"""
return ca.Function(
'f_c',
[self.t, self.x, self.y, self.m, self.p, self.ng, self.nu],
[self.f_c],
... |
def rgb_to_hsv(self,RGB):
"linear rgb to hsv"
gammaRGB = self._gamma_rgb(RGB)
return self._ABC_to_DEF_by_fn(gammaRGB,rgb_to_hsv) | linear rgb to hsv | Below is the the instruction that describes the task:
### Input:
linear rgb to hsv
### Response:
def rgb_to_hsv(self,RGB):
"linear rgb to hsv"
gammaRGB = self._gamma_rgb(RGB)
return self._ABC_to_DEF_by_fn(gammaRGB,rgb_to_hsv) |
def _set_auto_watering(self, zoneid, value):
"""Private method to set auto_watering program."""
if not isinstance(value, bool):
return None
ddata = self.preupdate()
attr = 'zone{}_program_toggle'.format(zoneid)
try:
if not value:
ddata.pop... | Private method to set auto_watering program. | Below is the the instruction that describes the task:
### Input:
Private method to set auto_watering program.
### Response:
def _set_auto_watering(self, zoneid, value):
"""Private method to set auto_watering program."""
if not isinstance(value, bool):
return None
ddata = self.p... |
def gui():
"""remove libraries by GUI."""
sel = psidialogs.multi_choice(libraries(),
'select libraries to remove from %s!' % libraries_dir(),
title='remove boards')
print('%s selected' % sel)
if sel:
if psidialogs.ask_yes_no('... | remove libraries by GUI. | Below is the the instruction that describes the task:
### Input:
remove libraries by GUI.
### Response:
def gui():
"""remove libraries by GUI."""
sel = psidialogs.multi_choice(libraries(),
'select libraries to remove from %s!' % libraries_dir(),
... |
def auto_name_prefix(self):
"""
Generate platform prefix for cross-platform downloads.
"""
# if the platform is not native, auto_name would clobber native downloads.
# make a prefix to avoid this
native_system = std_platform.system()
native_machine = self.CPU_ALIA... | Generate platform prefix for cross-platform downloads. | Below is the the instruction that describes the task:
### Input:
Generate platform prefix for cross-platform downloads.
### Response:
def auto_name_prefix(self):
"""
Generate platform prefix for cross-platform downloads.
"""
# if the platform is not native, auto_name would clobber n... |
def set_sim_params(self, nparams, attr_params):
"""Store parameters in `params` in `h5file.root.parameters`.
`nparams` (dict)
A dict as returned by `get_params()` in `ParticlesSimulation()`
The format is:
keys:
used as parameter name
value... | Store parameters in `params` in `h5file.root.parameters`.
`nparams` (dict)
A dict as returned by `get_params()` in `ParticlesSimulation()`
The format is:
keys:
used as parameter name
values: (2-elements tuple)
first element is the ... | Below is the the instruction that describes the task:
### Input:
Store parameters in `params` in `h5file.root.parameters`.
`nparams` (dict)
A dict as returned by `get_params()` in `ParticlesSimulation()`
The format is:
keys:
used as parameter name
... |
def assignment(self):
"""
assignment ::= relation_name assign expression |
relation_name param_start attribute_list param_stop
assign expression
"""
lhs = Group(self.relation_name +
Optional(self.parenthesize(self.attribute_list)))
retu... | assignment ::= relation_name assign expression |
relation_name param_start attribute_list param_stop
assign expression | Below is the the instruction that describes the task:
### Input:
assignment ::= relation_name assign expression |
relation_name param_start attribute_list param_stop
assign expression
### Response:
def assignment(self):
"""
assignment ::= relation_name assign expression |
... |
def is_rfc1918(ip):
"""Checks to see if an IP address is used for local communications within
a private network as specified by RFC 1918
"""
if ip_between(ip, "10.0.0.0", "10.255.255.255"):
return True
elif ip_between(ip, "172.16.0.0", "172.31.255.255"):
return True
elif ip_betwe... | Checks to see if an IP address is used for local communications within
a private network as specified by RFC 1918 | Below is the the instruction that describes the task:
### Input:
Checks to see if an IP address is used for local communications within
a private network as specified by RFC 1918
### Response:
def is_rfc1918(ip):
"""Checks to see if an IP address is used for local communications within
a private networ... |
async def destroy_unit(self, *unit_names):
"""Destroy units by name.
"""
connection = self.connection()
app_facade = client.ApplicationFacade.from_connection(connection)
log.debug(
'Destroying unit%s %s',
's' if len(unit_names) == 1 else '',
... | Destroy units by name. | Below is the the instruction that describes the task:
### Input:
Destroy units by name.
### Response:
async def destroy_unit(self, *unit_names):
"""Destroy units by name.
"""
connection = self.connection()
app_facade = client.ApplicationFacade.from_connection(connection)
l... |
def _create_file(self, filename):
"""Ensure a new file is created and opened for writing."""
file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
return os.fdopen(file_descriptor, 'w') | Ensure a new file is created and opened for writing. | Below is the the instruction that describes the task:
### Input:
Ensure a new file is created and opened for writing.
### Response:
def _create_file(self, filename):
"""Ensure a new file is created and opened for writing."""
file_descriptor = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
... |
def stop_all_children(self):
'''Kill all workers.'''
# There's an unfortunate race condition if we try to log this
# case: we can't depend on the logging child actually receiving
# the log message before we kill it off. C'est la vie...
self.stop_log_child()
for pid in se... | Kill all workers. | Below is the the instruction that describes the task:
### Input:
Kill all workers.
### Response:
def stop_all_children(self):
'''Kill all workers.'''
# There's an unfortunate race condition if we try to log this
# case: we can't depend on the logging child actually receiving
# the l... |
def plot_hpars(HDD, hpars, sym):
"""
function to plot hysteresis parameters
deprecated (used in hysteresis_magic)
"""
plt.figure(num=HDD['hyst'])
X, Y = [], []
X.append(0)
Y.append(old_div(float(hpars['hysteresis_mr_moment']), float(
hpars['hysteresis_ms_moment'])))
X.append(... | function to plot hysteresis parameters
deprecated (used in hysteresis_magic) | Below is the the instruction that describes the task:
### Input:
function to plot hysteresis parameters
deprecated (used in hysteresis_magic)
### Response:
def plot_hpars(HDD, hpars, sym):
"""
function to plot hysteresis parameters
deprecated (used in hysteresis_magic)
"""
plt.figure(num=HD... |
def tables(self):
"""
:return: all tables stored in this database
"""
cursor = self.connection.cursor()
cursor.execute("show tables in %s" % self.db)
self._tables = [t.Table(r[0], con=self.connection, db=self.db) for r in cursor.fetchall()]
return self._tables | :return: all tables stored in this database | Below is the the instruction that describes the task:
### Input:
:return: all tables stored in this database
### Response:
def tables(self):
"""
:return: all tables stored in this database
"""
cursor = self.connection.cursor()
cursor.execute("show tables in %s" % self.db)
... |
def remove_and_append(self, index):
"""Remove previous entrances of a tab, and add it as the latest."""
while index in self:
self.remove(index)
self.append(index) | Remove previous entrances of a tab, and add it as the latest. | Below is the the instruction that describes the task:
### Input:
Remove previous entrances of a tab, and add it as the latest.
### Response:
def remove_and_append(self, index):
"""Remove previous entrances of a tab, and add it as the latest."""
while index in self:
self.remove(index)... |
def handle_error(self, request: Any, status: int = 500, exc: Any = None, message: Optional[str] = None) -> web.Response:
"""Handle errors.
Returns HTTP response with specific status code. Logs additional
information. It always closes current connection."""
if self.transport is None:
... | Handle errors.
Returns HTTP response with specific status code. Logs additional
information. It always closes current connection. | Below is the the instruction that describes the task:
### Input:
Handle errors.
Returns HTTP response with specific status code. Logs additional
information. It always closes current connection.
### Response:
def handle_error(self, request: Any, status: int = 500, exc: Any = None, message: Optiona... |
def has_attr(cls, attr_name):
"""Check to see if an attribute is defined for the model."""
if attr_name in cls.attrs:
return True
if isinstance(cls.primary_key_name, str) and cls.primary_key_name == attr_name:
return True
if isinstance(cls.primary_key_name, tuple) and attr_name in cls.prim... | Check to see if an attribute is defined for the model. | Below is the the instruction that describes the task:
### Input:
Check to see if an attribute is defined for the model.
### Response:
def has_attr(cls, attr_name):
"""Check to see if an attribute is defined for the model."""
if attr_name in cls.attrs:
return True
if isinstance(cls.primary_key_na... |
def build_dict(img_iterator):
"""
Build a dict from files from iterator.
{'absolute_filename': {'EXIF field': 'exif tag value'}}
Parse DateTime from filename in the same loop, added as 'TIME'.
"""
files_with_tags = dict()
for f in img_iterator:
with open(str(f.abspath()), 'rb... | Build a dict from files from iterator.
{'absolute_filename': {'EXIF field': 'exif tag value'}}
Parse DateTime from filename in the same loop, added as 'TIME'. | Below is the the instruction that describes the task:
### Input:
Build a dict from files from iterator.
{'absolute_filename': {'EXIF field': 'exif tag value'}}
Parse DateTime from filename in the same loop, added as 'TIME'.
### Response:
def build_dict(img_iterator):
"""
Build a dict from files... |
def has_comment(src):
"""Indicate whether an input line has (i.e. ends in, or is) a comment.
This uses tokenize, so it can distinguish comments from # inside strings.
Parameters
----------
src : string
A single line input string.
Returns
-------
Boolean: True if sour... | Indicate whether an input line has (i.e. ends in, or is) a comment.
This uses tokenize, so it can distinguish comments from # inside strings.
Parameters
----------
src : string
A single line input string.
Returns
-------
Boolean: True if source has a comment. | Below is the the instruction that describes the task:
### Input:
Indicate whether an input line has (i.e. ends in, or is) a comment.
This uses tokenize, so it can distinguish comments from # inside strings.
Parameters
----------
src : string
A single line input string.
Retur... |
def get(self):
"""API endpoint to get the related blocks for a transaction.
Return:
A ``list`` of ``block_id``s that contain the given transaction. The
list may be filtered when provided a status query parameter:
"valid", "invalid", "undecided".
"""
p... | API endpoint to get the related blocks for a transaction.
Return:
A ``list`` of ``block_id``s that contain the given transaction. The
list may be filtered when provided a status query parameter:
"valid", "invalid", "undecided". | Below is the the instruction that describes the task:
### Input:
API endpoint to get the related blocks for a transaction.
Return:
A ``list`` of ``block_id``s that contain the given transaction. The
list may be filtered when provided a status query parameter:
"valid", "i... |
def infer(cls, nij, Ti, root_state, fixed_pi=None, pc=5.0, gap_limit=0.01, **kwargs):
"""
Infer a GTR model by specifying the number of transitions and time spent in each
character. The basic equation that is being solved is
:math:`n_{ij} = pi_i W_{ij} T_j`
where :math:`n_{ij}`... | Infer a GTR model by specifying the number of transitions and time spent in each
character. The basic equation that is being solved is
:math:`n_{ij} = pi_i W_{ij} T_j`
where :math:`n_{ij}` are the transitions, :math:`pi_i` are the equilibrium
state frequencies, :math:`W_{ij}` is the "s... | Below is the the instruction that describes the task:
### Input:
Infer a GTR model by specifying the number of transitions and time spent in each
character. The basic equation that is being solved is
:math:`n_{ij} = pi_i W_{ij} T_j`
where :math:`n_{ij}` are the transitions, :math:`pi_i` ar... |
def get_region_for_chip(x, y, level=3):
"""Get the region word for the given chip co-ordinates.
Parameters
----------
x : int
x co-ordinate
y : int
y co-ordinate
level : int
Level of region to build. 0 is the most coarse and 3 is the finest.
When 3 is used the sp... | Get the region word for the given chip co-ordinates.
Parameters
----------
x : int
x co-ordinate
y : int
y co-ordinate
level : int
Level of region to build. 0 is the most coarse and 3 is the finest.
When 3 is used the specified region will ONLY select the given chip,... | Below is the the instruction that describes the task:
### Input:
Get the region word for the given chip co-ordinates.
Parameters
----------
x : int
x co-ordinate
y : int
y co-ordinate
level : int
Level of region to build. 0 is the most coarse and 3 is the finest.
... |
def iter_filtered_dir_entry(dir_entries, match_patterns, on_skip):
"""
Filter a list of DirEntryPath instances with the given pattern
:param dir_entries: list of DirEntryPath instances
:param match_patterns: used with Path.match()
e.g.: "__pycache__/*", "*.tmp", "*.cache"
:param on_skip: fu... | Filter a list of DirEntryPath instances with the given pattern
:param dir_entries: list of DirEntryPath instances
:param match_patterns: used with Path.match()
e.g.: "__pycache__/*", "*.tmp", "*.cache"
:param on_skip: function that will be called if 'match_patterns' hits.
e.g.:
def ... | Below is the the instruction that describes the task:
### Input:
Filter a list of DirEntryPath instances with the given pattern
:param dir_entries: list of DirEntryPath instances
:param match_patterns: used with Path.match()
e.g.: "__pycache__/*", "*.tmp", "*.cache"
:param on_skip: function tha... |
def newTextReaderFilename(URI):
"""Create an xmlTextReader structure fed with the resource at
@URI """
ret = libxml2mod.xmlNewTextReaderFilename(URI)
if ret is None:raise treeError('xmlNewTextReaderFilename() failed')
return xmlTextReader(_obj=ret) | Create an xmlTextReader structure fed with the resource at
@URI | Below is the the instruction that describes the task:
### Input:
Create an xmlTextReader structure fed with the resource at
@URI
### Response:
def newTextReaderFilename(URI):
"""Create an xmlTextReader structure fed with the resource at
@URI """
ret = libxml2mod.xmlNewTextReaderFilename(URI)
... |
def verify_words(self):
"""Verify the fields source, imagery_used and comment of the changeset
for some suspect words.
"""
if self.comment:
if find_words(self.comment, self.suspect_words, self.excluded_words):
self.label_suspicious('suspect_word')
if ... | Verify the fields source, imagery_used and comment of the changeset
for some suspect words. | Below is the the instruction that describes the task:
### Input:
Verify the fields source, imagery_used and comment of the changeset
for some suspect words.
### Response:
def verify_words(self):
"""Verify the fields source, imagery_used and comment of the changeset
for some suspect words.
... |
def set_data(self, data):
"""
Set a new data buffer.
:Parameters:
`data` : a basestring object
New data buffer.
"""
if not isinstance(data, basestring):
raise ValueError("data must an instance of basestring")
self._data = data
... | Set a new data buffer.
:Parameters:
`data` : a basestring object
New data buffer. | Below is the the instruction that describes the task:
### Input:
Set a new data buffer.
:Parameters:
`data` : a basestring object
New data buffer.
### Response:
def set_data(self, data):
"""
Set a new data buffer.
:Parameters:
`data` : a ... |
def add(self, layers, above=None, below=None):
""" Add one or more layers to the stack of masking layers.
Args:
layers: A string, NiBabel image, list, or dict. If anything other
than a dict is passed, assigns sequential layer names based on
the current positio... | Add one or more layers to the stack of masking layers.
Args:
layers: A string, NiBabel image, list, or dict. If anything other
than a dict is passed, assigns sequential layer names based on
the current position in stack; if a dict, uses key as the name
... | Below is the the instruction that describes the task:
### Input:
Add one or more layers to the stack of masking layers.
Args:
layers: A string, NiBabel image, list, or dict. If anything other
than a dict is passed, assigns sequential layer names based on
the curre... |
def expires(self):
"""Union[datetime.datetime, None]: Datetime at which the table will be
deleted.
Raises:
ValueError: For invalid value types.
"""
expiration_time = self._properties.get("expirationTime")
if expiration_time is not None:
# expirati... | Union[datetime.datetime, None]: Datetime at which the table will be
deleted.
Raises:
ValueError: For invalid value types. | Below is the the instruction that describes the task:
### Input:
Union[datetime.datetime, None]: Datetime at which the table will be
deleted.
Raises:
ValueError: For invalid value types.
### Response:
def expires(self):
"""Union[datetime.datetime, None]: Datetime at which the t... |
def reset(self):
# pylint: disable=not-context-manager
"""Reset scheduler::
* Remove waiting results
* Clear checks and actions lists
:return: None
"""
logger.info("Scheduling loop reset")
with self.waiting_results.mutex:
self.waiting_results... | Reset scheduler::
* Remove waiting results
* Clear checks and actions lists
:return: None | Below is the the instruction that describes the task:
### Input:
Reset scheduler::
* Remove waiting results
* Clear checks and actions lists
:return: None
### Response:
def reset(self):
# pylint: disable=not-context-manager
"""Reset scheduler::
* Remove waiting re... |
def fromXml(cls, xml):
"""
Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject>
"""
clsname = xml.get('class')
if clsname:
subcls = XmlObject.byName(clsname)
if subcls is None:... | Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject> | Below is the the instruction that describes the task:
### Input:
Restores an object from XML.
:param xml | <xml.etree.ElementTree.Element>
:return subclass of <XmlObject>
### Response:
def fromXml(cls, xml):
"""
Restores an object from XML.
:param xml | <xml... |
def document_fromstring(html, guess_charset=True, parser=None):
"""Parse a whole document into a string."""
if not isinstance(html, _strings):
raise TypeError('string required')
if parser is None:
parser = html_parser
return parser.parse(html, useChardet=guess_charset).getroot() | Parse a whole document into a string. | Below is the the instruction that describes the task:
### Input:
Parse a whole document into a string.
### Response:
def document_fromstring(html, guess_charset=True, parser=None):
"""Parse a whole document into a string."""
if not isinstance(html, _strings):
raise TypeError('string required')
... |
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0):
"""Builds a list of segments satisfying the given criteria """
seg_result = segmentlist([])
sum_result = segmentlist([])
# Is there any way to get segment and segement summar... | Builds a list of segments satisfying the given criteria | Below is the the instruction that describes the task:
### Input:
Builds a list of segments satisfying the given criteria
### Response:
def build_segment_list_one(engine, gps_start_time, gps_end_time, ifo, segment_name, version = None, start_pad = 0, end_pad = 0):
"""Builds a list of segments satisfying the giv... |
def getVersionFromArchiveId(git_archive_id='$Format:%ct %d$'):
""" Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX t... | Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX timestamp
%d: ref names, like the --decorate option of git-l... | Below is the the instruction that describes the task:
### Input:
Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX tim... |
def get_sitk_image_from_ndarray(data3d):
"""
Prepare SimpleItk Image object and rescale data to unsigned types.
Simple ITK with version higher than 1.0.0 can not write signed int16. This function check
the SimpleITK version and use work around with Rescale Intercept and Rescale Slope
:param data3d:... | Prepare SimpleItk Image object and rescale data to unsigned types.
Simple ITK with version higher than 1.0.0 can not write signed int16. This function check
the SimpleITK version and use work around with Rescale Intercept and Rescale Slope
:param data3d:
:return: | Below is the the instruction that describes the task:
### Input:
Prepare SimpleItk Image object and rescale data to unsigned types.
Simple ITK with version higher than 1.0.0 can not write signed int16. This function check
the SimpleITK version and use work around with Rescale Intercept and Rescale Slope
... |
def load(cls, path):
"""
Load a SOM from a JSON file saved with this package.
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class.
"""
data = json.load(... | Load a SOM from a JSON file saved with this package.
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class. | Below is the the instruction that describes the task:
### Input:
Load a SOM from a JSON file saved with this package.
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class.
### Respon... |
def create_snapshot(kwargs=None, call=None, wait_to_finish=False):
'''
Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snaps... | Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snapshot my-ec2-config volume_id=vol-351d8826
salt-cloud -f create_snapshot ... | Below is the the instruction that describes the task:
### Input:
Create a snapshot.
volume_id
The ID of the Volume from which to create a snapshot.
description
The optional description of the snapshot.
CLI Exampe:
.. code-block:: bash
salt-cloud -f create_snapshot my-ec2... |
def GetFilePathsWithDialog(fileTypes=[]):
"""
Multipul File Select with dialog
fileTypes: you can choise file extension
ex) fileTypes=[('Excel Files', '.xlsx')]
"""
root = tkinter.Tk()
root.withdraw()
filepath = filedialog.askopenfilenames(
filetypes=fileTypes, p... | Multipul File Select with dialog
fileTypes: you can choise file extension
ex) fileTypes=[('Excel Files', '.xlsx')] | Below is the the instruction that describes the task:
### Input:
Multipul File Select with dialog
fileTypes: you can choise file extension
ex) fileTypes=[('Excel Files', '.xlsx')]
### Response:
def GetFilePathsWithDialog(fileTypes=[]):
"""
Multipul File Select with dialog
... |
def _add_bearer_token(self, *args, **kwargs):
"""Add a bearer token to the request uri, body or authorization header.
This is overwritten to change the headers slightly.
"""
s = super(TwitchOAuthClient, self)
uri, headers, body = s._add_bearer_token(*args, **kwargs)
auth... | Add a bearer token to the request uri, body or authorization header.
This is overwritten to change the headers slightly. | Below is the the instruction that describes the task:
### Input:
Add a bearer token to the request uri, body or authorization header.
This is overwritten to change the headers slightly.
### Response:
def _add_bearer_token(self, *args, **kwargs):
"""Add a bearer token to the request uri, body or au... |
def generate_nonce_timestamp():
""" Generate unique nonce with counter, uuid and rng."""
global count
rng = botan.rng().get(30)
uuid4 = uuid.uuid4().bytes # 16 byte
tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng
nonce = tmpnonce[:41] # 41 byte (328 bit)
count += 1
return ... | Generate unique nonce with counter, uuid and rng. | Below is the the instruction that describes the task:
### Input:
Generate unique nonce with counter, uuid and rng.
### Response:
def generate_nonce_timestamp():
""" Generate unique nonce with counter, uuid and rng."""
global count
rng = botan.rng().get(30)
uuid4 = uuid.uuid4().bytes # 16 byte
... |
def devices(self):
"""Get a listing of devices registered to the Google Music account."""
response = self._call(
mc_calls.DeviceManagementInfo
)
registered_devices = response.body.get('data', {}).get('items', [])
return registered_devices | Get a listing of devices registered to the Google Music account. | Below is the the instruction that describes the task:
### Input:
Get a listing of devices registered to the Google Music account.
### Response:
def devices(self):
"""Get a listing of devices registered to the Google Music account."""
response = self._call(
mc_calls.DeviceManagementInfo
)
registered_dev... |
def _assert_version(self, version):
'''
Assert that the grid version is equal to or above the given value.
If no version is set, set the version.
'''
if self.nearest_version < version:
if self._version_given:
raise ValueError(
'... | Assert that the grid version is equal to or above the given value.
If no version is set, set the version. | Below is the the instruction that describes the task:
### Input:
Assert that the grid version is equal to or above the given value.
If no version is set, set the version.
### Response:
def _assert_version(self, version):
'''
Assert that the grid version is equal to or above the given value.... |
def _B(self, R):
"""Return numpy array from B1 up to and including Bn. (eqn. 6)"""
HNn_R = self._HNn / R
return HNn_R / self._sin_alpha * (0.4 * HNn_R / self._sin_alpha + 1) | Return numpy array from B1 up to and including Bn. (eqn. 6) | Below is the the instruction that describes the task:
### Input:
Return numpy array from B1 up to and including Bn. (eqn. 6)
### Response:
def _B(self, R):
"""Return numpy array from B1 up to and including Bn. (eqn. 6)"""
HNn_R = self._HNn / R
return HNn_R / self._sin_alpha * (0.4 * HNn_R ... |
def writeObjectReference(self, obj, output):
"""Tries to write an object reference, adding it to the references
table. Does not write the actual object bytes or set the reference
position. Returns a tuple of whether the object was a new reference
(True if it was, False if it alr... | Tries to write an object reference, adding it to the references
table. Does not write the actual object bytes or set the reference
position. Returns a tuple of whether the object was a new reference
(True if it was, False if it already was in the reference table)
and the new ... | Below is the the instruction that describes the task:
### Input:
Tries to write an object reference, adding it to the references
table. Does not write the actual object bytes or set the reference
position. Returns a tuple of whether the object was a new reference
(True if it was, Fa... |
def orchestration_save(self, mode="shallow", custom_params=None):
"""Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json
... | Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json | Below is the the instruction that describes the task:
### Input:
Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json
### Response:... |
def _parse_prop(self, dd, row):
"""
:param dd: datadict
:param _row: (tablename, row)
:return:
"""
key = row['name']
if key.startswith('#'):
deprecated = True
else:
deprecated = False
v = dd.get(key)
_value = self._g... | :param dd: datadict
:param _row: (tablename, row)
:return: | Below is the the instruction that describes the task:
### Input:
:param dd: datadict
:param _row: (tablename, row)
:return:
### Response:
def _parse_prop(self, dd, row):
"""
:param dd: datadict
:param _row: (tablename, row)
:return:
"""
key = row['nam... |
def organize_models(self, outdir, force_rerun=False):
"""Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again even i... | Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again even if they already exist
Returns:
dict: Dictiona... | Below is the the instruction that describes the task:
### Input:
Organize and rename SWISS-MODEL models to a single folder with a name containing template information.
Args:
outdir (str): New directory to copy renamed models to
force_rerun (bool): If models should be copied again ev... |
def readSTATION0(path, stations):
"""
Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
:returns: List of tup... | Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
:returns: List of tuples of station, lat, long, elevation
:rtyp... | Below is the the instruction that describes the task:
### Input:
Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
... |
def fetch(task_id, wait=0, cached=Conf.CACHED):
"""
Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:return: th... | Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:return: the full task object
:rtype: Task | Below is the the instruction that describes the task:
### Input:
Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:r... |
def _getsatname(self):
"""
Get the satellite name used in the rsr-reader, from the platform
and number
"""
if self.platform_name.startswith("Meteosat"):
return self.platform_name
else:
raise NotImplementedError(
'Platform {0} not y... | Get the satellite name used in the rsr-reader, from the platform
and number | Below is the the instruction that describes the task:
### Input:
Get the satellite name used in the rsr-reader, from the platform
and number
### Response:
def _getsatname(self):
"""
Get the satellite name used in the rsr-reader, from the platform
and number
"""
if s... |
def bh_effective_spin(chi,incl):
"""
Determines the effective [as defined in Stone, Loeb,
Berger, PRD 87, 084053 (2013)] aligned dimensionless
spin parameter of a NS-BH binary with tilted BH spin.
This means finding the root chi_eff of
ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl))
wit... | Determines the effective [as defined in Stone, Loeb,
Berger, PRD 87, 084053 (2013)] aligned dimensionless
spin parameter of a NS-BH binary with tilted BH spin.
This means finding the root chi_eff of
ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl))
with the correct sign.
Parameters
-----... | Below is the the instruction that describes the task:
### Input:
Determines the effective [as defined in Stone, Loeb,
Berger, PRD 87, 084053 (2013)] aligned dimensionless
spin parameter of a NS-BH binary with tilted BH spin.
This means finding the root chi_eff of
ISCO_eq_chi_first(chi_eff, PG_ISSO_s... |
def ast_to_sympy(expr):
'''Converts an AST expression to a sympy expression (STUPID)'''
from dolang import to_source
s = to_source(expr)
not_to_be_treated_as_functions = ['alpha','beta', 'gamma','zeta', 'Chi']
d = {v: sympy.Symbol(v) for v in not_to_be_treated_as_functions}
return sympy.sympify(... | Converts an AST expression to a sympy expression (STUPID) | Below is the the instruction that describes the task:
### Input:
Converts an AST expression to a sympy expression (STUPID)
### Response:
def ast_to_sympy(expr):
'''Converts an AST expression to a sympy expression (STUPID)'''
from dolang import to_source
s = to_source(expr)
not_to_be_treated_as_func... |
def block_worker(self, worker_id, reason):
"""
Block a worker from working on my tasks.
"""
params = {'WorkerId': worker_id, 'Reason': reason}
return self._process_request('BlockWorker', params) | Block a worker from working on my tasks. | Below is the the instruction that describes the task:
### Input:
Block a worker from working on my tasks.
### Response:
def block_worker(self, worker_id, reason):
"""
Block a worker from working on my tasks.
"""
params = {'WorkerId': worker_id, 'Reason': reason}
return self... |
def _build(self, inputs):
"""Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the m... | Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variables to be the correct size for the multiplication. The
batch size... | Below is the the instruction that describes the task:
### Input:
Connects the Linear module into the graph, with input Tensor `inputs`.
If this is not the first time the module has been connected to the graph,
the Tensor provided here must have the same final dimension, in order for
the existing variab... |
def register_error_code(code, exception_type, domain='core'):
"""Register a new error code"""
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) | Register a new error code | Below is the the instruction that describes the task:
### Input:
Register a new error code
### Response:
def register_error_code(code, exception_type, domain='core'):
"""Register a new error code"""
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain... |
def get(self, didMethodName, required=True) -> DidMethod:
"""
:param didMethodName: name of DID Method
:param required: if not found and True, throws an exception, else None
:return: DID Method
"""
dm = self.d.get(didMethodName) if didMethodName else self.default
... | :param didMethodName: name of DID Method
:param required: if not found and True, throws an exception, else None
:return: DID Method | Below is the the instruction that describes the task:
### Input:
:param didMethodName: name of DID Method
:param required: if not found and True, throws an exception, else None
:return: DID Method
### Response:
def get(self, didMethodName, required=True) -> DidMethod:
"""
:param did... |
def get_reviews(self, user_id):
""" Get reviews for a particular user
"""
url = _REVIEWS_USER.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
user_id=user_id,
at=s... | Get reviews for a particular user | Below is the the instruction that describes the task:
### Input:
Get reviews for a particular user
### Response:
def get_reviews(self, user_id):
""" Get reviews for a particular user
"""
url = _REVIEWS_USER.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,... |
def center(self, X):
"""
Center `X` in PCA space.
"""
X = X.copy()
inan = numpy.isnan(X)
if self.mu is None:
X_ = numpy.ma.masked_array(X, inan)
self.mu = X_.mean(0).base
self.sigma = X_.std(0).base
reduce(lambda y,x: setitem(x[... | Center `X` in PCA space. | Below is the the instruction that describes the task:
### Input:
Center `X` in PCA space.
### Response:
def center(self, X):
"""
Center `X` in PCA space.
"""
X = X.copy()
inan = numpy.isnan(X)
if self.mu is None:
X_ = numpy.ma.masked_array(X, inan)
... |
def fetch(self):
"""
Fetch a CallSummaryInstance
:returns: Fetched CallSummaryInstance
:rtype: twilio.rest.insights.v1.summary.CallSummaryInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
par... | Fetch a CallSummaryInstance
:returns: Fetched CallSummaryInstance
:rtype: twilio.rest.insights.v1.summary.CallSummaryInstance | Below is the the instruction that describes the task:
### Input:
Fetch a CallSummaryInstance
:returns: Fetched CallSummaryInstance
:rtype: twilio.rest.insights.v1.summary.CallSummaryInstance
### Response:
def fetch(self):
"""
Fetch a CallSummaryInstance
:returns: Fetched C... |
def gcmt_to_simple_array(self, centroid_location=True):
"""
Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-... | Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-eigenvalue, t-plunge, t-azimuth,
t-eigenvalue, moment, f_clvd, erel] | Below is the the instruction that describes the task:
### Input:
Converts the GCMT catalogue to a simple array of
[ID, year, month, day, hour, minute, second, long., lat., depth, Mw,
strike1, dip1, rake1, strike2, dip2, rake2, b-plunge, b-azimuth,
b-eigenvalue, p-plunge, p-azimuth, p-eigenva... |
def data_check(self, participant):
"""Check a participants data."""
participant_id = participant.uniqueid
nodes = Node.query.filter_by(participant_id=participant_id).all()
if len(nodes) != self.experiment_repeats + self.practice_repeats:
print("Error: Participant has {} nod... | Check a participants data. | Below is the the instruction that describes the task:
### Input:
Check a participants data.
### Response:
def data_check(self, participant):
"""Check a participants data."""
participant_id = participant.uniqueid
nodes = Node.query.filter_by(participant_id=participant_id).all()
if ... |
def debug_derivative(self, guess):
"""returns (explicit, auto)"""
from .lmmin import check_derivative
return check_derivative(self.component.npar, self.data.size,
self.lm_model, self.lm_deriv, guess) | returns (explicit, auto) | Below is the the instruction that describes the task:
### Input:
returns (explicit, auto)
### Response:
def debug_derivative(self, guess):
"""returns (explicit, auto)"""
from .lmmin import check_derivative
return check_derivative(self.component.npar, self.data.size,
... |
def open(cls, sock, chunk_type, isatty, chunk_eof_type=None, buf_size=None, select_timeout=None):
"""Yields the write side of a pipe that will copy appropriately chunked values to a socket."""
with cls.open_multi(sock,
(chunk_type,),
(isatty,),
... | Yields the write side of a pipe that will copy appropriately chunked values to a socket. | Below is the the instruction that describes the task:
### Input:
Yields the write side of a pipe that will copy appropriately chunked values to a socket.
### Response:
def open(cls, sock, chunk_type, isatty, chunk_eof_type=None, buf_size=None, select_timeout=None):
"""Yields the write side of a pipe that will ... |
def installer(cv, ctx, site, force=False):
"""
Installer factory
@param cv: Current version (The version of IPS we are installing)
@type cv: ips_vagrant.common.version.Version
@type ctx: ips_vagrant.cli.Context
@param site: The IPS Site we are installing
@type site: ip... | Installer factory
@param cv: Current version (The version of IPS we are installing)
@type cv: ips_vagrant.common.version.Version
@type ctx: ips_vagrant.cli.Context
@param site: The IPS Site we are installing
@type site: ips_vagrant.models.sites.Site
@param force: Overwri... | Below is the the instruction that describes the task:
### Input:
Installer factory
@param cv: Current version (The version of IPS we are installing)
@type cv: ips_vagrant.common.version.Version
@type ctx: ips_vagrant.cli.Context
@param site: The IPS Site we are installing
@typ... |
def view_portfolio_losses(token, dstore):
"""
The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table.
"""
oq = dstore['oqparam']
loss_dt = oq.loss_dt()
data = portfolio_loss(dstore).view(loss_dt)[:, 0]
rlzids = [str(r) for r in range(le... | The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table. | Below is the the instruction that describes the task:
### Input:
The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table.
### Response:
def view_portfolio_losses(token, dstore):
"""
The losses for the full portfolio, for each realization and loss type,... |
def output(self, stream, value):
"""SPL output port assignment expression.
Arguments:
stream(Stream): Output stream the assignment is for.
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
... | SPL output port assignment expression.
Arguments:
stream(Stream): Output stream the assignment is for.
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
Expression: Output assignment ex... | Below is the the instruction that describes the task:
### Input:
SPL output port assignment expression.
Arguments:
stream(Stream): Output stream the assignment is for.
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expres... |
def filter(self, **filters):
"""
Add a filter to this query.
Appends to any previous filters set.
:rtype: Query
"""
q = self._clone()
for key, value in filters.items():
filter_key = re.split('__', key)
filter_attr = filter_key[0]
... | Add a filter to this query.
Appends to any previous filters set.
:rtype: Query | Below is the the instruction that describes the task:
### Input:
Add a filter to this query.
Appends to any previous filters set.
:rtype: Query
### Response:
def filter(self, **filters):
"""
Add a filter to this query.
Appends to any previous filters set.
:rtype: Q... |
def unique_flags(items, key=None):
"""
Returns a list of booleans corresponding to the first instance of each
unique item.
Args:
items (Sequence): indexable collection of items
key (Callable, optional): custom normalization function.
If specified returns items where `key(it... | Returns a list of booleans corresponding to the first instance of each
unique item.
Args:
items (Sequence): indexable collection of items
key (Callable, optional): custom normalization function.
If specified returns items where `key(item)` is unique.
Returns:
List[bool... | Below is the the instruction that describes the task:
### Input:
Returns a list of booleans corresponding to the first instance of each
unique item.
Args:
items (Sequence): indexable collection of items
key (Callable, optional): custom normalization function.
If specified retur... |
def unregister(self, uuid):
"""Unregister a schema registered with input uuid.
:raises: KeyError if uuid is not already registered.
"""
schema = self._schbyuuid.pop(uuid)
# clean schemas by name
self._schbyname[schema.name].remove(schema)
if not self._schbyname[... | Unregister a schema registered with input uuid.
:raises: KeyError if uuid is not already registered. | Below is the the instruction that describes the task:
### Input:
Unregister a schema registered with input uuid.
:raises: KeyError if uuid is not already registered.
### Response:
def unregister(self, uuid):
"""Unregister a schema registered with input uuid.
:raises: KeyError if uuid is n... |
def filter(self, userinfo, user_info_claims=None):
"""
Return only those claims that are asked for.
It's a best effort task; if essential claims are not present
no error is flagged.
:param userinfo: A dictionary containing the available info for one user
:param user_info... | Return only those claims that are asked for.
It's a best effort task; if essential claims are not present
no error is flagged.
:param userinfo: A dictionary containing the available info for one user
:param user_info_claims: A dictionary specifying the asked for claims
:return: ... | Below is the the instruction that describes the task:
### Input:
Return only those claims that are asked for.
It's a best effort task; if essential claims are not present
no error is flagged.
:param userinfo: A dictionary containing the available info for one user
:param user_info_c... |
def load_state_from_disk():
""" loads the state from a local data.json file
"""
if is_there_state():
with open('data.json', 'r') as f:
data = json.load(f)
return data
else:
return False | loads the state from a local data.json file | Below is the the instruction that describes the task:
### Input:
loads the state from a local data.json file
### Response:
def load_state_from_disk():
""" loads the state from a local data.json file
"""
if is_there_state():
with open('data.json', 'r') as f:
data = json.load(f)
... |
def remove(name=None, pkgs=None, **kwargs):
'''
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no space... | Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packages, no spaces.
pkgs (list):
A list of packages ... | Below is the the instruction that describes the task:
### Input:
Remove the passed package(s) from the system using winrepo
.. versionadded:: 0.16.0
Args:
name (str):
The name(s) of the package(s) to be uninstalled. Can be a
single package or a comma delimited list of packa... |
def drop_database(self, name, force=False):
"""
Drop an MapD database
Parameters
----------
name : string
Database name
force : boolean, default False
If False and there are any tables in this database, raises an
IntegrityError
"""
... | Drop an MapD database
Parameters
----------
name : string
Database name
force : boolean, default False
If False and there are any tables in this database, raises an
IntegrityError | Below is the the instruction that describes the task:
### Input:
Drop an MapD database
Parameters
----------
name : string
Database name
force : boolean, default False
If False and there are any tables in this database, raises an
IntegrityError
### Resp... |
def build_post_form_args(self, bucket_name, key, expires_in = 6000,
acl = None, success_action_redirect = None,
max_content_length = None,
http_method = "http", fields=None,
conditions=None):
"""
... | Taken from the AWS book Python examples and modified for use with boto
This only returns the arguments required for the post form, not the
actual form. This does not return the file input field which also
needs to be added
:type bucket_name: string
:param bucket_name: ... | Below is the the instruction that describes the task:
### Input:
Taken from the AWS book Python examples and modified for use with boto
This only returns the arguments required for the post form, not the
actual form. This does not return the file input field which also
needs to be added
... |
def structured_partlist(input, timeout=20, showgui=False):
'''export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value'... | export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..]) | Below is the the instruction that describes the task:
### Input:
export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'val... |
def get(self, exchange, virtual_host='/'):
"""Get Exchange details.
:param str exchange: Exchange name
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity i... | Get Exchange details.
:param str exchange: Exchange name
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Get Exchange details.
:param str exchange: Exchange name
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a... |
def set_min(self, fmin):
"""
Updates minimum value
"""
if round(100000*fmin) != 100000*fmin:
raise DriverError('utils.widgets.Expose.set_min: ' +
'fmin must be a multiple of 0.00001')
self.fmin = fmin
self.set(self.fmin) | Updates minimum value | Below is the the instruction that describes the task:
### Input:
Updates minimum value
### Response:
def set_min(self, fmin):
"""
Updates minimum value
"""
if round(100000*fmin) != 100000*fmin:
raise DriverError('utils.widgets.Expose.set_min: ' +
... |
def inspect_partitions(bucket):
"""Discover the partitions on a bucket via introspection.
For large buckets which lack s3 inventories, salactus will attempt
to process objects in parallel on the bucket by breaking the bucket
into a separate keyspace partitions. It does this with a heurestic
that at... | Discover the partitions on a bucket via introspection.
For large buckets which lack s3 inventories, salactus will attempt
to process objects in parallel on the bucket by breaking the bucket
into a separate keyspace partitions. It does this with a heurestic
that attempts to sample the keyspace and deter... | Below is the the instruction that describes the task:
### Input:
Discover the partitions on a bucket via introspection.
For large buckets which lack s3 inventories, salactus will attempt
to process objects in parallel on the bucket by breaking the bucket
into a separate keyspace partitions. It does thi... |
def _get_format_name_loader_mapping(self):
"""
:return: Mappings of format-name and loader class.
:rtype: dict
"""
loader_table = self._get_common_loader_mapping()
loader_table.update(
{
"excel": ExcelTableFileLoader,
"json_lin... | :return: Mappings of format-name and loader class.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
:return: Mappings of format-name and loader class.
:rtype: dict
### Response:
def _get_format_name_loader_mapping(self):
"""
:return: Mappings of format-name and loader class.
:rtype: dict
"""
loader_t... |
def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None):
'''
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:para... | Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
... | Below is the the instruction that describes the task:
### Input:
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return t... |
def timer(self, stat, tags=None):
"""Contextmanager for easily computing timings.
:arg string stat: A period delimited alphanumeric key.
:arg list-of-strings tags: Each string in the tag consists of a key and
a value separated by a colon. Tags can make it easier to break down
... | Contextmanager for easily computing timings.
:arg string stat: A period delimited alphanumeric key.
:arg list-of-strings tags: Each string in the tag consists of a key and
a value separated by a colon. Tags can make it easier to break down
metrics for analysis.
For... | Below is the the instruction that describes the task:
### Input:
Contextmanager for easily computing timings.
:arg string stat: A period delimited alphanumeric key.
:arg list-of-strings tags: Each string in the tag consists of a key and
a value separated by a colon. Tags can make it ea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.