code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def reset(self):
"""Resets the iterator to the beginning of the data."""
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.last_batch_handle != 'roll_over' or \
self._cache_data is None:
if self.imgrec is not None:
self... | Resets the iterator to the beginning of the data. | Below is the the instruction that describes the task:
### Input:
Resets the iterator to the beginning of the data.
### Response:
def reset(self):
"""Resets the iterator to the beginning of the data."""
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.la... |
def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] | Known symlinks of the block device. | Below is the the instruction that describes the task:
### Input:
Known symlinks of the block device.
### Response:
def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] |
def refs(self):
"""Iterate over downloadable sources -- references and templates"""
def set_bundle(s):
s._bundle = self
return s
return list(set_bundle(s) for s in self.dataset.sources if not s.is_downloadable) | Iterate over downloadable sources -- references and templates | Below is the the instruction that describes the task:
### Input:
Iterate over downloadable sources -- references and templates
### Response:
def refs(self):
"""Iterate over downloadable sources -- references and templates"""
def set_bundle(s):
s._bundle = self
return s
... |
def make_response(self,
data: Any = None,
**kwargs: Any) -> Any:
r"""Validate response data and wrap it inside response factory.
:param data: Response data. Could be ommited.
:param \*\*kwargs: Keyword arguments to be passed to response factory.
... | r"""Validate response data and wrap it inside response factory.
:param data: Response data. Could be ommited.
:param \*\*kwargs: Keyword arguments to be passed to response factory. | Below is the the instruction that describes the task:
### Input:
r"""Validate response data and wrap it inside response factory.
:param data: Response data. Could be ommited.
:param \*\*kwargs: Keyword arguments to be passed to response factory.
### Response:
def make_response(self,
... |
def search_channels(self, query, limit=25, offset=0):
"""Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offs... | Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of channels
:rt... | Below is the the instruction that describes the task:
### Input:
Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type ... |
def reset() -> None:
"""Reset all wdom objects.
This function clear all connections, elements, and resistered custom
elements. This function also makes new document/application and set them.
"""
from wdom.document import get_new_document, set_document
from wdom.element import Element
from w... | Reset all wdom objects.
This function clear all connections, elements, and resistered custom
elements. This function also makes new document/application and set them. | Below is the the instruction that describes the task:
### Input:
Reset all wdom objects.
This function clear all connections, elements, and resistered custom
elements. This function also makes new document/application and set them.
### Response:
def reset() -> None:
"""Reset all wdom objects.
Thi... |
def startMenu(translator, navigation, tag):
"""
Drop-down menu-style navigation view.
For each primary navigation element available, a copy of the I{tab}
pattern will be loaded from the tag. It will have its I{href} slot
filled with the URL for that navigation item. It will have its I{name}
s... | Drop-down menu-style navigation view.
For each primary navigation element available, a copy of the I{tab}
pattern will be loaded from the tag. It will have its I{href} slot
filled with the URL for that navigation item. It will have its I{name}
slot filled with the user-visible name of the navigation ... | Below is the the instruction that describes the task:
### Input:
Drop-down menu-style navigation view.
For each primary navigation element available, a copy of the I{tab}
pattern will be loaded from the tag. It will have its I{href} slot
filled with the URL for that navigation item. It will have its ... |
def create_network(self):
"""Create a new network."""
return DiscreteGenerational(
generations=self.generations,
generation_size=self.generation_size,
initial_source=True,
) | Create a new network. | Below is the the instruction that describes the task:
### Input:
Create a new network.
### Response:
def create_network(self):
"""Create a new network."""
return DiscreteGenerational(
generations=self.generations,
generation_size=self.generation_size,
initial_sou... |
def message_interactions(self):
"""
Access the message_interactions
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
"""
... | Access the message_interactions
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList | Below is the the instruction that describes the task:
### Input:
Access the message_interactions
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
... |
def install(self, struct, ui, debug=False):
"""
This is the only method that should be called from outside. Call it
like:
`DependencyInstaller(struct)` and it will install packages which are
not present on system (it uses package managers specified by `struct`
structure)
... | This is the only method that should be called from outside. Call it
like:
`DependencyInstaller(struct)` and it will install packages which are
not present on system (it uses package managers specified by `struct`
structure) | Below is the the instruction that describes the task:
### Input:
This is the only method that should be called from outside. Call it
like:
`DependencyInstaller(struct)` and it will install packages which are
not present on system (it uses package managers specified by `struct`
struct... |
def uint(nstr, schema):
"""
!~~uint
"""
if isinstance(nstr, basestring):
if not nstr.isdigit():
return False
nstr = long(nstr)
elif not isinstance(nstr, (int, long)):
return False
return nstr > 0 | !~~uint | Below is the the instruction that describes the task:
### Input:
!~~uint
### Response:
def uint(nstr, schema):
"""
!~~uint
"""
if isinstance(nstr, basestring):
if not nstr.isdigit():
return False
nstr = long(nstr)
elif not isinstance(nstr, (int, long)):
retur... |
def genemark(args):
"""
%prog genemark species fastafile
Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig
model gff file is needed.
"""
p = OptionParser(genemark.__doc__)
p.add_option("--junctions", help="Path to `junctions.bed` from Tophat2")
p.set_home("gmes")
... | %prog genemark species fastafile
Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig
model gff file is needed. | Below is the the instruction that describes the task:
### Input:
%prog genemark species fastafile
Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig
model gff file is needed.
### Response:
def genemark(args):
"""
%prog genemark species fastafile
Train GENEMARK model give... |
def integerize(self):
"""Convert co-ordinate values to integers."""
self.x = int(round(self.x))
self.y = int(round(self.y)) | Convert co-ordinate values to integers. | Below is the the instruction that describes the task:
### Input:
Convert co-ordinate values to integers.
### Response:
def integerize(self):
"""Convert co-ordinate values to integers."""
self.x = int(round(self.x))
self.y = int(round(self.y)) |
def formatmonth(self, theyear, themonth, withyear=True, net=None, qs=None, template='happenings/partials/calendar/month_table.html'):
"""Return a formatted month as a table."""
context = self.get_context()
context['month_start_date'] = date(self.yr, self.mo, 1)
context['week_rows'] = []
... | Return a formatted month as a table. | Below is the the instruction that describes the task:
### Input:
Return a formatted month as a table.
### Response:
def formatmonth(self, theyear, themonth, withyear=True, net=None, qs=None, template='happenings/partials/calendar/month_table.html'):
"""Return a formatted month as a table."""
contex... |
def _process_voc_annot_view(self, limit):
"""
This MGI table represents associations between things.
We add the internal annotation id to the idhashmap.
It is expected that the genotypes have already been added to the idhash
:param limit:
:return:
"""
... | This MGI table represents associations between things.
We add the internal annotation id to the idhashmap.
It is expected that the genotypes have already been added to the idhash
:param limit:
:return: | Below is the the instruction that describes the task:
### Input:
This MGI table represents associations between things.
We add the internal annotation id to the idhashmap.
It is expected that the genotypes have already been added to the idhash
:param limit:
:return:
### Response:
... |
def filter(self, date=None, regroup=False, ignored=None, pushed=None, unmapped=None, current_workday=None):
"""
Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`}
items.
`date` can either be a single :class:`datetime.date` object to filter onl... | Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`}
items.
`date` can either be a single :class:`datetime.date` object to filter only entries from the given date,
or a tuple of :class:`datetime.date` objects representing `(from, to)`. `filter_callback`... | Below is the the instruction that describes the task:
### Input:
Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`}
items.
`date` can either be a single :class:`datetime.date` object to filter only entries from the given date,
or a tuple of :class... |
def effect_has_complete_transcript(effect):
"""
Parameters
----------
effect : subclass of MutationEffect
Returns True if effect has transcript and that transcript has complete CDS
"""
return apply_to_transcript_if_exists(
effect=effect,
fn=lambda t: t.complete,
defa... | Parameters
----------
effect : subclass of MutationEffect
Returns True if effect has transcript and that transcript has complete CDS | Below is the the instruction that describes the task:
### Input:
Parameters
----------
effect : subclass of MutationEffect
Returns True if effect has transcript and that transcript has complete CDS
### Response:
def effect_has_complete_transcript(effect):
"""
Parameters
----------
effe... |
def GetTransPosition(df,field,dic,refCol="transcript_id"):
"""
Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923... | Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST23923910:'234,235,236,1021,..'}
:param refCol: header of the reference c... | Below is the the instruction that describes the task:
### Input:
Maps a genome position to transcript positon"
:param df: a Pandas dataframe
:param field: the head of the column containing the genomic position
:param dic: a dictionary containing for each transcript the respective bases eg. {ENST2392391... |
def set_language(self, language, dialect=None):
"""
Set the language used for TTS.
en: English
es: Spanish | [ lan: latino or ca: castilian ]
"""
self.currentAction = 'setting language'
l = 0
if language == 'en':
l = 0
elif language == ... | Set the language used for TTS.
en: English
es: Spanish | [ lan: latino or ca: castilian ] | Below is the the instruction that describes the task:
### Input:
Set the language used for TTS.
en: English
es: Spanish | [ lan: latino or ca: castilian ]
### Response:
def set_language(self, language, dialect=None):
"""
Set the language used for TTS.
en: English
es:... |
def _set_all_axis_color(self, axis, color):
"""Set axis ticks, title, labels to given color"""
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
'labels']:
prop_set = getattr(axis.properties, prop)
if color and prop in ['title', 'labels']:
... | Set axis ticks, title, labels to given color | Below is the the instruction that describes the task:
### Input:
Set axis ticks, title, labels to given color
### Response:
def _set_all_axis_color(self, axis, color):
"""Set axis ticks, title, labels to given color"""
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
... |
def num2hexstring(number, size=1, little_endian=False):
"""
Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endi... | Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endian - Encode the hex in little endian form
:return {string} | Below is the the instruction that describes the task:
### Input:
Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_end... |
def replace_nones(list_, repl=-1):
r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
... | r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
Example:
>>> # ENABLE_DOCTEST
... | Below is the the instruction that describes the task:
### Input:
r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_... |
def _create_command(wrapper, name, return_value, wrap_result):
"""Create MPD command related function.
"""
def mpd_command(self, *args):
callback = _create_callback(self, return_value, wrap_result)
return wrapper(self, name, args, callback)
return mpd_command | Create MPD command related function. | Below is the the instruction that describes the task:
### Input:
Create MPD command related function.
### Response:
def _create_command(wrapper, name, return_value, wrap_result):
"""Create MPD command related function.
"""
def mpd_command(self, *args):
callback = _create_callback(self, return_v... |
def oriented_bounds_2D(points, qhull_options='QbB'):
"""
Find an oriented bounding box for an array of 2D points.
Parameters
----------
points : (n,2) float
Points in 2D.
Returns
----------
transform : (3,3) float
Homogenous 2D transformation matrix to move the
input ... | Find an oriented bounding box for an array of 2D points.
Parameters
----------
points : (n,2) float
Points in 2D.
Returns
----------
transform : (3,3) float
Homogenous 2D transformation matrix to move the
input points so that the axis aligned bounding box
is CENTERED AT... | Below is the the instruction that describes the task:
### Input:
Find an oriented bounding box for an array of 2D points.
Parameters
----------
points : (n,2) float
Points in 2D.
Returns
----------
transform : (3,3) float
Homogenous 2D transformation matrix to move the
in... |
def as_from(value):
"""
Constructs an instance of :class:`SerialSettings` from a string
representation, that looks like ``/dev/ttyS0:9600,8,1,N,RTSCTS``,
describing, in order, the serial port name, baud rate, byte size,
stop bits, parity and flow control protocol.
Valid ... | Constructs an instance of :class:`SerialSettings` from a string
representation, that looks like ``/dev/ttyS0:9600,8,1,N,RTSCTS``,
describing, in order, the serial port name, baud rate, byte size,
stop bits, parity and flow control protocol.
Valid string representations are (in cases whe... | Below is the the instruction that describes the task:
### Input:
Constructs an instance of :class:`SerialSettings` from a string
representation, that looks like ``/dev/ttyS0:9600,8,1,N,RTSCTS``,
describing, in order, the serial port name, baud rate, byte size,
stop bits, parity and flow cont... |
def make_worlist_trie(wordlist):
"""
Creates a nested dictionary representing the trie created
by the given word list.
:param wordlist: str list:
:return: nested dictionary
>>> make_worlist_trie(['einander', 'einen', 'neben'])
{'e': {'i': {'n': {'a': {'n': {'d': {'e': {'r': {'__end__': '__... | Creates a nested dictionary representing the trie created
by the given word list.
:param wordlist: str list:
:return: nested dictionary
>>> make_worlist_trie(['einander', 'einen', 'neben'])
{'e': {'i': {'n': {'a': {'n': {'d': {'e': {'r': {'__end__': '__end__'}}}}}, 'e': {'n': {'__end__': '__end__'... | Below is the the instruction that describes the task:
### Input:
Creates a nested dictionary representing the trie created
by the given word list.
:param wordlist: str list:
:return: nested dictionary
>>> make_worlist_trie(['einander', 'einen', 'neben'])
{'e': {'i': {'n': {'a': {'n': {'d': {'e... |
def convex_comb_agg_log(model,a,b):
"""convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate o... | convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear re... | Below is the the instruction that describes the task:
### Input:
convex_comb_agg_log -- add piecewise relation with a logarithmic number of binary variables
using the convex combination formulation -- non-disaggregated.
Parameters:
- model: a model where to include the piecewise linear relation
... |
def _publish_pyin(self, code, parent, execution_count):
"""Publish the code request on the pyin stream."""
self.session.send(self.iopub_socket, u'pyin',
{u'code':code, u'execution_count': execution_count},
parent=parent, ident=self._topic('pyin')
... | Publish the code request on the pyin stream. | Below is the the instruction that describes the task:
### Input:
Publish the code request on the pyin stream.
### Response:
def _publish_pyin(self, code, parent, execution_count):
"""Publish the code request on the pyin stream."""
self.session.send(self.iopub_socket, u'pyin',
... |
def make_receipt(self,
base_header: BlockHeader,
transaction: BaseTransaction,
computation: BaseComputation,
state: BaseState) -> Receipt:
"""
Generate the receipt resulting from applying the transaction.
:param... | Generate the receipt resulting from applying the transaction.
:param base_header: the header of the block before the transaction was applied.
:param transaction: the transaction used to generate the receipt
:param computation: the result of running the transaction computation
:param sta... | Below is the the instruction that describes the task:
### Input:
Generate the receipt resulting from applying the transaction.
:param base_header: the header of the block before the transaction was applied.
:param transaction: the transaction used to generate the receipt
:param computation:... |
def select_Heavy(self, exclude_symmetry_related=False):
"""
Returns the indexes of all heavy atoms (Mass >= 2),
optionally excluding symmetry-related heavy atoms.
Parameters
----------
exclude_symmetry_related : boolean, default=False
if True, exclude symmetr... | Returns the indexes of all heavy atoms (Mass >= 2),
optionally excluding symmetry-related heavy atoms.
Parameters
----------
exclude_symmetry_related : boolean, default=False
if True, exclude symmetry-related heavy atoms.
Returns
-------
indexes : nd... | Below is the the instruction that describes the task:
### Input:
Returns the indexes of all heavy atoms (Mass >= 2),
optionally excluding symmetry-related heavy atoms.
Parameters
----------
exclude_symmetry_related : boolean, default=False
if True, exclude symmetry-relat... |
def init(self, ):
"""Initialize the plugin. Do nothing.
This function gets called when the plugin is loaded by the plugin manager.
:returns:
:rtype:
:raises:
"""
self.gw = None
pm = MayaPluginManager.get()
genesis = pm.get_plugin("Genesis")
... | Initialize the plugin. Do nothing.
This function gets called when the plugin is loaded by the plugin manager.
:returns:
:rtype:
:raises: | Below is the the instruction that describes the task:
### Input:
Initialize the plugin. Do nothing.
This function gets called when the plugin is loaded by the plugin manager.
:returns:
:rtype:
:raises:
### Response:
def init(self, ):
"""Initialize the plugin. Do nothing.
... |
def update_vm_settings(self, vm, settings):
"""
Updates the VM settings.
:param vm: VM instance
:param settings: settings to update (dict)
"""
for name, value in settings.items():
if hasattr(vm, name) and getattr(vm, name) != value:
if hasatt... | Updates the VM settings.
:param vm: VM instance
:param settings: settings to update (dict) | Below is the the instruction that describes the task:
### Input:
Updates the VM settings.
:param vm: VM instance
:param settings: settings to update (dict)
### Response:
def update_vm_settings(self, vm, settings):
"""
Updates the VM settings.
:param vm: VM instance
... |
def init_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.w... | Initialize the weights. | Below is the the instruction that describes the task:
### Input:
Initialize the weights.
### Response:
def init_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding)):
# Slightly different from the TF version which uses truncated_... |
def flags(rule_or_module, variable_name, condition, values = []):
""" Specifies the flags (variables) that must be set on targets under certain
conditions, described by arguments.
rule_or_module: If contains dot, should be a rule name.
The flags will be applied when that ... | Specifies the flags (variables) that must be set on targets under certain
conditions, described by arguments.
rule_or_module: If contains dot, should be a rule name.
The flags will be applied when that rule is
used to set up build actions.
... | Below is the the instruction that describes the task:
### Input:
Specifies the flags (variables) that must be set on targets under certain
conditions, described by arguments.
rule_or_module: If contains dot, should be a rule name.
The flags will be applied when that rule ... |
def get_table_acl(self, table_name, timeout=None):
'''
Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The se... | Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The server timeout, expressed in seconds.
:return: A dictionary of ac... | Below is the the instruction that describes the task:
### Input:
Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The serv... |
def stream_info(self):
"""
Retrieve information for each stream managed by the consumer group.
Calls :py:meth:`~Database.xinfo_stream` for each stream.
:returns: a dictionary mapping stream key to a dictionary of metadata
"""
accum = {}
for key in self.keys:
... | Retrieve information for each stream managed by the consumer group.
Calls :py:meth:`~Database.xinfo_stream` for each stream.
:returns: a dictionary mapping stream key to a dictionary of metadata | Below is the the instruction that describes the task:
### Input:
Retrieve information for each stream managed by the consumer group.
Calls :py:meth:`~Database.xinfo_stream` for each stream.
:returns: a dictionary mapping stream key to a dictionary of metadata
### Response:
def stream_info(self):
... |
def setup_hooks(self):
"""
Creates and returns a list of hooks to use in a session. Populates self.saver_directory.
Returns: List of hooks to use in a session.
"""
hooks = list()
# Checkpoint saver hook
if self.saver_spec is not None and (self.execution_type == ... | Creates and returns a list of hooks to use in a session. Populates self.saver_directory.
Returns: List of hooks to use in a session. | Below is the the instruction that describes the task:
### Input:
Creates and returns a list of hooks to use in a session. Populates self.saver_directory.
Returns: List of hooks to use in a session.
### Response:
def setup_hooks(self):
"""
Creates and returns a list of hooks to use in a ses... |
def get_directory(db, user_id, api_dirname, content):
"""
Return the names of all files/directories that are direct children of
api_dirname.
If content is False, return a bare model containing just a database-style
name.
"""
db_dirname = from_api_dirname(api_dirname)
if not _dir_exists(... | Return the names of all files/directories that are direct children of
api_dirname.
If content is False, return a bare model containing just a database-style
name. | Below is the the instruction that describes the task:
### Input:
Return the names of all files/directories that are direct children of
api_dirname.
If content is False, return a bare model containing just a database-style
name.
### Response:
def get_directory(db, user_id, api_dirname, content):
""... |
def write_compound_to_auxi_file(directory, compound):
"""
Writes a compound to an auxi file at the specified directory.
:param dir: The directory.
:param compound: The compound.
"""
file_name = "Compound_" + compound.formula + ".json"
with open(os.path.join(directory, file_name), 'w') as f... | Writes a compound to an auxi file at the specified directory.
:param dir: The directory.
:param compound: The compound. | Below is the the instruction that describes the task:
### Input:
Writes a compound to an auxi file at the specified directory.
:param dir: The directory.
:param compound: The compound.
### Response:
def write_compound_to_auxi_file(directory, compound):
"""
Writes a compound to an auxi file at the ... |
def ref(self, ref):
"""Get a reference pointed to by ``ref``.
The most common will be branches and tags. For a branch, you must
specify 'heads/branchname' and for a tag, 'tags/tagname'. Essentially,
the system should return any reference you provide it in the namespace,
includin... | Get a reference pointed to by ``ref``.
The most common will be branches and tags. For a branch, you must
specify 'heads/branchname' and for a tag, 'tags/tagname'. Essentially,
the system should return any reference you provide it in the namespace,
including notes and stashes (provided t... | Below is the the instruction that describes the task:
### Input:
Get a reference pointed to by ``ref``.
The most common will be branches and tags. For a branch, you must
specify 'heads/branchname' and for a tag, 'tags/tagname'. Essentially,
the system should return any reference you provide... |
def calc_ionic(site, structure, zval):
"""
Calculate the ionic dipole moment using ZVAL from pseudopotential
site: PeriodicSite
structure: Structure
zval: Charge value for ion (ZVAL for VASP pseudopotential)
Returns polarization in electron Angstroms.
"""
norms = structure.lattice.leng... | Calculate the ionic dipole moment using ZVAL from pseudopotential
site: PeriodicSite
structure: Structure
zval: Charge value for ion (ZVAL for VASP pseudopotential)
Returns polarization in electron Angstroms. | Below is the the instruction that describes the task:
### Input:
Calculate the ionic dipole moment using ZVAL from pseudopotential
site: PeriodicSite
structure: Structure
zval: Charge value for ion (ZVAL for VASP pseudopotential)
Returns polarization in electron Angstroms.
### Response:
def calc_... |
def _query(cmd):
""" Create the grammar for a scan/query """
action = upkey(cmd).setResultsName("action")
consist = upkey("consistent").setResultsName("consistent")
order_by = (Suppress(upkey("order") + upkey("by")) + var).setResultsName("order_by")
ordering = (upkey("desc") | upkey("asc")).setResul... | Create the grammar for a scan/query | Below is the the instruction that describes the task:
### Input:
Create the grammar for a scan/query
### Response:
def _query(cmd):
""" Create the grammar for a scan/query """
action = upkey(cmd).setResultsName("action")
consist = upkey("consistent").setResultsName("consistent")
order_by = (Suppres... |
def _builder_connect_signals(self, _dict):
"""Called by controllers which want to autoconnect their
handlers with signals declared in internal Gtk.Builder.
This method accumulates handlers, and books signal
autoconnection later on the idle of the next occurring gtk
loop. After t... | Called by controllers which want to autoconnect their
handlers with signals declared in internal Gtk.Builder.
This method accumulates handlers, and books signal
autoconnection later on the idle of the next occurring gtk
loop. After the autoconnection is done, this method cannot be
... | Below is the the instruction that describes the task:
### Input:
Called by controllers which want to autoconnect their
handlers with signals declared in internal Gtk.Builder.
This method accumulates handlers, and books signal
autoconnection later on the idle of the next occurring gtk
... |
def get_mysql_connection(host, user, port, password, database, ssl={}):
""" MySQL connection """
return pymysql.connect(host=host,
user=user,
port=port,
password=password,
db=database,
... | MySQL connection | Below is the the instruction that describes the task:
### Input:
MySQL connection
### Response:
def get_mysql_connection(host, user, port, password, database, ssl={}):
""" MySQL connection """
return pymysql.connect(host=host,
user=user,
port=port,
... |
def ensure_xpointer_compatibility(node_id):
"""
makes a given node ID xpointer compatible.
xpointer identifiers must not contain ':', so we'll
replace it by '_'.
Parameters
----------
node_id : str or unicode or int
a node or edge ID
Returns
-------
xpointer_id : str or... | makes a given node ID xpointer compatible.
xpointer identifiers must not contain ':', so we'll
replace it by '_'.
Parameters
----------
node_id : str or unicode or int
a node or edge ID
Returns
-------
xpointer_id : str or unicode or int
int IDs are returned verbatim, s... | Below is the the instruction that describes the task:
### Input:
makes a given node ID xpointer compatible.
xpointer identifiers must not contain ':', so we'll
replace it by '_'.
Parameters
----------
node_id : str or unicode or int
a node or edge ID
Returns
-------
xpointe... |
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str:
""" Generate a slot variable for slotname as defined in class
"""
slot = self.schema.slots[slotname]
# Alias allows re-use of slot names in different contexts
if slot.alias:
slotname = slot.alia... | Generate a slot variable for slotname as defined in class | Below is the the instruction that describes the task:
### Input:
Generate a slot variable for slotname as defined in class
### Response:
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str:
""" Generate a slot variable for slotname as defined in class
"""
slot = self.sch... |
def get_signatures(self):
"""
Return a list of the data of the signature files.
Only v1 / JAR Signing.
:rtype: list of bytes
"""
signature_expr = re.compile(r"^(META-INF/)(.*)(\.RSA|\.EC|\.DSA)$")
signature_datas = []
for i in self.get_files():
... | Return a list of the data of the signature files.
Only v1 / JAR Signing.
:rtype: list of bytes | Below is the the instruction that describes the task:
### Input:
Return a list of the data of the signature files.
Only v1 / JAR Signing.
:rtype: list of bytes
### Response:
def get_signatures(self):
"""
Return a list of the data of the signature files.
Only v1 / JAR Signin... |
def _get_package(self):
"""Get the package related to simple hardware ordering."""
mask = '''
items[
keyName,
capacity,
description,
attributes[id,attributeTypeKeyName],
itemCategory[id,categoryCode],
... | Get the package related to simple hardware ordering. | Below is the the instruction that describes the task:
### Input:
Get the package related to simple hardware ordering.
### Response:
def _get_package(self):
"""Get the package related to simple hardware ordering."""
mask = '''
items[
keyName,
capacity,
... |
def solve(self, assumptions=[]):
"""
Solve internal formula.
"""
if self.minicard:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL)
... | Solve internal formula. | Below is the the instruction that describes the task:
### Input:
Solve internal formula.
### Response:
def solve(self, assumptions=[]):
"""
Solve internal formula.
"""
if self.minicard:
if self.use_timer:
start_time = time.clock()
# sav... |
def pick_q_v1(self):
"""Assign the actual value of the inlet sequence to the upper joint
of the subreach upstream."""
inl = self.sequences.inlets.fastaccess
new = self.sequences.states.fastaccess_new
new.qjoints[0] = 0.
for idx in range(inl.len_q):
new.qjoints[0] += inl.q[idx][0] | Assign the actual value of the inlet sequence to the upper joint
of the subreach upstream. | Below is the the instruction that describes the task:
### Input:
Assign the actual value of the inlet sequence to the upper joint
of the subreach upstream.
### Response:
def pick_q_v1(self):
"""Assign the actual value of the inlet sequence to the upper joint
of the subreach upstream."""
inl = self.... |
def scan(self, thing, thing_type=None, blocking=False):
"""
\nScan a single or list of URLs, or Domains\n
NOTE: URLs must include the scheme (http:// or https://)\n
NOTE: For a single domain or list of domains this method will automatically append an 'http://' to the \n
beginning... | \nScan a single or list of URLs, or Domains\n
NOTE: URLs must include the scheme (http:// or https://)\n
NOTE: For a single domain or list of domains this method will automatically append an 'http://' to the \n
beginningof the domain(s)\n
:param thing: a URL or list of URLs,
... | Below is the the instruction that describes the task:
### Input:
\nScan a single or list of URLs, or Domains\n
NOTE: URLs must include the scheme (http:// or https://)\n
NOTE: For a single domain or list of domains this method will automatically append an 'http://' to the \n
beginningof the ... |
def check_subtype_integrity(m, super_kind, rel_id):
'''
Check the model for integrity violations across a subtype association.
'''
if isinstance(rel_id, int):
rel_id = 'R%d' % rel_id
res = 0
for inst in m.select_many(super_kind):
if not xtuml.navigate_subtype(inst, rel_id):
... | Check the model for integrity violations across a subtype association. | Below is the the instruction that describes the task:
### Input:
Check the model for integrity violations across a subtype association.
### Response:
def check_subtype_integrity(m, super_kind, rel_id):
'''
Check the model for integrity violations across a subtype association.
'''
if isinstance(rel_... |
def disassemble_around(self, lpAddress, dwSize = 64):
"""
Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddre... | Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddress - dwSize to lpAddress + dwSize.
@rtype: list of tuple( long, ... | Below is the the instruction that describes the task:
### Input:
Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddress - ... |
def get_path(url):
"""Get the path (e.g /page/23) of the given URL.
Args:
url (str): The URL to get the path from.
Returns:
str: The path
"""
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
return URLHelper.... | Get the path (e.g /page/23) of the given URL.
Args:
url (str): The URL to get the path from.
Returns:
str: The path | Below is the the instruction that describes the task:
### Input:
Get the path (e.g /page/23) of the given URL.
Args:
url (str): The URL to get the path from.
Returns:
str: The path
### Response:
def get_path(url):
"""Get the path (e.g /page/23) of the given URL.
... |
def initialize_record_handler(test_uid, test_record, notify_update):
"""Initialize the record handler for a test.
For each running test, we attach a record handler to the top-level OpenHTF
logger. The handler will append OpenHTF logs to the test record, while
filtering out logs that are specific to any other t... | Initialize the record handler for a test.
For each running test, we attach a record handler to the top-level OpenHTF
logger. The handler will append OpenHTF logs to the test record, while
filtering out logs that are specific to any other test run. | Below is the the instruction that describes the task:
### Input:
Initialize the record handler for a test.
For each running test, we attach a record handler to the top-level OpenHTF
logger. The handler will append OpenHTF logs to the test record, while
filtering out logs that are specific to any other test r... |
def write (stream_or_path, holders, **kwargs):
"""Very simple writing in ini format. The simple stringification of each value
in each Holder is printed, and no escaping is performed. (This is most
relevant for multiline values or ones containing pound signs.) `None` values are
skipped.
Arguments:
... | Very simple writing in ini format. The simple stringification of each value
in each Holder is printed, and no escaping is performed. (This is most
relevant for multiline values or ones containing pound signs.) `None` values are
skipped.
Arguments:
stream
A text stream to write to.
holder... | Below is the the instruction that describes the task:
### Input:
Very simple writing in ini format. The simple stringification of each value
in each Holder is printed, and no escaping is performed. (This is most
relevant for multiline values or ones containing pound signs.) `None` values are
skipped.
... |
def pty_fork(*args):
"""Runs a subprocess with a PTY attached via fork and exec.
The output from the PTY is streamed through log_to_client.
This should not be necessary for most subprocesses, we
built this to handle Compose up which only streams pull
progress if it is attached to a TTY."""
upda... | Runs a subprocess with a PTY attached via fork and exec.
The output from the PTY is streamed through log_to_client.
This should not be necessary for most subprocesses, we
built this to handle Compose up which only streams pull
progress if it is attached to a TTY. | Below is the the instruction that describes the task:
### Input:
Runs a subprocess with a PTY attached via fork and exec.
The output from the PTY is streamed through log_to_client.
This should not be necessary for most subprocesses, we
built this to handle Compose up which only streams pull
progress... |
def get_assessment_part(self):
"""Gets the parent assessment.
return: (osid.assessment.authoring.AssessmentPart) - the parent
assessment part
raise: IllegalState - ``has_parent_part()`` is ``false``
raise: OperationFailed - unable to complete request
*complianc... | Gets the parent assessment.
return: (osid.assessment.authoring.AssessmentPart) - the parent
assessment part
raise: IllegalState - ``has_parent_part()`` is ``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implem... | Below is the the instruction that describes the task:
### Input:
Gets the parent assessment.
return: (osid.assessment.authoring.AssessmentPart) - the parent
assessment part
raise: IllegalState - ``has_parent_part()`` is ``false``
raise: OperationFailed - unable to complete... |
def check_range(self, j):
"""Check that j is a valid index into self."""
if isinstance(j, int):
if j < 0 or j >= self.size:
raise QiskitIndexError("register index out of range")
elif isinstance(j, slice):
if j.start < 0 or j.stop >= self.size or (j... | Check that j is a valid index into self. | Below is the the instruction that describes the task:
### Input:
Check that j is a valid index into self.
### Response:
def check_range(self, j):
"""Check that j is a valid index into self."""
if isinstance(j, int):
if j < 0 or j >= self.size:
raise QiskitIndexError("reg... |
def CSS_setEffectivePropertyValueForNode(self, nodeId, propertyName, value):
"""
Function path: CSS.setEffectivePropertyValueForNode
Domain: CSS
Method name: setEffectivePropertyValueForNode
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'nodeId' (type: D... | Function path: CSS.setEffectivePropertyValueForNode
Domain: CSS
Method name: setEffectivePropertyValueForNode
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'nodeId' (type: DOM.NodeId) -> The element id for which to set property.
'propertyName' (type: st... | Below is the the instruction that describes the task:
### Input:
Function path: CSS.setEffectivePropertyValueForNode
Domain: CSS
Method name: setEffectivePropertyValueForNode
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'nodeId' (type: DOM.NodeId) -> Th... |
def replace(self, replacements):
"""
Replace variables with other variables.
:param dict replacements: A dict of variable replacements.
:return: self
"""
for old_var, new_var in replacements.items():
old_var_id = id(old_var)
... | Replace variables with other variables.
:param dict replacements: A dict of variable replacements.
:return: self | Below is the the instruction that describes the task:
### Input:
Replace variables with other variables.
:param dict replacements: A dict of variable replacements.
:return: self
### Response:
def replace(self, replacements):
"""
Replace variables with other var... |
def _obtain_credentials(self):
"""
Obtains a credentials handle from secur32.dll for use with SChannel
"""
protocol_values = {
'SSLv3': Secur32Const.SP_PROT_SSL3_CLIENT,
'TLSv1': Secur32Const.SP_PROT_TLS1_CLIENT,
'TLSv1.1': Secur32Const.SP_PROT_TLS1_1... | Obtains a credentials handle from secur32.dll for use with SChannel | Below is the the instruction that describes the task:
### Input:
Obtains a credentials handle from secur32.dll for use with SChannel
### Response:
def _obtain_credentials(self):
"""
Obtains a credentials handle from secur32.dll for use with SChannel
"""
protocol_values = {
... |
async def load(self,
file_path,
locale=None,
key: int = 0,
pos: int = 1,
neg: Optional[ColRanges] = None):
"""
Start the loading/watching process
"""
if neg is None:
neg: ColRanges... | Start the loading/watching process | Below is the the instruction that describes the task:
### Input:
Start the loading/watching process
### Response:
async def load(self,
file_path,
locale=None,
key: int = 0,
pos: int = 1,
neg: Optional[ColRanges] = None):... |
def parse_args():
"""Create an argument parser for the ``build-stack-docs`` program.
Returns
-------
args : `argparse.Namespace`
Parsed argument object.
"""
parser = argparse.ArgumentParser(
description="Build a Sphinx documentation site for an EUPS stack, "
... | Create an argument parser for the ``build-stack-docs`` program.
Returns
-------
args : `argparse.Namespace`
Parsed argument object. | Below is the the instruction that describes the task:
### Input:
Create an argument parser for the ``build-stack-docs`` program.
Returns
-------
args : `argparse.Namespace`
Parsed argument object.
### Response:
def parse_args():
"""Create an argument parser for the ``build-stack-docs`` pro... |
def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
valu... | Urlencode a multidimensional dict. | Below is the the instruction that describes the task:
### Input:
Urlencode a multidimensional dict.
### Response:
def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dic... |
def DEFINE_float(self, name, default, help, constant=False):
"""A helper for defining float options."""
self.AddOption(
type_info.Float(name=name, default=default, description=help),
constant=constant) | A helper for defining float options. | Below is the the instruction that describes the task:
### Input:
A helper for defining float options.
### Response:
def DEFINE_float(self, name, default, help, constant=False):
"""A helper for defining float options."""
self.AddOption(
type_info.Float(name=name, default=default, description=help),
... |
def change_class(self):
""" "on changing the classification label, update the "draw" text """
self.toolbarcenterframe.config(text="Draw: {}".format(self.config.solar_class_name[self.solar_class_var.get()])) | "on changing the classification label, update the "draw" text | Below is the the instruction that describes the task:
### Input:
"on changing the classification label, update the "draw" text
### Response:
def change_class(self):
""" "on changing the classification label, update the "draw" text """
self.toolbarcenterframe.config(text="Draw: {}".format(self.confi... |
def get_assessment_admin_session(self):
"""Gets the ``OsidSession`` associated with the assessment administration service.
return: (osid.assessment.AssessmentAdminSession) - an
``AssessmentAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimpl... | Gets the ``OsidSession`` associated with the assessment administration service.
return: (osid.assessment.AssessmentAdminSession) - an
``AssessmentAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_assessment_admin()`` is
... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the assessment administration service.
return: (osid.assessment.AssessmentAdminSession) - an
``AssessmentAdminSession``
raise: OperationFailed - unable to complete request
... |
def calc_epc_v1(self):
"""Apply the evaporation correction factors and adjust evaporation
to the altitude of the individual zones.
Calculate the areal mean of (uncorrected) potential evaporation
for the subbasin, adjust it to the individual zones in accordance
with their heights and perform some co... | Apply the evaporation correction factors and adjust evaporation
to the altitude of the individual zones.
Calculate the areal mean of (uncorrected) potential evaporation
for the subbasin, adjust it to the individual zones in accordance
with their heights and perform some corrections, among which one
... | Below is the the instruction that describes the task:
### Input:
Apply the evaporation correction factors and adjust evaporation
to the altitude of the individual zones.
Calculate the areal mean of (uncorrected) potential evaporation
for the subbasin, adjust it to the individual zones in accordance
... |
def OnContentChanged(self, event):
"""Titlebar star adjustment event handler"""
self.main_window.grid.update_attribute_toolbar()
title = self.main_window.GetTitle()
if undo.stack().haschanged():
# Put * in front of title
if title[:2] != "* ":
ne... | Titlebar star adjustment event handler | Below is the the instruction that describes the task:
### Input:
Titlebar star adjustment event handler
### Response:
def OnContentChanged(self, event):
"""Titlebar star adjustment event handler"""
self.main_window.grid.update_attribute_toolbar()
title = self.main_window.GetTitle()
... |
def symmetrize_molecule(self):
"""Returns a symmetrized molecule
The equivalent atoms obtained via
:meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms`
are rotated, mirrored... unto one position.
Then the average position is calculated.
The average... | Returns a symmetrized molecule
The equivalent atoms obtained via
:meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms`
are rotated, mirrored... unto one position.
Then the average position is calculated.
The average position is rotated, mirrored... back wit... | Below is the the instruction that describes the task:
### Input:
Returns a symmetrized molecule
The equivalent atoms obtained via
:meth:`~pymatgen.symmetry.analyzer.PointGroupAnalyzer.get_equivalent_atoms`
are rotated, mirrored... unto one position.
Then the average position is calc... |
def convert_celeba(which_format, directory, output_directory,
output_filename=None):
"""Converts the CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is
saved as 'celeba_aligned_cropped.hdf5' o... | Converts the CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is
saved as 'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on the `which_format` argument.
Parameters
----------
which_form... | Below is the the instruction that describes the task:
### Input:
Converts the CelebA dataset to HDF5.
Converts the CelebA dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CelebA`. The converted dataset is
saved as 'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',
depending on the `... |
def get_user_contact_list(self, id, contact_list_id, **data):
"""
GET /users/:id/contact_lists/:contact_list_id/
Gets a user's :format:`contact_list` by ID as ``contact_list``.
"""
return self.get("/users/{0}/contact_lists/{0}/".format(id,contact_list_id), data=data) | GET /users/:id/contact_lists/:contact_list_id/
Gets a user's :format:`contact_list` by ID as ``contact_list``. | Below is the the instruction that describes the task:
### Input:
GET /users/:id/contact_lists/:contact_list_id/
Gets a user's :format:`contact_list` by ID as ``contact_list``.
### Response:
def get_user_contact_list(self, id, contact_list_id, **data):
"""
GET /users/:id/contact_lists/:conta... |
def reverse_delete_ipv6(self, subid, ipaddr, params=None):
''' /v1/server/reverse_delete_ipv6
POST - account
Remove a reverse DNS entry for an IPv6 address of a virtual machine.
Upon success, DNS changes may take 6-12 hours to become active.
Link: https://www.vultr.com/api/#serv... | /v1/server/reverse_delete_ipv6
POST - account
Remove a reverse DNS entry for an IPv6 address of a virtual machine.
Upon success, DNS changes may take 6-12 hours to become active.
Link: https://www.vultr.com/api/#server_reverse_delete_ipv6 | Below is the the instruction that describes the task:
### Input:
/v1/server/reverse_delete_ipv6
POST - account
Remove a reverse DNS entry for an IPv6 address of a virtual machine.
Upon success, DNS changes may take 6-12 hours to become active.
Link: https://www.vultr.com/api/#server... |
def ensure_directory_exists(dirname, context=None):
"""
Ensures that a directory exits.
If it does not exist, it is automatically created.
"""
real_dirname = dirname
if context:
real_dirname = realpath_with_context(dirname, context)
if not os.path.exists(real_dirname):
os.mak... | Ensures that a directory exits.
If it does not exist, it is automatically created. | Below is the the instruction that describes the task:
### Input:
Ensures that a directory exits.
If it does not exist, it is automatically created.
### Response:
def ensure_directory_exists(dirname, context=None):
"""
Ensures that a directory exits.
If it does not exist, it is automatically created... |
def eval_dir(
reference_dir,
estimates_dir,
output_dir=None,
mode='v4',
win=1.0,
hop=1.0,
):
"""Compute bss_eval metrics for two given directories assuming file
names are identical for both, reference source and estimates.
Parameters
----------
reference_dir : str
pa... | Compute bss_eval metrics for two given directories assuming file
names are identical for both, reference source and estimates.
Parameters
----------
reference_dir : str
path to reference sources directory.
estimates_dir : str
path to estimates directory.
output_dir : str
... | Below is the the instruction that describes the task:
### Input:
Compute bss_eval metrics for two given directories assuming file
names are identical for both, reference source and estimates.
Parameters
----------
reference_dir : str
path to reference sources directory.
estimates_dir : ... |
def refactor_dir(self, dir_name, write=False, doctests_only=False):
"""Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped.
"""
py_ext = os.extsep + "py"
... | Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped. | Below is the the instruction that describes the task:
### Input:
Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped.
### Response:
def refactor_dir(self, dir_name, write=False, do... |
def write_to_file(self):
"""
This function calls "gui_batch.py" with inputs values to write the batch file.
"""
bt = BatchFile(self.batch_name_value, self.p_values, self.x_value, self.y_value, self.g_value, self.s_value,
self.z_value, self.wavelength_values, self.v... | This function calls "gui_batch.py" with inputs values to write the batch file. | Below is the the instruction that describes the task:
### Input:
This function calls "gui_batch.py" with inputs values to write the batch file.
### Response:
def write_to_file(self):
"""
This function calls "gui_batch.py" with inputs values to write the batch file.
"""
bt = BatchFil... |
def duplicates_removed(it, already_seen=()):
"""
Returns a list with duplicates removed from the iterable `it`.
Order is preserved.
"""
lst = []
seen = set()
for i in it:
if i in seen or i in already_seen:
continue
lst.append(i)
seen.add(i)
return lst | Returns a list with duplicates removed from the iterable `it`.
Order is preserved. | Below is the the instruction that describes the task:
### Input:
Returns a list with duplicates removed from the iterable `it`.
Order is preserved.
### Response:
def duplicates_removed(it, already_seen=()):
"""
Returns a list with duplicates removed from the iterable `it`.
Order is preserved.
... |
def addlogo(community_id, logo):
"""Add logo to the community."""
# Create the bucket
c = Community.get(community_id)
if not c:
click.secho('Community {0} does not exist.'.format(community_id),
fg='red')
return
ext = save_and_validate_logo(logo, logo.name, c.id)
... | Add logo to the community. | Below is the the instruction that describes the task:
### Input:
Add logo to the community.
### Response:
def addlogo(community_id, logo):
"""Add logo to the community."""
# Create the bucket
c = Community.get(community_id)
if not c:
click.secho('Community {0} does not exist.'.format(commun... |
def _identifiers(self):
"""Return iterable of dataset item identifiers."""
for handle in self._storage_broker.iter_item_handles():
yield dtoolcore.utils.generate_identifier(handle) | Return iterable of dataset item identifiers. | Below is the the instruction that describes the task:
### Input:
Return iterable of dataset item identifiers.
### Response:
def _identifiers(self):
"""Return iterable of dataset item identifiers."""
for handle in self._storage_broker.iter_item_handles():
yield dtoolcore.utils.generate_i... |
def bust_caches(cls, obj, excludes=()):
"""Bust the cache for all :class:`.cached_property` objects on `obj`
:param obj: The instance on which to bust the caches.
"""
for name, _ in cls.get_cached_properties(obj):
if name in obj.__dict__ and not name in excludes:
... | Bust the cache for all :class:`.cached_property` objects on `obj`
:param obj: The instance on which to bust the caches. | Below is the the instruction that describes the task:
### Input:
Bust the cache for all :class:`.cached_property` objects on `obj`
:param obj: The instance on which to bust the caches.
### Response:
def bust_caches(cls, obj, excludes=()):
"""Bust the cache for all :class:`.cached_property` objects... |
def errmsg(self, message, opts={}):
""" Convenience short-hand for self.intf[-1].errmsg """
if 'plain' != self.debugger.settings['highlight']:
message = colorize('standout', message)
pass
return(self.intf[-1].errmsg(message)) | Convenience short-hand for self.intf[-1].errmsg | Below is the the instruction that describes the task:
### Input:
Convenience short-hand for self.intf[-1].errmsg
### Response:
def errmsg(self, message, opts={}):
""" Convenience short-hand for self.intf[-1].errmsg """
if 'plain' != self.debugger.settings['highlight']:
message = coloriz... |
def new_filehandlers_for_filetype(self, filetype_info, filenames, fh_kwargs=None):
"""Create filehandlers for a given filetype."""
filename_iter = self.filename_items_for_filetype(filenames,
filetype_info)
if self.filter_filenames:
... | Create filehandlers for a given filetype. | Below is the the instruction that describes the task:
### Input:
Create filehandlers for a given filetype.
### Response:
def new_filehandlers_for_filetype(self, filetype_info, filenames, fh_kwargs=None):
"""Create filehandlers for a given filetype."""
filename_iter = self.filename_items_for_filetyp... |
def reverse(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
culture=None,
include_country_code=False
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
... | Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latitude)s, %(longitude)s"``.
:pa... | Below is the the instruction that describes the task:
### Input:
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longi... |
def _maketicks(self, ax, units='THz'):
"""Utility method to add tick marks to a band structure."""
# set y-ticks
ax.yaxis.set_major_locator(MaxNLocator(6))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
# set x-ticks; only... | Utility method to add tick marks to a band structure. | Below is the the instruction that describes the task:
### Input:
Utility method to add tick marks to a band structure.
### Response:
def _maketicks(self, ax, units='THz'):
"""Utility method to add tick marks to a band structure."""
# set y-ticks
ax.yaxis.set_major_locator(MaxNLocator(6))
... |
def cookies(self) -> Dict[str, str]:
"""The parsed cookies attached to this request."""
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
return {key: cookie.value for key, cookie in cookies.items()} | The parsed cookies attached to this request. | Below is the the instruction that describes the task:
### Input:
The parsed cookies attached to this request.
### Response:
def cookies(self) -> Dict[str, str]:
"""The parsed cookies attached to this request."""
cookies = SimpleCookie()
cookies.load(self.headers.get('Cookie', ''))
r... |
def suffix(tokens, operator_table):
"""Match a suffix of an operator."""
operator, matched_tokens = operator_table.suffix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) | Match a suffix of an operator. | Below is the the instruction that describes the task:
### Input:
Match a suffix of an operator.
### Response:
def suffix(tokens, operator_table):
"""Match a suffix of an operator."""
operator, matched_tokens = operator_table.suffix.match(tokens)
if operator:
return TokenMatch(operator, None, ma... |
def _get_radius(site):
"""
An internal method to get the expected radius for a site with
oxidation state.
Args:
site: (Site)
Returns:
Oxidation-state dependent radius: ionic, covalent, or atomic.
Returns 0 if no oxidation state or appropriate ... | An internal method to get the expected radius for a site with
oxidation state.
Args:
site: (Site)
Returns:
Oxidation-state dependent radius: ionic, covalent, or atomic.
Returns 0 if no oxidation state or appropriate radius is found. | Below is the the instruction that describes the task:
### Input:
An internal method to get the expected radius for a site with
oxidation state.
Args:
site: (Site)
Returns:
Oxidation-state dependent radius: ionic, covalent, or atomic.
Returns 0 if no oxida... |
def subscribe(self, handler):
"""Adds a new event handler."""
assert callable(handler), "Invalid handler %s" % handler
self.handlers.append(handler) | Adds a new event handler. | Below is the the instruction that describes the task:
### Input:
Adds a new event handler.
### Response:
def subscribe(self, handler):
"""Adds a new event handler."""
assert callable(handler), "Invalid handler %s" % handler
self.handlers.append(handler) |
def smkdirs(dpath, mode=0o777):
"""Safely make a full directory path if it doesn't exist.
Parameters
----------
dpath : str
Path of directory/directories to create
mode : int [default=0777]
Permissions for the new directories
See also
--------
os.makedirs
"""
i... | Safely make a full directory path if it doesn't exist.
Parameters
----------
dpath : str
Path of directory/directories to create
mode : int [default=0777]
Permissions for the new directories
See also
--------
os.makedirs | Below is the the instruction that describes the task:
### Input:
Safely make a full directory path if it doesn't exist.
Parameters
----------
dpath : str
Path of directory/directories to create
mode : int [default=0777]
Permissions for the new directories
See also
--------... |
def _fetch_parent_path(self, request: Request, use_cache: bool=True):
'''Fetch parent directory and return list FileEntry.
Coroutine.
'''
directory_url = to_dir_path_url(request.url_info)
if use_cache:
if directory_url in self._processor.listing_cache:
... | Fetch parent directory and return list FileEntry.
Coroutine. | Below is the the instruction that describes the task:
### Input:
Fetch parent directory and return list FileEntry.
Coroutine.
### Response:
def _fetch_parent_path(self, request: Request, use_cache: bool=True):
'''Fetch parent directory and return list FileEntry.
Coroutine.
'''
... |
async def async_set_port_poe_mode(self, port_idx, mode):
"""Set port poe mode.
Auto, 24v, passthrough, off.
Make sure to not overwrite any existing configs.
"""
no_existing_config = True
for port_override in self.port_overrides:
if port_idx == port_override['... | Set port poe mode.
Auto, 24v, passthrough, off.
Make sure to not overwrite any existing configs. | Below is the the instruction that describes the task:
### Input:
Set port poe mode.
Auto, 24v, passthrough, off.
Make sure to not overwrite any existing configs.
### Response:
async def async_set_port_poe_mode(self, port_idx, mode):
"""Set port poe mode.
Auto, 24v, passthrough, of... |
def fix_quotes(cls, query_string):
"""Heuristic attempt to fix unbalanced quotes in query_string."""
if query_string.count('"') % 2 == 0:
# no unbalanced quotes to fix
return query_string
fields = [] # contains what's matched by the regexp
# e.g. fields = ['sort... | Heuristic attempt to fix unbalanced quotes in query_string. | Below is the the instruction that describes the task:
### Input:
Heuristic attempt to fix unbalanced quotes in query_string.
### Response:
def fix_quotes(cls, query_string):
"""Heuristic attempt to fix unbalanced quotes in query_string."""
if query_string.count('"') % 2 == 0:
# no unbal... |
def does_database_exist(self, database_name):
"""
Checks if a database exists in CosmosDB.
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
existing_database = list(self.get_conn().QueryDatabases({
"query": "SELECT * ... | Checks if a database exists in CosmosDB. | Below is the the instruction that describes the task:
### Input:
Checks if a database exists in CosmosDB.
### Response:
def does_database_exist(self, database_name):
"""
Checks if a database exists in CosmosDB.
"""
if database_name is None:
raise AirflowBadRequest("Datab... |
def get_ccap(self, cycle=None, dataset_number=None):
"""Returns charge_capacity (in mAh/g), and voltage."""
# TODO: should return a DataFrame as default
# but remark that we then have to update e.g. batch_helpers.py
dataset_number = self._validate_dataset_number(dataset_number)
... | Returns charge_capacity (in mAh/g), and voltage. | Below is the the instruction that describes the task:
### Input:
Returns charge_capacity (in mAh/g), and voltage.
### Response:
def get_ccap(self, cycle=None, dataset_number=None):
"""Returns charge_capacity (in mAh/g), and voltage."""
# TODO: should return a DataFrame as default
# but r... |
def parse(binary, **params):
"""Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8')
return json.loads(binary, encoding=encoding) | Turns a JSON structure into a python object. | Below is the the instruction that describes the task:
### Input:
Turns a JSON structure into a python object.
### Response:
def parse(binary, **params):
"""Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8')
return json.loads(binary, encoding=encoding) |
def build_relation_predicate(relations: Strings) -> EdgePredicate:
"""Build an edge predicate that passes for edges with the given relation."""
if isinstance(relations, str):
@edge_predicate
def relation_predicate(edge_data: EdgeData) -> bool:
"""Pass for relations matching the enclo... | Build an edge predicate that passes for edges with the given relation. | Below is the the instruction that describes the task:
### Input:
Build an edge predicate that passes for edges with the given relation.
### Response:
def build_relation_predicate(relations: Strings) -> EdgePredicate:
"""Build an edge predicate that passes for edges with the given relation."""
if isinstance... |
def get_total_size_of_queued_replicas():
"""Return the total number of bytes of requested, unprocessed replicas."""
return (
d1_gmn.app.models.ReplicationQueue.objects.filter(
local_replica__info__status__status='queued'
).aggregate(Sum('size'))['size__sum']
or 0
) | Return the total number of bytes of requested, unprocessed replicas. | Below is the the instruction that describes the task:
### Input:
Return the total number of bytes of requested, unprocessed replicas.
### Response:
def get_total_size_of_queued_replicas():
"""Return the total number of bytes of requested, unprocessed replicas."""
return (
d1_gmn.app.models.Replicat... |
def _get_after_tld_chars(self):
"""
Initialize after tld characters
"""
after_tld_chars = set(string.whitespace)
after_tld_chars |= {'/', '\"', '\'', '<', '>', '?', ':', '.', ','}
# get left enclosure characters
_, right_enclosure = zip(*self._enclosure)
#... | Initialize after tld characters | Below is the the instruction that describes the task:
### Input:
Initialize after tld characters
### Response:
def _get_after_tld_chars(self):
"""
Initialize after tld characters
"""
after_tld_chars = set(string.whitespace)
after_tld_chars |= {'/', '\"', '\'', '<', '>', '?',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.