code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def build_software_cache(sw_dir=None):
"""
Builds up the software cache directory at *sw_dir* by simply copying all required python
modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`.
"""
# ensure the cache is empty
sw_dir = get_sw_dir(sw_dir)
remove_software_cache(sw_dir)
os.make... | Builds up the software cache directory at *sw_dir* by simply copying all required python
modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`. | Below is the the instruction that describes the task:
### Input:
Builds up the software cache directory at *sw_dir* by simply copying all required python
modules. *sw_dir* is evaluated with :py:func:`get_sw_dir`.
### Response:
def build_software_cache(sw_dir=None):
"""
Builds up the software cache dire... |
def supply_and_demand(
lcm, choosers, alternatives, alt_segmenter, price_col,
base_multiplier=None, clip_change_low=0.75, clip_change_high=1.25,
iterations=5, multiplier_func=None):
"""
Adjust real estate prices to compensate for supply and demand effects.
Parameters
----------
... | Adjust real estate prices to compensate for supply and demand effects.
Parameters
----------
lcm : LocationChoiceModel
Used to calculate the probability of agents choosing among
alternatives. Must be fully configured and fitted.
choosers : pandas.DataFrame
alternatives : pandas.Data... | Below is the the instruction that describes the task:
### Input:
Adjust real estate prices to compensate for supply and demand effects.
Parameters
----------
lcm : LocationChoiceModel
Used to calculate the probability of agents choosing among
alternatives. Must be fully configured and f... |
def warningFlag(self):
'''
When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check ... | When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the template need not
check each of these conditions individually repea... | Below is the the instruction that describes the task:
### Input:
When viewing individual event registrations, there are a large number of potential
issues that can arise that may warrant scrutiny. This property just checks all of
these conditions and indicates if anything is amiss so that the templa... |
def prepare(self, f):
"""Accept an objective function for optimization."""
self.g = autograd.grad(f)
self.h = autograd.hessian(f) | Accept an objective function for optimization. | Below is the the instruction that describes the task:
### Input:
Accept an objective function for optimization.
### Response:
def prepare(self, f):
"""Accept an objective function for optimization."""
self.g = autograd.grad(f)
self.h = autograd.hessian(f) |
def plot_hist(f, height=20.0, bincount=None, binwidth=None, pch="o", colour="default", title="", xlab=None, showSummary=False, regular=False):
"""
Make a histogram
Arguments:
height -- the height of the histogram in # of lines
bincount -- number of bins in the histogram
binwidth -- ... | Make a histogram
Arguments:
height -- the height of the histogram in # of lines
bincount -- number of bins in the histogram
binwidth -- width of bins in the histogram
pch -- shape of the bars in the plot
colour -- colour of the bars in the terminal
title -- title at ... | Below is the the instruction that describes the task:
### Input:
Make a histogram
Arguments:
height -- the height of the histogram in # of lines
bincount -- number of bins in the histogram
binwidth -- width of bins in the histogram
pch -- shape of the bars in the plot
co... |
def _get_all_file_versions(self, secure_data_path, limit=None):
"""
Convenience function that returns a generator yielding the contents of all versions of
a file and its version info
secure_data_path -- full path to the file in the safety deposit box
limit -- Default(100), limit... | Convenience function that returns a generator yielding the contents of all versions of
a file and its version info
secure_data_path -- full path to the file in the safety deposit box
limit -- Default(100), limits how many records to be returned from the api at once. | Below is the the instruction that describes the task:
### Input:
Convenience function that returns a generator yielding the contents of all versions of
a file and its version info
secure_data_path -- full path to the file in the safety deposit box
limit -- Default(100), limits how many reco... |
def _scan_instance(obj, include_underscore, exclude):
"""(Executed on remote or local engine) Examines an object and returns info
about any instance-specific methods or attributes.
(For example, any attributes that were set by __init__() )
By default, methods or attributes starting with an underscore a... | (Executed on remote or local engine) Examines an object and returns info
about any instance-specific methods or attributes.
(For example, any attributes that were set by __init__() )
By default, methods or attributes starting with an underscore are ignored.
Args:
obj (object): the object to scan... | Below is the the instruction that describes the task:
### Input:
(Executed on remote or local engine) Examines an object and returns info
about any instance-specific methods or attributes.
(For example, any attributes that were set by __init__() )
By default, methods or attributes starting with an unde... |
def read_apply(lib, symbol, func, chunk_range=None):
"""
Apply `func` to each chunk in lib.symbol
Parameters
----------
lib: arctic library
symbol: str
the symbol for the given item in the DB
chunk_range: None, or a range object
allows you to subset the chunks by range
... | Apply `func` to each chunk in lib.symbol
Parameters
----------
lib: arctic library
symbol: str
the symbol for the given item in the DB
chunk_range: None, or a range object
allows you to subset the chunks by range
Returns
-------
generator | Below is the the instruction that describes the task:
### Input:
Apply `func` to each chunk in lib.symbol
Parameters
----------
lib: arctic library
symbol: str
the symbol for the given item in the DB
chunk_range: None, or a range object
allows you to subset the chunks by range
... |
def get(self, catID, includeRelationships=False):
'''Retrieves the strip footprint WKT string given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
includeRelationships (bool): whether to include graph links to related objects. Default False.
... | Retrieves the strip footprint WKT string given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
includeRelationships (bool): whether to include graph links to related objects. Default False.
Returns:
record (dict): A dict object identic... | Below is the the instruction that describes the task:
### Input:
Retrieves the strip footprint WKT string given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
includeRelationships (bool): whether to include graph links to related objects. Default Fals... |
def rm_crypttab(name, config='/etc/crypttab'):
'''
Remove the named mapping from the crypttab. If the described entry does not
exist, nothing is changed, but the command succeeds by returning
``'absent'``. If a line is removed, it returns ``'change'``.
CLI Example:
.. code-block:: bash
... | Remove the named mapping from the crypttab. If the described entry does not
exist, nothing is changed, but the command succeeds by returning
``'absent'``. If a line is removed, it returns ``'change'``.
CLI Example:
.. code-block:: bash
salt '*' cryptdev.rm_crypttab foo | Below is the the instruction that describes the task:
### Input:
Remove the named mapping from the crypttab. If the described entry does not
exist, nothing is changed, but the command succeeds by returning
``'absent'``. If a line is removed, it returns ``'change'``.
CLI Example:
.. code-block:: ba... |
def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True):
"""
IoU for foreground class
binary: 1 foreground, 0 background
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
intersection = ((label == 1) & (pre... | IoU for foreground class
binary: 1 foreground, 0 background | Below is the the instruction that describes the task:
### Input:
IoU for foreground class
binary: 1 foreground, 0 background
### Response:
def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True):
"""
IoU for foreground class
binary: 1 foreground, 0 background
"""
if not per_ima... |
def _compute(self, inputs, outputs):
"""
Run one iteration of TMRegion's compute
"""
#if self.topDownMode and (not 'topDownIn' in inputs):
# raise RuntimeError("The input topDownIn must be linked in if "
# "topDownMode is True")
if self._tfdr is None:
raise Runtime... | Run one iteration of TMRegion's compute | Below is the the instruction that describes the task:
### Input:
Run one iteration of TMRegion's compute
### Response:
def _compute(self, inputs, outputs):
"""
Run one iteration of TMRegion's compute
"""
#if self.topDownMode and (not 'topDownIn' in inputs):
# raise RuntimeError("The input topD... |
def move(self, key, db):
"""Move key from the currently selected database (see
:meth:`~tredis.RedisClient.select`) to the specified destination
database. When key already exists in the destination database, or it
does not exist in the source database, it does nothing. It is possible
... | Move key from the currently selected database (see
:meth:`~tredis.RedisClient.select`) to the specified destination
database. When key already exists in the destination database, or it
does not exist in the source database, it does nothing. It is possible
to use :meth:`~tredis.RedisClien... | Below is the the instruction that describes the task:
### Input:
Move key from the currently selected database (see
:meth:`~tredis.RedisClient.select`) to the specified destination
database. When key already exists in the destination database, or it
does not exist in the source database, it ... |
def _run_pass(self):
"""Read lines from a file and performs a callback against them"""
while True:
try:
data = self._file.read(4096)
except IOError, e:
if e.errno == errno.ESTALE:
self.active = False
return F... | Read lines from a file and performs a callback against them | Below is the the instruction that describes the task:
### Input:
Read lines from a file and performs a callback against them
### Response:
def _run_pass(self):
"""Read lines from a file and performs a callback against them"""
while True:
try:
data = self._file.read(4096)... |
def fastgapfill(model_extended, core, solver, weights={}, epsilon=1e-5):
"""Run FastGapFill gap-filling algorithm by calling
:func:`psamm.fastcore.fastcore`.
FastGapFill will try to find a minimum subset of reactions that includes
the core reactions and it also has no blocked reactions.
Return the ... | Run FastGapFill gap-filling algorithm by calling
:func:`psamm.fastcore.fastcore`.
FastGapFill will try to find a minimum subset of reactions that includes
the core reactions and it also has no blocked reactions.
Return the set of reactions in the minimum subset. An extended model that
includes arti... | Below is the the instruction that describes the task:
### Input:
Run FastGapFill gap-filling algorithm by calling
:func:`psamm.fastcore.fastcore`.
FastGapFill will try to find a minimum subset of reactions that includes
the core reactions and it also has no blocked reactions.
Return the set of reac... |
def url_for(**options):
'''Returns the url for the specified options'''
url_parts = get_url_parts(**options)
image_hash = hashlib.md5(b(options['image_url'])).hexdigest()
url_parts.append(image_hash)
return "/".join(url_parts) | Returns the url for the specified options | Below is the the instruction that describes the task:
### Input:
Returns the url for the specified options
### Response:
def url_for(**options):
'''Returns the url for the specified options'''
url_parts = get_url_parts(**options)
image_hash = hashlib.md5(b(options['image_url'])).hexdigest()
url_pa... |
def AddSeasonDirTable(self, showID, seasonNum, seasonDir):
"""
Add entry to SeasonDir table. If a different entry for season directory
is found for the given show id and season number combination this raises
a fatal error.
Parameters
----------
showID : int
Show id.
seasonN... | Add entry to SeasonDir table. If a different entry for season directory
is found for the given show id and season number combination this raises
a fatal error.
Parameters
----------
showID : int
Show id.
seasonNum : int
Season number.
seasonDir : string
Seaso... | Below is the the instruction that describes the task:
### Input:
Add entry to SeasonDir table. If a different entry for season directory
is found for the given show id and season number combination this raises
a fatal error.
Parameters
----------
showID : int
Show id.
seasonNum... |
def upgrade(**kwargs):
'''
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
... | Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet implemented for Windows.
Returns:
dict: Empty dict, until imp... | Below is the the instruction that describes the task:
### Input:
Upgrade all software. Currently not implemented
Kwargs:
saltenv (str): The salt environment to use. Default ``base``.
refresh (bool): Refresh package metadata. Default ``True``.
.. note::
This feature is not yet imple... |
def complete_multipart_upload(self, key_name, upload_id,
xml_body, headers=None):
"""
Complete a multipart upload operation.
"""
query_args = 'uploadId=%s' % upload_id
if headers is None:
headers = {}
headers['Content-Type'] =... | Complete a multipart upload operation. | Below is the the instruction that describes the task:
### Input:
Complete a multipart upload operation.
### Response:
def complete_multipart_upload(self, key_name, upload_id,
xml_body, headers=None):
"""
Complete a multipart upload operation.
"""
qu... |
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision) | Mapped mpv seek command, see man mpv(1). | Below is the the instruction that describes the task:
### Input:
Mapped mpv seek command, see man mpv(1).
### Response:
def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision) |
def set_principal_credit_string(self, credit_string):
"""Sets the principal credit string.
arg: credit_string (string): the new credit string
raise: InvalidArgument - ``credit_string`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument -... | Sets the principal credit string.
arg: credit_string (string): the new credit string
raise: InvalidArgument - ``credit_string`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``credit_string`` is ``null``
*compliance: mandatory -- ... | Below is the the instruction that describes the task:
### Input:
Sets the principal credit string.
arg: credit_string (string): the new credit string
raise: InvalidArgument - ``credit_string`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgume... |
def load_rel(self, reltype, target, rId, is_external=False):
"""
Return newly added |_Relationship| instance of *reltype* between this
part and *target* with key *rId*. Target mode is set to
``RTM.EXTERNAL`` if *is_external* is |True|. Intended for use during
load from a serializ... | Return newly added |_Relationship| instance of *reltype* between this
part and *target* with key *rId*. Target mode is set to
``RTM.EXTERNAL`` if *is_external* is |True|. Intended for use during
load from a serialized package, where the rId is well known. Other
methods exist for adding a... | Below is the the instruction that describes the task:
### Input:
Return newly added |_Relationship| instance of *reltype* between this
part and *target* with key *rId*. Target mode is set to
``RTM.EXTERNAL`` if *is_external* is |True|. Intended for use during
load from a serialized package, ... |
def get_units_from_category(self, category) -> typing.Iterator['BaseUnit']:
"""
Args:
category: unit category
Returns: generator over all units of a specific category in this coalition
"""
Mission.validator_group_category.validate(category, 'group category')
... | Args:
category: unit category
Returns: generator over all units of a specific category in this coalition | Below is the the instruction that describes the task:
### Input:
Args:
category: unit category
Returns: generator over all units of a specific category in this coalition
### Response:
def get_units_from_category(self, category) -> typing.Iterator['BaseUnit']:
"""
Args:
... |
def updateEditorGeometry(self, editor, option, index):
""" Ensures that the editor is displayed correctly with respect to the item view.
"""
cti = index.model().getItem(index)
if cti.checkState is None:
displayRect = option.rect
else:
checkBoxRect = widget... | Ensures that the editor is displayed correctly with respect to the item view. | Below is the the instruction that describes the task:
### Input:
Ensures that the editor is displayed correctly with respect to the item view.
### Response:
def updateEditorGeometry(self, editor, option, index):
""" Ensures that the editor is displayed correctly with respect to the item view.
"""
... |
def synset_signatures(ss: "wn.Synset", hyperhypo=True, adapted=False,
remove_stopwords=True, to_lemmatize=True, remove_numbers=True,
lowercase=True, original_lesk=False, from_cache=True) -> set:
"""
Takes a Synset and returns its signature words.
:param ss: An in... | Takes a Synset and returns its signature words.
:param ss: An instance of wn.Synset.
:return: A set of signature strings | Below is the the instruction that describes the task:
### Input:
Takes a Synset and returns its signature words.
:param ss: An instance of wn.Synset.
:return: A set of signature strings
### Response:
def synset_signatures(ss: "wn.Synset", hyperhypo=True, adapted=False,
remove_stopwor... |
def clear(self) -> None:
"""
Destroys all running containers.
"""
r = self.__api.delete('containers')
if r.status_code != 204:
self.__api.handle_erroneous_response(r) | Destroys all running containers. | Below is the the instruction that describes the task:
### Input:
Destroys all running containers.
### Response:
def clear(self) -> None:
"""
Destroys all running containers.
"""
r = self.__api.delete('containers')
if r.status_code != 204:
self.__api.handle_errone... |
def draw(self, context):
"""Draws self to Cairo context"""
context.set_line_width(self.width)
context.set_source_rgb(*self.color)
context.move_to(*self.start_point)
context.line_to(*self.end_point)
context.stroke() | Draws self to Cairo context | Below is the the instruction that describes the task:
### Input:
Draws self to Cairo context
### Response:
def draw(self, context):
"""Draws self to Cairo context"""
context.set_line_width(self.width)
context.set_source_rgb(*self.color)
context.move_to(*self.start_point)
c... |
def set_mode(self, mode):
"""
:Parameters:
`mode` : *(int)*
New mode, must be one of:
- `StreamTokenizer.STRICT_MIN_LENGTH`
- `StreamTokenizer.DROP_TRAILING_SILENCE`
- `StreamTokenizer.STRICT_MIN_LENGTH | StreamTokenizer.DROP_TRAILING_... | :Parameters:
`mode` : *(int)*
New mode, must be one of:
- `StreamTokenizer.STRICT_MIN_LENGTH`
- `StreamTokenizer.DROP_TRAILING_SILENCE`
- `StreamTokenizer.STRICT_MIN_LENGTH | StreamTokenizer.DROP_TRAILING_SILENCE`
- `0`
See `Stre... | Below is the the instruction that describes the task:
### Input:
:Parameters:
`mode` : *(int)*
New mode, must be one of:
- `StreamTokenizer.STRICT_MIN_LENGTH`
- `StreamTokenizer.DROP_TRAILING_SILENCE`
- `StreamTokenizer.STRICT_MIN_LENGTH | StreamT... |
def itemgetters(*args):
"""
Get a handful of items from an iterable.
This is just map(itemgetter(...), iterable) with a list comprehension.
"""
f = itemgetter(*args)
def inner(l):
return [f(x) for x in l]
return inner | Get a handful of items from an iterable.
This is just map(itemgetter(...), iterable) with a list comprehension. | Below is the the instruction that describes the task:
### Input:
Get a handful of items from an iterable.
This is just map(itemgetter(...), iterable) with a list comprehension.
### Response:
def itemgetters(*args):
"""
Get a handful of items from an iterable.
This is just map(itemgetter(...), ite... |
def compute(self, inputs, outputs):
"""
Run one iteration of TemporalPoolerRegion's compute.
Note that if the reset signal is True (1) we assume this iteration
represents the *end* of a sequence. The output will contain the pooled
representation to this point and any history will then be reset. The... | Run one iteration of TemporalPoolerRegion's compute.
Note that if the reset signal is True (1) we assume this iteration
represents the *end* of a sequence. The output will contain the pooled
representation to this point and any history will then be reset. The output
at the next compute will start fresh... | Below is the the instruction that describes the task:
### Input:
Run one iteration of TemporalPoolerRegion's compute.
Note that if the reset signal is True (1) we assume this iteration
represents the *end* of a sequence. The output will contain the pooled
representation to this point and any history wi... |
def positiveint(value):
"""
:param value: input string
:returns: positive integer
"""
i = int(not_empty(value))
if i < 0:
raise ValueError('integer %d < 0' % i)
return i | :param value: input string
:returns: positive integer | Below is the the instruction that describes the task:
### Input:
:param value: input string
:returns: positive integer
### Response:
def positiveint(value):
"""
:param value: input string
:returns: positive integer
"""
i = int(not_empty(value))
if i < 0:
raise ValueError('intege... |
def uplink_bond_intf_process(self):
"""Process the case when uplink interface becomes part of a bond.
This is called to check if the phy interface became a part of the
bond. If the below condition is True, this means, a physical
interface that was not a part of a bond was earlier discov... | Process the case when uplink interface becomes part of a bond.
This is called to check if the phy interface became a part of the
bond. If the below condition is True, this means, a physical
interface that was not a part of a bond was earlier discovered as
uplink and now that interface b... | Below is the the instruction that describes the task:
### Input:
Process the case when uplink interface becomes part of a bond.
This is called to check if the phy interface became a part of the
bond. If the below condition is True, this means, a physical
interface that was not a part of a b... |
def ajax_list_catalog(self, catid):
'''
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
'''
out_arr = {}
for catinfo in MPost2Catalog.query_postinfo_by_cat(catid):
out_arr[catinfo.uid] = catinfo.title
json.dump(out_arr, ... | Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式 | Below is the the instruction that describes the task:
### Input:
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
### Response:
def ajax_list_catalog(self, catid):
'''
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
... |
def make_filter(**tests):
"""Create a filter from keyword arguments."""
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests) | Create a filter from keyword arguments. | Below is the the instruction that describes the task:
### Input:
Create a filter from keyword arguments.
### Response:
def make_filter(**tests):
"""Create a filter from keyword arguments."""
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests) |
def get_classifications(subcategory_key):
"""Get hazard or exposure classifications.
:param subcategory_key: The hazard or exposure key
:type subcategory_key: str
:returns: List of hazard or exposure classifications
:rtype: list
"""
classifications = definition(subcategory_key)['classifica... | Get hazard or exposure classifications.
:param subcategory_key: The hazard or exposure key
:type subcategory_key: str
:returns: List of hazard or exposure classifications
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get hazard or exposure classifications.
:param subcategory_key: The hazard or exposure key
:type subcategory_key: str
:returns: List of hazard or exposure classifications
:rtype: list
### Response:
def get_classifications(subcategor... |
def _parse_node(self, node, state):
"""Entry point for parsing all node types.
:param node: The lxml HTML node to parse
:param state: The global state necessary to place the node in context
of the document as a whole.
:rtype: a *generator* of Sentences
"""
# ... | Entry point for parsing all node types.
:param node: The lxml HTML node to parse
:param state: The global state necessary to place the node in context
of the document as a whole.
:rtype: a *generator* of Sentences | Below is the the instruction that describes the task:
### Input:
Entry point for parsing all node types.
:param node: The lxml HTML node to parse
:param state: The global state necessary to place the node in context
of the document as a whole.
:rtype: a *generator* of Sentences
... |
def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs) | if there's a start method for this element, call it | Below is the the instruction that describes the task:
### Input:
if there's a start method for this element, call it
### Response:
def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name... |
def forms_valid(self, form, inlines):
"""
If the form and formsets are valid, save the associated models.
"""
response = self.form_valid(form)
for formset in inlines:
formset.save()
return response | If the form and formsets are valid, save the associated models. | Below is the the instruction that describes the task:
### Input:
If the form and formsets are valid, save the associated models.
### Response:
def forms_valid(self, form, inlines):
"""
If the form and formsets are valid, save the associated models.
"""
response = self.form_valid(for... |
def off_coordinator(self, year):
"""Returns the coach ID for the team's OC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the OC.
"""
try:
oc_anchor = self._year_info_pq(year, 'Offensive Coordinator')('a')
... | Returns the coach ID for the team's OC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the OC. | Below is the the instruction that describes the task:
### Input:
Returns the coach ID for the team's OC in a given year.
:year: An int representing the year.
:returns: A string containing the coach ID of the OC.
### Response:
def off_coordinator(self, year):
"""Returns the coach ID for the... |
def zrange(self, name, start, end, desc=False, withscores=False,
score_cast_func=float):
"""
Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param en... | Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
:param score_cast_func:
:return: | Below is the the instruction that describes the task:
### Input:
Returns all the elements including between ``start`` (non included)
and ``stop`` (included).
:param name: str the name of the redis key
:param start:
:param end:
:param desc:
:param withscores:
... |
def writeline(self, line, line_number):
"""Rewrite a single line in the file.
Args:
line (str): The new text to write to the file.
line_number (int): The line of the file to rewrite. Numbering
starts at 0.
"""
tmp_file = tempfile.TemporaryFile('w+... | Rewrite a single line in the file.
Args:
line (str): The new text to write to the file.
line_number (int): The line of the file to rewrite. Numbering
starts at 0. | Below is the the instruction that describes the task:
### Input:
Rewrite a single line in the file.
Args:
line (str): The new text to write to the file.
line_number (int): The line of the file to rewrite. Numbering
starts at 0.
### Response:
def writeline(self, line... |
def exportCustomers(self, outPath):
"""exports customer list to a csv file
Input:
outPath - save location of the customer list
"""
url = "%s/customers/export" % self.root
params = {"f":"csv"}
dirPath = None
fileName = None
if outPath is not None:
... | exports customer list to a csv file
Input:
outPath - save location of the customer list | Below is the the instruction that describes the task:
### Input:
exports customer list to a csv file
Input:
outPath - save location of the customer list
### Response:
def exportCustomers(self, outPath):
"""exports customer list to a csv file
Input:
outPath - save location ... |
def run_benchmark():
""" Run a set of InsertWorkers and record their performance. """
stopping = threading.Event()
workers = [ InsertWorker(stopping) for _ in range(NUM_WORKERS) ]
print('Launching %d workers' % NUM_WORKERS)
[ worker.start() for worker in workers ]
time.sleep(WORKLOAD_TIME)
... | Run a set of InsertWorkers and record their performance. | Below is the the instruction that describes the task:
### Input:
Run a set of InsertWorkers and record their performance.
### Response:
def run_benchmark():
""" Run a set of InsertWorkers and record their performance. """
stopping = threading.Event()
workers = [ InsertWorker(stopping) for _ in range(N... |
def use(cls, ec):
"""
use will duplicate a new Model class and bind ec
ec is Engine name or Sesstion object
"""
if isinstance(ec, (str, unicode)):
m = get_model(cls._alias, ec, signal=False)
else:
m = cls._use(ec)
return m | use will duplicate a new Model class and bind ec
ec is Engine name or Sesstion object | Below is the the instruction that describes the task:
### Input:
use will duplicate a new Model class and bind ec
ec is Engine name or Sesstion object
### Response:
def use(cls, ec):
"""
use will duplicate a new Model class and bind ec
ec is Engine name or Sesstion... |
def file_dump(self, data, filename): # pylint: disable=no-self-use
"""
Dump the data to a JSON formatted file
:param data: data to be dumped
:param filename: name of the file to use. Only the file name, not the full path!
:return: dumped file absolute file name
"""
... | Dump the data to a JSON formatted file
:param data: data to be dumped
:param filename: name of the file to use. Only the file name, not the full path!
:return: dumped file absolute file name | Below is the the instruction that describes the task:
### Input:
Dump the data to a JSON formatted file
:param data: data to be dumped
:param filename: name of the file to use. Only the file name, not the full path!
:return: dumped file absolute file name
### Response:
def file_dump(self, d... |
def _silence():
"""A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
exception_occurred = False
try:
yield
except:
exception_occurred = True
# Go ahead... | A context manager that silences sys.stdout and sys.stderr. | Below is the the instruction that describes the task:
### Input:
A context manager that silences sys.stdout and sys.stderr.
### Response:
def _silence():
"""A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
s... |
def create_exchange_for_vhost(self, exchange, vhost, body):
"""
Create an individual exchange.
The body should look like:
::
{
"type": "direct",
"auto_delete": false,
"durable": true,
"internal": false,
... | Create an individual exchange.
The body should look like:
::
{
"type": "direct",
"auto_delete": false,
"durable": true,
"internal": false,
"arguments": {}
}
The type key is mandatory; other ... | Below is the the instruction that describes the task:
### Input:
Create an individual exchange.
The body should look like:
::
{
"type": "direct",
"auto_delete": false,
"durable": true,
"internal": false,
"ar... |
def get_related_ids(self):
"""
Get all of the IDs for the related models.
:rtype: list
"""
related = self.get_related()
full_key = related.get_qualified_key_name()
return self.get_query().select(full_key).lists(related.get_key_name()) | Get all of the IDs for the related models.
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get all of the IDs for the related models.
:rtype: list
### Response:
def get_related_ids(self):
"""
Get all of the IDs for the related models.
:rtype: list
"""
related = self.get_related()
f... |
def calculate_extents(labels, indexes):
"""Return the area of each object divided by the area of its bounding box"""
fix = fixup_scipy_ndimage_result
areas = fix(scind.sum(np.ones(labels.shape),labels,np.array(indexes, dtype=np.int32)))
y,x = np.mgrid[0:labels.shape[0],0:labels.shape[1]]
xmin = fix(... | Return the area of each object divided by the area of its bounding box | Below is the the instruction that describes the task:
### Input:
Return the area of each object divided by the area of its bounding box
### Response:
def calculate_extents(labels, indexes):
"""Return the area of each object divided by the area of its bounding box"""
fix = fixup_scipy_ndimage_result
are... |
def close(self):
""" Close the tunnel.
If the tunnel is already closed or never opened,
do nothing.
"""
if self.fd is None:
return
logger.debug("Closing tunnel '%s'..." % (self.name or "", ))
# Close tun.ko file
os.close(... | Close the tunnel.
If the tunnel is already closed or never opened,
do nothing. | Below is the the instruction that describes the task:
### Input:
Close the tunnel.
If the tunnel is already closed or never opened,
do nothing.
### Response:
def close(self):
""" Close the tunnel.
If the tunnel is already closed or never opened,
do nothing.
... |
def set_features(self, features):
"""Set features in the disco#info object.
All existing features are removed from `self`.
:Parameters:
- `features`: list of features.
:Types:
- `features`: sequence of `unicode`
"""
for var in self.features:
... | Set features in the disco#info object.
All existing features are removed from `self`.
:Parameters:
- `features`: list of features.
:Types:
- `features`: sequence of `unicode` | Below is the the instruction that describes the task:
### Input:
Set features in the disco#info object.
All existing features are removed from `self`.
:Parameters:
- `features`: list of features.
:Types:
- `features`: sequence of `unicode`
### Response:
def set_fea... |
def clear(self, ts=None):
"""Clear all session in prepare phase.
:param ts: timestamp used locate the namespace
"""
sp_key = "%s:session_prepare" % self.namespace(ts or int(time.time()))
return self.r.delete(sp_key) | Clear all session in prepare phase.
:param ts: timestamp used locate the namespace | Below is the the instruction that describes the task:
### Input:
Clear all session in prepare phase.
:param ts: timestamp used locate the namespace
### Response:
def clear(self, ts=None):
"""Clear all session in prepare phase.
:param ts: timestamp used locate the namespace
"""
... |
def hex2termhex(hexval: str, allow_short: bool = False) -> str:
""" Convert a hex value into the nearest terminal color matched hex. """
return rgb2termhex(*hex2rgb(hexval, allow_short=allow_short)) | Convert a hex value into the nearest terminal color matched hex. | Below is the the instruction that describes the task:
### Input:
Convert a hex value into the nearest terminal color matched hex.
### Response:
def hex2termhex(hexval: str, allow_short: bool = False) -> str:
""" Convert a hex value into the nearest terminal color matched hex. """
return rgb2termhex(*hex2rg... |
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate:
"""Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero,
else do gate1 on 1"""
assert gate0.qubits == gate1.qubits # FIXME
tensor = join_gates(P0(control), gate0).tensor
tensor += join_gates(P1(control), gate1... | Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero,
else do gate1 on 1 | Below is the the instruction that describes the task:
### Input:
Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero,
else do gate1 on 1
### Response:
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate:
"""Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 i... |
def _send_packet(self, sid, pkt):
"""Send a Socket.IO packet to a client."""
encoded_packet = pkt.encode()
if isinstance(encoded_packet, list):
binary = False
for ep in encoded_packet:
self.eio.send(sid, ep, binary=binary)
binary = True
... | Send a Socket.IO packet to a client. | Below is the the instruction that describes the task:
### Input:
Send a Socket.IO packet to a client.
### Response:
def _send_packet(self, sid, pkt):
"""Send a Socket.IO packet to a client."""
encoded_packet = pkt.encode()
if isinstance(encoded_packet, list):
binary = False
... |
def non_transactional(func, args, kwds, allow_existing=True):
"""A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an exce... | A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an exception if called from within
a transaction. If true, temporar... | Below is the the instruction that describes the task:
### Input:
A decorator that ensures a function is run outside a transaction.
If there is an existing transaction (and allow_existing=True), the
existing transaction is paused while the function is executed.
Args:
allow_existing: If false, throw an ex... |
def _set_system_monitor(self, v, load=False):
"""
Setter method for system_monitor, mapped from YANG variable /rbridge_id/system_monitor (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_monitor is considered as a private
method. Backends looking to ... | Setter method for system_monitor, mapped from YANG variable /rbridge_id/system_monitor (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_monitor is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... | Below is the the instruction that describes the task:
### Input:
Setter method for system_monitor, mapped from YANG variable /rbridge_id/system_monitor (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_system_monitor is considered as a private
method. Backends ... |
def zulu(self):
''' a method to report ISO UTC datetime string from a labDT object
NOTE: for timezone offset string use .isoformat() instead
:return: string in ISO UTC format
'''
# construct ISO UTC string from labDT
utc_dt = self.astimezone(pytz.utc)
i... | a method to report ISO UTC datetime string from a labDT object
NOTE: for timezone offset string use .isoformat() instead
:return: string in ISO UTC format | Below is the the instruction that describes the task:
### Input:
a method to report ISO UTC datetime string from a labDT object
NOTE: for timezone offset string use .isoformat() instead
:return: string in ISO UTC format
### Response:
def zulu(self):
''' a method to report ISO UTC d... |
def compute_association_matrix_of_groups(adata, prediction, reference,
normalization='prediction',
threshold=0.01, max_n_names=2):
"""Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Param... | Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Parameters
----------
adata : AnnData
prediction : str
Field name of adata.obs.
reference : str
Field name of adata.obs.
normalization : {'prediction', 'reference'}
Whether to norma... | Below is the the instruction that describes the task:
### Input:
Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Parameters
----------
adata : AnnData
prediction : str
Field name of adata.obs.
reference : str
Field name of adata.obs.
... |
def make_decorator(func):
"""
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
"""
def decorate(newfunc):
if hasattr(func, 'compat_func_name'):
name = func.compat_func_name
... | Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown). | Below is the the instruction that describes the task:
### Input:
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
### Response:
def make_decorator(func):
"""
Wraps a test decorator so as to properl... |
def query_sequence_retriever(fastaq_handle, b6_handle, e_value,
fastaq='fasta', *args, **kwargs):
"""Returns FASTA entries for subject sequences from BLAST hits
Stores B6/M8 entries with E-Values below the e_value cutoff. Then iterates
through the FASTA file and if an entry mat... | Returns FASTA entries for subject sequences from BLAST hits
Stores B6/M8 entries with E-Values below the e_value cutoff. Then iterates
through the FASTA file and if an entry matches the query of an B6/M8
entry, it's sequence is extracted and returned as a FASTA entry
plus the E-Value.
Args:
... | Below is the the instruction that describes the task:
### Input:
Returns FASTA entries for subject sequences from BLAST hits
Stores B6/M8 entries with E-Values below the e_value cutoff. Then iterates
through the FASTA file and if an entry matches the query of an B6/M8
entry, it's sequence is extracted ... |
def callSetsGenerator(self, request):
"""
Returns a generator over the (callSet, nextPageToken) pairs defined
by the specified request.
"""
compoundId = datamodel.VariantSetCompoundId.parse(
request.variant_set_id)
dataset = self.getDataRepository().getDataset... | Returns a generator over the (callSet, nextPageToken) pairs defined
by the specified request. | Below is the the instruction that describes the task:
### Input:
Returns a generator over the (callSet, nextPageToken) pairs defined
by the specified request.
### Response:
def callSetsGenerator(self, request):
"""
Returns a generator over the (callSet, nextPageToken) pairs defined
... |
def _get_attributes(self):
"""Return a generator for instance and class attribute.
.. code-block:: python3
for instance_attribute, class_attribute in self._get_attributes():
print("Instance Attribute: {}".format(instance_attribute))
print("Class Attribute: {... | Return a generator for instance and class attribute.
.. code-block:: python3
for instance_attribute, class_attribute in self._get_attributes():
print("Instance Attribute: {}".format(instance_attribute))
print("Class Attribute: {}".format(class_attribute))
R... | Below is the the instruction that describes the task:
### Input:
Return a generator for instance and class attribute.
.. code-block:: python3
for instance_attribute, class_attribute in self._get_attributes():
print("Instance Attribute: {}".format(instance_attribute))
... |
def init_file(self, filename, lines, expected, line_offset):
"""Signal a new file."""
self._deferred_print = []
return super(StandardReport, self).init_file(
filename, lines, expected, line_offset) | Signal a new file. | Below is the the instruction that describes the task:
### Input:
Signal a new file.
### Response:
def init_file(self, filename, lines, expected, line_offset):
"""Signal a new file."""
self._deferred_print = []
return super(StandardReport, self).init_file(
filename, lines, expect... |
def load_key(pubkey):
"""Load public RSA key, with work-around for keys using
incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
"""
try:
return load_pem_public_key(pubkey.encode(), default_b... | Load public RSA key, with work-around for keys using
incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ | Below is the the instruction that describes the task:
### Input:
Load public RSA key, with work-around for keys using
incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
### Response:
def load_key(pubkey):
... |
def average_series(self, *args, **kwargs) -> InfoArray:
"""Average the actual time series of the |Variable| object for all
time points.
Method |IOSequence.average_series| works similarly as method
|Variable.average_values| of class |Variable|, from which we
borrow some examples.... | Average the actual time series of the |Variable| object for all
time points.
Method |IOSequence.average_series| works similarly as method
|Variable.average_values| of class |Variable|, from which we
borrow some examples. However, firstly, we have to prepare a
|Timegrids| object ... | Below is the the instruction that describes the task:
### Input:
Average the actual time series of the |Variable| object for all
time points.
Method |IOSequence.average_series| works similarly as method
|Variable.average_values| of class |Variable|, from which we
borrow some example... |
def locked_delete(self):
"""Delete credentials from the SQLAlchemy datastore."""
filters = {self.key_name: self.key_value}
self.session.query(self.model_class).filter_by(**filters).delete() | Delete credentials from the SQLAlchemy datastore. | Below is the the instruction that describes the task:
### Input:
Delete credentials from the SQLAlchemy datastore.
### Response:
def locked_delete(self):
"""Delete credentials from the SQLAlchemy datastore."""
filters = {self.key_name: self.key_value}
self.session.query(self.model_class).fi... |
def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"):
""" Displays postal address with localized fields """
country_prefix = "country"
prefix = request.POST.get('prefix', prefix)
if prefix:
country_prefix = prefix + '-country'
country_cod... | Displays postal address with localized fields | Below is the the instruction that describes the task:
### Input:
Displays postal address with localized fields
### Response:
def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"):
""" Displays postal address with localized fields """
country_prefix = "country"
... |
def company_business_id(self):
"""
Returns Finnish company Business Identity Code (y-tunnus).
Format is 8 digits - e.g. FI99999999,[8] last digit is a check
digit utilizing MOD 11-2. The first digit is zero for some old
organizations. This function provides current codes starting... | Returns Finnish company Business Identity Code (y-tunnus).
Format is 8 digits - e.g. FI99999999,[8] last digit is a check
digit utilizing MOD 11-2. The first digit is zero for some old
organizations. This function provides current codes starting with
non-zero. | Below is the the instruction that describes the task:
### Input:
Returns Finnish company Business Identity Code (y-tunnus).
Format is 8 digits - e.g. FI99999999,[8] last digit is a check
digit utilizing MOD 11-2. The first digit is zero for some old
organizations. This function provides curr... |
def to_export(export):
"""Serializes export to id string
:param export: object to serialize
:return: string id
"""
from sevenbridges.models.storage_export import Export
if not export:
raise SbgError('Export is required!')
elif isinstance(export, Export... | Serializes export to id string
:param export: object to serialize
:return: string id | Below is the the instruction that describes the task:
### Input:
Serializes export to id string
:param export: object to serialize
:return: string id
### Response:
def to_export(export):
"""Serializes export to id string
:param export: object to serialize
:return: string id
... |
def from_dict(cls, d):
"""
As in :Class: `pymatgen.core.Molecule` except
restoring graphs using `from_dict_of_dicts`
from NetworkX to restore graph information.
"""
m = Molecule.from_dict(d['molecule'])
return cls(m, d['graphs']) | As in :Class: `pymatgen.core.Molecule` except
restoring graphs using `from_dict_of_dicts`
from NetworkX to restore graph information. | Below is the the instruction that describes the task:
### Input:
As in :Class: `pymatgen.core.Molecule` except
restoring graphs using `from_dict_of_dicts`
from NetworkX to restore graph information.
### Response:
def from_dict(cls, d):
"""
As in :Class: `pymatgen.core.Molecule` exce... |
def nnz_obs_names(self):
"""get the non-zero weight observation names
Returns
-------
nnz_obs_names : list
a list of non-zero weighted observation names
"""
# nz_names = []
# for w,n in zip(self.observation_data.weight,
# self.... | get the non-zero weight observation names
Returns
-------
nnz_obs_names : list
a list of non-zero weighted observation names | Below is the the instruction that describes the task:
### Input:
get the non-zero weight observation names
Returns
-------
nnz_obs_names : list
a list of non-zero weighted observation names
### Response:
def nnz_obs_names(self):
"""get the non-zero weight observation na... |
def get_group_policy_document(group_name, policy_name, client=None, **kwargs):
"""Fetches the specific IAM group inline-policy document."""
return client.get_group_policy(GroupName=group_name, PolicyName=policy_name, **kwargs)['PolicyDocument'] | Fetches the specific IAM group inline-policy document. | Below is the the instruction that describes the task:
### Input:
Fetches the specific IAM group inline-policy document.
### Response:
def get_group_policy_document(group_name, policy_name, client=None, **kwargs):
"""Fetches the specific IAM group inline-policy document."""
return client.get_group_policy(Gr... |
def get(self, name, section=None, fallback=False):
"""
Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if ... | Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if you want to avoid providing section param
:type name: str.
... | Below is the the instruction that describes the task:
### Input:
Returns a previously registered preference
:param section: The section name under which the preference is registered
:type section: str.
:param name: The name of the preference. You can use dotted notation 'section.name' if yo... |
def sitemap_check(url):
"""
Sitemap-Crawler are supported by every site which have a
Sitemap set in the robots.txt.
:param str url: the url to work on
:return bool: Determines if Sitemap is set in the site's robots.txt
"""
response = urllib2.urlopen(UrlExtractor.... | Sitemap-Crawler are supported by every site which have a
Sitemap set in the robots.txt.
:param str url: the url to work on
:return bool: Determines if Sitemap is set in the site's robots.txt | Below is the the instruction that describes the task:
### Input:
Sitemap-Crawler are supported by every site which have a
Sitemap set in the robots.txt.
:param str url: the url to work on
:return bool: Determines if Sitemap is set in the site's robots.txt
### Response:
def sitemap_check(ur... |
def lambda_handler(event, context):
"""Run the script."""
body = event.get('body', dict())
events = body.get('events', list())
source_ip = str(event.get('source_ip', ''))
if len(events) == 0:
return {'success': False, 'message': "No events sent in"}
status = process_events(events, source... | Run the script. | Below is the the instruction that describes the task:
### Input:
Run the script.
### Response:
def lambda_handler(event, context):
"""Run the script."""
body = event.get('body', dict())
events = body.get('events', list())
source_ip = str(event.get('source_ip', ''))
if len(events) == 0:
... |
def get_gradebook_columns_by_gradebooks(self, gradebook_ids):
"""Gets the list of gradebook columns corresponding to a list of ``Gradebooks``.
arg: gradebook_ids (osid.id.IdList): list of gradebook
``Ids``
return: (osid.grading.GradebookColumnList) - list of gradebook
... | Gets the list of gradebook columns corresponding to a list of ``Gradebooks``.
arg: gradebook_ids (osid.id.IdList): list of gradebook
``Ids``
return: (osid.grading.GradebookColumnList) - list of gradebook
columns
raise: NullArgument - ``gradebook_ids`` is ``nu... | Below is the the instruction that describes the task:
### Input:
Gets the list of gradebook columns corresponding to a list of ``Gradebooks``.
arg: gradebook_ids (osid.id.IdList): list of gradebook
``Ids``
return: (osid.grading.GradebookColumnList) - list of gradebook
... |
def make_list(obj, cast=True):
"""
Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list.
"""
if isinstance(obj, list):
return list(obj)
elif is_lazy_iterable... | Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list. | Below is the the instruction that describes the task:
### Input:
Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are
converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list.
### Response:
def make_list(obj, cast=True):
"""
Conv... |
def confirm_authorization_request(self):
"""When consumer confirm the authorization."""
server = self.server
scope = request.values.get('scope') or ''
scopes = scope.split()
credentials = dict(
client_id=request.values.get('client_id'),
redirect_uri=reques... | When consumer confirm the authorization. | Below is the the instruction that describes the task:
### Input:
When consumer confirm the authorization.
### Response:
def confirm_authorization_request(self):
"""When consumer confirm the authorization."""
server = self.server
scope = request.values.get('scope') or ''
scopes = sco... |
def _convert_rules_bubble(self, srules=''):
"""srules, a string containing the rules in bubble format will be
converted to the internal list of dictonary based rules.
'>>>': seperator : a rule has only certain amount of seperators
a rule is built like: >>>input>>>function>>>output>>>
... | srules, a string containing the rules in bubble format will be
converted to the internal list of dictonary based rules.
'>>>': seperator : a rule has only certain amount of seperators
a rule is built like: >>>input>>>function>>>output>>>
for example:
>>>i>>>adder>>>o>>>>
... | Below is the the instruction that describes the task:
### Input:
srules, a string containing the rules in bubble format will be
converted to the internal list of dictonary based rules.
'>>>': seperator : a rule has only certain amount of seperators
a rule is built like: >>>input>>>function>... |
def create_topics(self, new_topics, timeout_ms=None, validate_only=False):
"""Create new topics in the cluster.
:param new_topics: A list of NewTopic objects.
:param timeout_ms: Milliseconds to wait for new topics to be created
before the broker returns.
:param validate_only... | Create new topics in the cluster.
:param new_topics: A list of NewTopic objects.
:param timeout_ms: Milliseconds to wait for new topics to be created
before the broker returns.
:param validate_only: If True, don't actually create new topics.
Not supported by all versions... | Below is the the instruction that describes the task:
### Input:
Create new topics in the cluster.
:param new_topics: A list of NewTopic objects.
:param timeout_ms: Milliseconds to wait for new topics to be created
before the broker returns.
:param validate_only: If True, don't ... |
def format_datetime(date):
"""
Convert datetime to UTC ISO 8601
"""
# todo: test me
if date.utcoffset() is None:
return date.isoformat() + 'Z'
utc_offset_sec = date.utcoffset()
utc_date = date - utc_offset_sec
utc_date_without_offset = utc_date.replace(tzinfo=None)
return ut... | Convert datetime to UTC ISO 8601 | Below is the the instruction that describes the task:
### Input:
Convert datetime to UTC ISO 8601
### Response:
def format_datetime(date):
"""
Convert datetime to UTC ISO 8601
"""
# todo: test me
if date.utcoffset() is None:
return date.isoformat() + 'Z'
utc_offset_sec = date.utcof... |
def _no_context_variadic(node, variadic_name, variadic_type, variadics):
"""Verify if the given call node has variadic nodes without context
This is a workaround for handling cases of nested call functions
which don't have the specific call context at hand.
Variadic arguments (variable positional argum... | Verify if the given call node has variadic nodes without context
This is a workaround for handling cases of nested call functions
which don't have the specific call context at hand.
Variadic arguments (variable positional arguments and variable
keyword arguments) are inferred, inherently wrong, by astr... | Below is the the instruction that describes the task:
### Input:
Verify if the given call node has variadic nodes without context
This is a workaround for handling cases of nested call functions
which don't have the specific call context at hand.
Variadic arguments (variable positional arguments and va... |
def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool:
"""
Download file from Google Drive
:param item_id:
:param dir_name:
:return:
"""
service = self.__get_service()
request = service.files().get_media(fileId=item_id)
self.... | Download file from Google Drive
:param item_id:
:param dir_name:
:return: | Below is the the instruction that describes the task:
### Input:
Download file from Google Drive
:param item_id:
:param dir_name:
:return:
### Response:
def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool:
"""
Download file from Google Drive
... |
def get_masked_cnv_manifest(tcga_id):
"""Get manifest for masked TCGA copy-number variation data.
Params
------
tcga_id : str
The TCGA project ID.
download_file : str
The path of the download file.
Returns
-------
`pandas.DataFrame`
The manifest.
... | Get manifest for masked TCGA copy-number variation data.
Params
------
tcga_id : str
The TCGA project ID.
download_file : str
The path of the download file.
Returns
-------
`pandas.DataFrame`
The manifest. | Below is the the instruction that describes the task:
### Input:
Get manifest for masked TCGA copy-number variation data.
Params
------
tcga_id : str
The TCGA project ID.
download_file : str
The path of the download file.
Returns
-------
`pandas.DataFrame`
... |
def get_http_boot_url(self):
"""Request the http boot url from system in uefi boot mode.
:returns: URL for http boot
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the bios boot mode.
"""
if(self.... | Request the http boot url from system in uefi boot mode.
:returns: URL for http boot
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the bios boot mode. | Below is the the instruction that describes the task:
### Input:
Request the http boot url from system in uefi boot mode.
:returns: URL for http boot
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the bios boot mode.... |
def solar_zenith(self, dateandtime, latitude, longitude):
"""Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latit... | Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:par... | Below is the the instruction that describes the task:
### Input:
Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latit... |
def getWmAllowedActions(self, win, str=False):
"""
Get the list of allowed actions for the given window (property
_NET_WM_ALLOWED_ACTIONS).
:param win: the window object
:param str: True to get a list of string allowed actions instead of int
:return: list of (int|str)
... | Get the list of allowed actions for the given window (property
_NET_WM_ALLOWED_ACTIONS).
:param win: the window object
:param str: True to get a list of string allowed actions instead of int
:return: list of (int|str) | Below is the the instruction that describes the task:
### Input:
Get the list of allowed actions for the given window (property
_NET_WM_ALLOWED_ACTIONS).
:param win: the window object
:param str: True to get a list of string allowed actions instead of int
:return: list of (int|str)
... |
def generate_scale_free_graph(steps, growth_num, self_loops=False, multi_edges=False):
'''
Generates and returns a :py:class:`~altgraph.Graph.Graph` instance that will have *steps* \* *growth_num* nodes
and a scale free (powerlaw) connectivity. Starting with a fully connected graph with *growth_num* nodes
... | Generates and returns a :py:class:`~altgraph.Graph.Graph` instance that will have *steps* \* *growth_num* nodes
and a scale free (powerlaw) connectivity. Starting with a fully connected graph with *growth_num* nodes
at every step *growth_num* nodes are added to the graph and are connected to existing nodes with... | Below is the the instruction that describes the task:
### Input:
Generates and returns a :py:class:`~altgraph.Graph.Graph` instance that will have *steps* \* *growth_num* nodes
and a scale free (powerlaw) connectivity. Starting with a fully connected graph with *growth_num* nodes
at every step *growth_num* ... |
def _finalize_job(cls, mapreduce_spec, mapreduce_state):
"""Finalize job execution.
Invokes done callback and save mapreduce state in a transaction,
and schedule necessary clean ups. This method is idempotent.
Args:
mapreduce_spec: an instance of MapreduceSpec
mapreduce_state: an instance ... | Finalize job execution.
Invokes done callback and save mapreduce state in a transaction,
and schedule necessary clean ups. This method is idempotent.
Args:
mapreduce_spec: an instance of MapreduceSpec
mapreduce_state: an instance of MapreduceState | Below is the the instruction that describes the task:
### Input:
Finalize job execution.
Invokes done callback and save mapreduce state in a transaction,
and schedule necessary clean ups. This method is idempotent.
Args:
mapreduce_spec: an instance of MapreduceSpec
mapreduce_state: an inst... |
def redirect(cls, request, response):
"""Redirect to the canonical URI for this resource."""
if cls.meta.legacy_redirect:
if request.method in ('GET', 'HEAD',):
# A SAFE request is allowed to redirect using a 301
response.status = http.client.MOVED_PERMANENTLY... | Redirect to the canonical URI for this resource. | Below is the the instruction that describes the task:
### Input:
Redirect to the canonical URI for this resource.
### Response:
def redirect(cls, request, response):
"""Redirect to the canonical URI for this resource."""
if cls.meta.legacy_redirect:
if request.method in ('GET', 'HEAD',)... |
def image(self, height=1, module_width=1, add_quiet_zone=True):
"""Get the barcode as PIL.Image.
By default the image is one pixel high and the number of modules pixels wide, with 10 empty modules added to
each side to act as the quiet zone. The size can be modified by setting height and module... | Get the barcode as PIL.Image.
By default the image is one pixel high and the number of modules pixels wide, with 10 empty modules added to
each side to act as the quiet zone. The size can be modified by setting height and module_width, but if used in
a web page it might be a good idea to do the... | Below is the the instruction that describes the task:
### Input:
Get the barcode as PIL.Image.
By default the image is one pixel high and the number of modules pixels wide, with 10 empty modules added to
each side to act as the quiet zone. The size can be modified by setting height and module_width... |
def plot_places(self):
'''Plot places (in the parameter space) of all the generated artifacts
and the artifacts accepted to the domain.
'''
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
title = "Agent places, artifacts and env artifacts ({} env artifacts)"... | Plot places (in the parameter space) of all the generated artifacts
and the artifacts accepted to the domain. | Below is the the instruction that describes the task:
### Input:
Plot places (in the parameter space) of all the generated artifacts
and the artifacts accepted to the domain.
### Response:
def plot_places(self):
'''Plot places (in the parameter space) of all the generated artifacts
and the ... |
def _setup_rpc(self):
"""Setup the RPC client for the current agent."""
self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN)
self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN)
self._client = n_rpc.get_client(self.target)
self._consumers.extend([
[topics... | Setup the RPC client for the current agent. | Below is the the instruction that describes the task:
### Input:
Setup the RPC client for the current agent.
### Response:
def _setup_rpc(self):
"""Setup the RPC client for the current agent."""
self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN)
self._state_rpc = agent_rpc.PluginReportSt... |
async def find_person(self, query):
"""Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches.
"""
url = self.url_builder(
'search/person',
dict(),
... | Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches. | Below is the the instruction that describes the task:
### Input:
Retrieve person data by search query.
Arguments:
query (:py:class:`str`): Query to search for.
Returns:
:py:class:`list`: Possible matches.
### Response:
async def find_person(self, query):
"""Retrieve pe... |
def set_list_attribute(self, other, trigger_klass, property_name):
"""Used to set guard the setting of a list attribute, ensuring the same element is not added twice."""
# Check property exists
if isinstance(other, trigger_klass):
if not hasattr(self, property_name):
... | Used to set guard the setting of a list attribute, ensuring the same element is not added twice. | Below is the the instruction that describes the task:
### Input:
Used to set guard the setting of a list attribute, ensuring the same element is not added twice.
### Response:
def set_list_attribute(self, other, trigger_klass, property_name):
"""Used to set guard the setting of a list attribute, ensuring t... |
def load_image(fname):
""" read an image from file - PIL doesnt close nicely """
with open(fname, "rb") as f:
i = Image.open(fname)
#i.load()
return i | read an image from file - PIL doesnt close nicely | Below is the the instruction that describes the task:
### Input:
read an image from file - PIL doesnt close nicely
### Response:
def load_image(fname):
""" read an image from file - PIL doesnt close nicely """
with open(fname, "rb") as f:
i = Image.open(fname)
#i.load()
return i |
def h1(title, line=OVERLINE):
"""Prints bold text with line beneath it spanning width of terminal
"""
width = utils.term.width
printy(bold(title.center(width)).as_utf8)
printy(bold((line * width)[:width]).as_utf8) | Prints bold text with line beneath it spanning width of terminal | Below is the the instruction that describes the task:
### Input:
Prints bold text with line beneath it spanning width of terminal
### Response:
def h1(title, line=OVERLINE):
"""Prints bold text with line beneath it spanning width of terminal
"""
width = utils.term.width
printy(bold(title.center(wid... |
def flatten_if(cond: Callable[[Union[T, ActualIterable[T]]], bool]):
"""
>>> from Redy.Collections import Traversal, Flow
>>> lst: Iterable[int] = [[1, 2, 3]]
>>> x = Flow(lst)[Traversal.flatten_if(lambda _: isinstance(_, list))]
>>> assert isinstance(x.unbox, Generator) and list(x.unbox) == [1, 2, ... | >>> from Redy.Collections import Traversal, Flow
>>> lst: Iterable[int] = [[1, 2, 3]]
>>> x = Flow(lst)[Traversal.flatten_if(lambda _: isinstance(_, list))]
>>> assert isinstance(x.unbox, Generator) and list(x.unbox) == [1, 2, 3] | Below is the the instruction that describes the task:
### Input:
>>> from Redy.Collections import Traversal, Flow
>>> lst: Iterable[int] = [[1, 2, 3]]
>>> x = Flow(lst)[Traversal.flatten_if(lambda _: isinstance(_, list))]
>>> assert isinstance(x.unbox, Generator) and list(x.unbox) == [1, 2, 3]
### Respo... |
def create_thumb(self):
"""Create the thumbnail for html output"""
thumbnail_figure = self.copy_thumbnail_figure()
if thumbnail_figure is not None:
if isinstance(thumbnail_figure, six.string_types):
pic = thumbnail_figure
else:
pic = self.p... | Create the thumbnail for html output | Below is the the instruction that describes the task:
### Input:
Create the thumbnail for html output
### Response:
def create_thumb(self):
"""Create the thumbnail for html output"""
thumbnail_figure = self.copy_thumbnail_figure()
if thumbnail_figure is not None:
if isinstance(t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.