code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
for lim in self.limits.values():... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. | Below is the the instruction that describes the task:
### Input:
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
### Response:
def find_usage(self):
"""
Determine the current usage for each limi... |
def upload_by_gemfury(self):
"""
upload to gemfury
:return:
"""
check_call_no_output([
'{}'.format(self.python),
'setup.py',
'sdist',
])
filename = self.get_package_filename()
# The command line is the one recommended by... | upload to gemfury
:return: | Below is the the instruction that describes the task:
### Input:
upload to gemfury
:return:
### Response:
def upload_by_gemfury(self):
"""
upload to gemfury
:return:
"""
check_call_no_output([
'{}'.format(self.python),
'setup.py',
... |
def ToBitmap(self, x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> Bitmap:
"""
Capture control to a Bitmap object.
x, y: int, the point in control's internal position(from 0,0).
width, height: int, image's width and height from x, y, use 0 for entire area.
... | Capture control to a Bitmap object.
x, y: int, the point in control's internal position(from 0,0).
width, height: int, image's width and height from x, y, use 0 for entire area.
If width(or height) < 0, image size will be control's width(or height) - width(or height). | Below is the the instruction that describes the task:
### Input:
Capture control to a Bitmap object.
x, y: int, the point in control's internal position(from 0,0).
width, height: int, image's width and height from x, y, use 0 for entire area.
If width(or height) < 0, image siz... |
def _generate_password():
"""Create a random password
The password is made by taking a uuid and passing it though sha1sum.
We may change this in future to gain more entropy.
This is based on the tripleo command os-make-password
"""
uuid_str = six.text_type(uuid.uuid4()).encode("UTF-8")
ret... | Create a random password
The password is made by taking a uuid and passing it though sha1sum.
We may change this in future to gain more entropy.
This is based on the tripleo command os-make-password | Below is the the instruction that describes the task:
### Input:
Create a random password
The password is made by taking a uuid and passing it though sha1sum.
We may change this in future to gain more entropy.
This is based on the tripleo command os-make-password
### Response:
def _generate_password(... |
def boost(self, dtrain, grad, hess):
"""
Boost the booster for one iteration, with customized gradient statistics.
Parameters
----------
dtrain : DMatrix
The training DMatrix.
grad : list
The first order of gradient.
hess : list
... | Boost the booster for one iteration, with customized gradient statistics.
Parameters
----------
dtrain : DMatrix
The training DMatrix.
grad : list
The first order of gradient.
hess : list
The second order of gradient. | Below is the the instruction that describes the task:
### Input:
Boost the booster for one iteration, with customized gradient statistics.
Parameters
----------
dtrain : DMatrix
The training DMatrix.
grad : list
The first order of gradient.
hess : lis... |
def get_v_total_stress_at_depth(self, z):
"""
Determine the vertical total stress at depth z, where z can be a number or an array of numbers.
"""
if not hasattr(z, "__len__"):
return self.one_vertical_total_stress(z)
else:
sigma_v_effs = []
fo... | Determine the vertical total stress at depth z, where z can be a number or an array of numbers. | Below is the the instruction that describes the task:
### Input:
Determine the vertical total stress at depth z, where z can be a number or an array of numbers.
### Response:
def get_v_total_stress_at_depth(self, z):
"""
Determine the vertical total stress at depth z, where z can be a number or an ... |
def handle_fractal():
"""Get fractal coordinates from query string, call mandelbrot to generate image.
Returns:
The image, wrapped in an HTML response.
"""
if check_etag():
return flask.make_response(), 304
level = int(flask.request.args.get("l", "0"))
x = float(int(flask.requ... | Get fractal coordinates from query string, call mandelbrot to generate image.
Returns:
The image, wrapped in an HTML response. | Below is the the instruction that describes the task:
### Input:
Get fractal coordinates from query string, call mandelbrot to generate image.
Returns:
The image, wrapped in an HTML response.
### Response:
def handle_fractal():
"""Get fractal coordinates from query string, call mandelbrot to gener... |
def iter_(obj):
"""A custom replacement for iter(), dispatching a few custom picklable
iterators for known types.
"""
if six.PY2:
file_types = file, # noqa
if six.PY3:
file_types = io.IOBase,
dict_items = {}.items().__class__
dict_values = {}.values().__class__
... | A custom replacement for iter(), dispatching a few custom picklable
iterators for known types. | Below is the the instruction that describes the task:
### Input:
A custom replacement for iter(), dispatching a few custom picklable
iterators for known types.
### Response:
def iter_(obj):
"""A custom replacement for iter(), dispatching a few custom picklable
iterators for known types.
"""
if ... |
def check_and_adjust_sighandlers(self):
"""Check to see if any of the signal handlers we are interested in have
changed or is not initially set. Change any that are not right. """
for signame in list(self.sigs.keys()):
if not self.check_and_adjust_sighandler(signame, self.sigs):
... | Check to see if any of the signal handlers we are interested in have
changed or is not initially set. Change any that are not right. | Below is the the instruction that describes the task:
### Input:
Check to see if any of the signal handlers we are interested in have
changed or is not initially set. Change any that are not right.
### Response:
def check_and_adjust_sighandlers(self):
"""Check to see if any of the signal handlers w... |
def logging_syslog_server_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras")
syslog_server = ET.SubElement(logging, "syslog-server")
syslogip_key = ET.SubEleme... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def logging_syslog_server_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-... |
def get_organism(self):
"""Select Enrichr organism from below:
Human & Mouse: H. sapiens & M. musculus
Fly: D. melanogaster
Yeast: S. cerevisiae
Worm: C. elegans
Fish: D. rerio
"""
organism = {'default': ['', 'hs', 'mm', 'human','mouse',
... | Select Enrichr organism from below:
Human & Mouse: H. sapiens & M. musculus
Fly: D. melanogaster
Yeast: S. cerevisiae
Worm: C. elegans
Fish: D. rerio | Below is the the instruction that describes the task:
### Input:
Select Enrichr organism from below:
Human & Mouse: H. sapiens & M. musculus
Fly: D. melanogaster
Yeast: S. cerevisiae
Worm: C. elegans
Fish: D. rerio
### Response:
def get_organism(self):
... |
def cpd3_convolution(inp, outmaps, kernel, r,
pad=None, stride=None, dilation=None,
oik_init=None, b_init=None,
base_axis=1, fix_parameters=False, rng=None, with_bias=True,
max_iter=500, stopping_criterion=1e-5, lambda_reg=0.0):
"""... | CP convolution is a low rank approximation of a convolution layer. A 3D tensor containing the parameter is built by collapsing the N-D kernels into 1D, then the tensor is decomposed into three matrices. The decomposed layer can be seen as linear combinations of the input feature maps to :math:`{R}` feature maps followe... | Below is the the instruction that describes the task:
### Input:
CP convolution is a low rank approximation of a convolution layer. A 3D tensor containing the parameter is built by collapsing the N-D kernels into 1D, then the tensor is decomposed into three matrices. The decomposed layer can be seen as linear combi... |
def edit( plugins, parent = None, default = None, modal = True ):
"""
Prompts the user to edit the config settings for the inputed config \
plugins.
:param plugins | [<XConfigPlugin>, ..]
parent | <QWidget>
default | <XConfigPlugin> ... | Prompts the user to edit the config settings for the inputed config \
plugins.
:param plugins | [<XConfigPlugin>, ..]
parent | <QWidget>
default | <XConfigPlugin> || None
:return <bool> success | Below is the the instruction that describes the task:
### Input:
Prompts the user to edit the config settings for the inputed config \
plugins.
:param plugins | [<XConfigPlugin>, ..]
parent | <QWidget>
default | <XConfigPlugin> || None
... |
def get_followers(self, first_user_id=None):
"""
获取关注者列表
详情请参考 http://mp.weixin.qq.com/wiki/3/17e6919a39c1c53555185907acf70093.html
:param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取
:return: 返回的 JSON 数据包
"""
params = dict()
if first_user_id:
par... | 获取关注者列表
详情请参考 http://mp.weixin.qq.com/wiki/3/17e6919a39c1c53555185907acf70093.html
:param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
获取关注者列表
详情请参考 http://mp.weixin.qq.com/wiki/3/17e6919a39c1c53555185907acf70093.html
:param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取
:return: 返回的 JSON 数据包
### Response:
def get_followers(self, first_user_id=None):
"""
... |
def _init_qualifier_decl(qualifier_decl, qual_repo):
"""
Initialize the flavors of a qualifier declaration if they are not
already set.
"""
assert qualifier_decl.name not in qual_repo
if qualifier_decl.tosubclass is None:
qualifier_decl.tosubclass = True
... | Initialize the flavors of a qualifier declaration if they are not
already set. | Below is the the instruction that describes the task:
### Input:
Initialize the flavors of a qualifier declaration if they are not
already set.
### Response:
def _init_qualifier_decl(qualifier_decl, qual_repo):
"""
Initialize the flavors of a qualifier declaration if they are not
al... |
def select(cls, dataset, selection_mask=None, **selection):
"""
Apply a selection to the data.
"""
import iris
constraint = cls.select_to_constraint(dataset, selection)
pre_dim_coords = [c.name() for c in dataset.data.dim_coords]
indexed = cls.indexed(dataset, sel... | Apply a selection to the data. | Below is the the instruction that describes the task:
### Input:
Apply a selection to the data.
### Response:
def select(cls, dataset, selection_mask=None, **selection):
"""
Apply a selection to the data.
"""
import iris
constraint = cls.select_to_constraint(dataset, selecti... |
def list_recipes(full=False):
"""Method that iterates over all available recipes and prints their
information to the standard output
Parameters
----------
full : bool
If true, it will provide the pipeline string along with the recipe name
"""
logger.info(colored_print(
"\n=... | Method that iterates over all available recipes and prints their
information to the standard output
Parameters
----------
full : bool
If true, it will provide the pipeline string along with the recipe name | Below is the the instruction that describes the task:
### Input:
Method that iterates over all available recipes and prints their
information to the standard output
Parameters
----------
full : bool
If true, it will provide the pipeline string along with the recipe name
### Response:
def l... |
def with_text(self, text, markdown=None):
'''Set text content.
:param text: text content.
:param markdown: is markdown? Defaults to ``False``.
'''
self._text = text
self._markdown = markdown or False
return self | Set text content.
:param text: text content.
:param markdown: is markdown? Defaults to ``False``. | Below is the the instruction that describes the task:
### Input:
Set text content.
:param text: text content.
:param markdown: is markdown? Defaults to ``False``.
### Response:
def with_text(self, text, markdown=None):
'''Set text content.
:param text: text content.
:param... |
def compute_wed(self):
"""
Computes weight error derivative for all connections in
self.connections starting with the last connection.
"""
if len(self.cacheConnections) != 0:
changeConnections = self.cacheConnections
else:
changeConnections = self.... | Computes weight error derivative for all connections in
self.connections starting with the last connection. | Below is the the instruction that describes the task:
### Input:
Computes weight error derivative for all connections in
self.connections starting with the last connection.
### Response:
def compute_wed(self):
"""
Computes weight error derivative for all connections in
self.connecti... |
def p_statement_if(p):
'''statement : IF LPAREN expr RPAREN statement elseif_list else_single
| IF LPAREN expr RPAREN COLON inner_statement_list new_elseif_list new_else_single ENDIF SEMI'''
if len(p) == 8:
p[0] = ast.If(p[3], p[5], p[6], p[7], lineno=p.lineno(1))
else:
p[0]... | statement : IF LPAREN expr RPAREN statement elseif_list else_single
| IF LPAREN expr RPAREN COLON inner_statement_list new_elseif_list new_else_single ENDIF SEMI | Below is the the instruction that describes the task:
### Input:
statement : IF LPAREN expr RPAREN statement elseif_list else_single
| IF LPAREN expr RPAREN COLON inner_statement_list new_elseif_list new_else_single ENDIF SEMI
### Response:
def p_statement_if(p):
'''statement : IF LPAREN expr ... |
def _entries_sorted(self):
""":return: list of entries, in a sorted fashion, first by path, then by stage"""
return sorted(self.entries.values(), key=lambda e: (e.path, e.stage)) | :return: list of entries, in a sorted fashion, first by path, then by stage | Below is the the instruction that describes the task:
### Input:
:return: list of entries, in a sorted fashion, first by path, then by stage
### Response:
def _entries_sorted(self):
""":return: list of entries, in a sorted fashion, first by path, then by stage"""
return sorted(self.entries.values()... |
def summary(self):
"""Returns the docstring summary for the code element if it exists."""
if self._summary is None:
self._summary = "No summary for element."
for doc in self.docstring:
if doc.doctype == "summary":
self._summary = doc.contents
... | Returns the docstring summary for the code element if it exists. | Below is the the instruction that describes the task:
### Input:
Returns the docstring summary for the code element if it exists.
### Response:
def summary(self):
"""Returns the docstring summary for the code element if it exists."""
if self._summary is None:
self._summary = "No summary... |
def stats_advanced(self, kind='R', summary=False):
"""Returns a DataFrame of advanced stats."""
return self._get_stats_table('advanced', kind=kind, summary=summary) | Returns a DataFrame of advanced stats. | Below is the the instruction that describes the task:
### Input:
Returns a DataFrame of advanced stats.
### Response:
def stats_advanced(self, kind='R', summary=False):
"""Returns a DataFrame of advanced stats."""
return self._get_stats_table('advanced', kind=kind, summary=summary) |
def camera_disable(self, camera_id, **kwargs):
"""Disable camera."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'Disable',
'version': 9,
'idList': camera_id,
}, **kwargs)
... | Disable camera. | Below is the the instruction that describes the task:
### Input:
Disable camera.
### Response:
def camera_disable(self, camera_id, **kwargs):
"""Disable camera."""
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'met... |
def filter(self, record):
"""
Filter record
:param record: Record to filter
:return:
"""
def modify(value):
"""
Modify logged record, truncating it to max length and logging remaining length
:param value: Record to modify
:... | Filter record
:param record: Record to filter
:return: | Below is the the instruction that describes the task:
### Input:
Filter record
:param record: Record to filter
:return:
### Response:
def filter(self, record):
"""
Filter record
:param record: Record to filter
:return:
"""
def modify(value):
... |
def _normalize_merge_diff(diff):
"""Make compare_config() for merge look similar to replace config diff."""
new_diff = []
for line in diff.splitlines():
# Filter blank lines and prepend +sign
if line.strip():
new_diff.append("+" + line)
if new_diff... | Make compare_config() for merge look similar to replace config diff. | Below is the the instruction that describes the task:
### Input:
Make compare_config() for merge look similar to replace config diff.
### Response:
def _normalize_merge_diff(diff):
"""Make compare_config() for merge look similar to replace config diff."""
new_diff = []
for line in diff.spli... |
def html_table(data, header=True, limit=None, withtype=False):
"""
Return a double iterable as an HTML table
@param data (iterable): the data to format
@param header (bool): if the first row is a header row
@param limit (int): maximum number of rows to render (excluding header)
@param wi... | Return a double iterable as an HTML table
@param data (iterable): the data to format
@param header (bool): if the first row is a header row
@param limit (int): maximum number of rows to render (excluding header)
@param withtype (bool): if columns are to have an alternating CSS class
(eve... | Below is the the instruction that describes the task:
### Input:
Return a double iterable as an HTML table
@param data (iterable): the data to format
@param header (bool): if the first row is a header row
@param limit (int): maximum number of rows to render (excluding header)
@param withtype... |
def sanity_check_insdcio(handle, id_marker, fake_id_line):
"""Sanity check for insdcio style files"""
found_id = False
found_end_marker = False
for line in handle:
line = line.strip()
if not line:
continue
if line.startswith(id_marker):
found_id = True
... | Sanity check for insdcio style files | Below is the the instruction that describes the task:
### Input:
Sanity check for insdcio style files
### Response:
def sanity_check_insdcio(handle, id_marker, fake_id_line):
"""Sanity check for insdcio style files"""
found_id = False
found_end_marker = False
for line in handle:
line = line... |
def _parse_attrs(elem, container=dict, **options):
"""
:param elem: ET Element object has attributes (elem.attrib)
:param container: callble to make a container object
:return: Parsed value or value itself depends on 'ac_parse_value'
"""
adic = dict((_tweak_ns(a, **options), v) for a, v in elem.... | :param elem: ET Element object has attributes (elem.attrib)
:param container: callble to make a container object
:return: Parsed value or value itself depends on 'ac_parse_value' | Below is the the instruction that describes the task:
### Input:
:param elem: ET Element object has attributes (elem.attrib)
:param container: callble to make a container object
:return: Parsed value or value itself depends on 'ac_parse_value'
### Response:
def _parse_attrs(elem, container=dict, **options)... |
def webhooks(self):
"""Instance depends on the API version:
* 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.operations.WebhooksOperations>`
* 2018-02-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.Webhoo... | Instance depends on the API version:
* 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.operations.WebhooksOperations>`
* 2018-02-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.WebhooksOperations>`
* 201... | Below is the the instruction that describes the task:
### Input:
Instance depends on the API version:
* 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.operations.WebhooksOperations>`
* 2018-02-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry... |
def any2mb(s):
"""Convert string or number to memory in megabytes."""
if is_string(s):
return int(Memory.from_string(s).to("Mb"))
else:
return int(s) | Convert string or number to memory in megabytes. | Below is the the instruction that describes the task:
### Input:
Convert string or number to memory in megabytes.
### Response:
def any2mb(s):
"""Convert string or number to memory in megabytes."""
if is_string(s):
return int(Memory.from_string(s).to("Mb"))
else:
return int(s) |
def to_nested_php_args(data, prefix_key=None):
"""
This function will take either a dict or list and will recursively loop
through the values converting it into a format similar to a PHP array which
Ubersmith requires for the info portion of the API's order.create method.
"""
is_root = prefix_ke... | This function will take either a dict or list and will recursively loop
through the values converting it into a format similar to a PHP array which
Ubersmith requires for the info portion of the API's order.create method. | Below is the the instruction that describes the task:
### Input:
This function will take either a dict or list and will recursively loop
through the values converting it into a format similar to a PHP array which
Ubersmith requires for the info portion of the API's order.create method.
### Response:
def to... |
def _build_kernel_function_declaration(self, name='kernel'):
"""Build and return kernel function declaration"""
array_declarations, array_dimensions = self._build_array_declarations(with_init=False)
scalar_declarations = self._build_scalar_declarations(with_init=False)
const_declarations... | Build and return kernel function declaration | Below is the the instruction that describes the task:
### Input:
Build and return kernel function declaration
### Response:
def _build_kernel_function_declaration(self, name='kernel'):
"""Build and return kernel function declaration"""
array_declarations, array_dimensions = self._build_array_declar... |
def cli(ctx, hostname, username, password, config_dir, https):
"""Command-line interface for interacting with a WVA device"""
ctx.is_root = True
ctx.user_values_entered = False
ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir))
ctx.config = load_config(ctx)
ctx.hostname = hostname
... | Command-line interface for interacting with a WVA device | Below is the the instruction that describes the task:
### Input:
Command-line interface for interacting with a WVA device
### Response:
def cli(ctx, hostname, username, password, config_dir, https):
"""Command-line interface for interacting with a WVA device"""
ctx.is_root = True
ctx.user_values_entere... |
def image(self):
r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
... | r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
Additionaly, if self.no... | Below is the the instruction that describes the task:
### Input:
r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is... |
def _diffSchema(diskSchema, memorySchema):
"""
Format a schema mismatch for human consumption.
@param diskSchema: The on-disk schema.
@param memorySchema: The in-memory schema.
@rtype: L{bytes}
@return: A description of the schema differences.
"""
diskSchema = set(diskSchema)
memo... | Format a schema mismatch for human consumption.
@param diskSchema: The on-disk schema.
@param memorySchema: The in-memory schema.
@rtype: L{bytes}
@return: A description of the schema differences. | Below is the the instruction that describes the task:
### Input:
Format a schema mismatch for human consumption.
@param diskSchema: The on-disk schema.
@param memorySchema: The in-memory schema.
@rtype: L{bytes}
@return: A description of the schema differences.
### Response:
def _diffSchema(disk... |
def get_sigla(self, work):
"""Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str`
"""
return [os.path.splitext(os.path.basename(path))[0]
for path in glob.glob(os.path.join(self._path, work, ... | Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str` | Below is the the instruction that describes the task:
### Input:
Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str`
### Response:
def get_sigla(self, work):
"""Returns a list of all of the sigla for `work`.
:p... |
def _create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return Frame(body=body... | Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders. | Below is the the instruction that describes the task:
### Input:
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
### Response:
def _create_popup_window(title, body):
"""
Return the layout for a pop-up wi... |
def get_time_estimator(total):
"""Given a total amount of items to compute, return a function that,
if called every time an item is computed (or every step items are computed)
will give a time estimation for how long it will take to compute the whole
set of itmes. The function will return two values: th... | Given a total amount of items to compute, return a function that,
if called every time an item is computed (or every step items are computed)
will give a time estimation for how long it will take to compute the whole
set of itmes. The function will return two values: the first is the number
of seconds t... | Below is the the instruction that describes the task:
### Input:
Given a total amount of items to compute, return a function that,
if called every time an item is computed (or every step items are computed)
will give a time estimation for how long it will take to compute the whole
set of itmes. The func... |
def run(self, cell, is_full_fc=False, parse_fc=True):
"""Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed... | Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is ... | Below is the the instruction that describes the task:
### Input:
Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are rem... |
def event_handler(event_name):
"""
Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object that can be encoded as a J... | Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object that can be encoded as a JSON (dict, list, str, int,
bool, float ... | Below is the the instruction that describes the task:
### Input:
Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object ... |
def isatty(self): # nocover
"""
Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr.
"""
return (self.redirect is not None and
hasattr(self.redir... | Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr. | Below is the the instruction that describes the task:
### Input:
Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr.
### Response:
def isatty(self): # nocover
"""
Returns ... |
def vcfchunk(data, optim, sidx, chunk, full):
"""
Function called within make_vcf to run chunks on separate engines.
"""
## empty array to be filled before writing
## will not actually be optim*maxlen, extra needs to be trimmed
maxlen = data._hackersonly["max_fragment_length"] + 20
## get d... | Function called within make_vcf to run chunks on separate engines. | Below is the the instruction that describes the task:
### Input:
Function called within make_vcf to run chunks on separate engines.
### Response:
def vcfchunk(data, optim, sidx, chunk, full):
"""
Function called within make_vcf to run chunks on separate engines.
"""
## empty array to be filled befo... |
def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId =... | cancel historical data stream | Below is the the instruction that describes the task:
### Input:
cancel historical data stream
### Response:
def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(... |
def write_file(response, destination_folder, file_name):
"""
Write the response content in a file in the destination folder.
:param response: Response
:param destination_folder: Destination folder, string
:param file_name: File name, string
:return: bool
"""
... | Write the response content in a file in the destination folder.
:param response: Response
:param destination_folder: Destination folder, string
:param file_name: File name, string
:return: bool | Below is the the instruction that describes the task:
### Input:
Write the response content in a file in the destination folder.
:param response: Response
:param destination_folder: Destination folder, string
:param file_name: File name, string
:return: bool
### Response:
def write_... |
def query_orders(self, accounts, status='filled'):
"""查询订单
Arguments:
accounts {[type]} -- [description]
Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})
Returns:
[type] -- [description]
"""
try:
... | 查询订单
Arguments:
accounts {[type]} -- [description]
Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})
Returns:
[type] -- [description] | Below is the the instruction that describes the task:
### Input:
查询订单
Arguments:
accounts {[type]} -- [description]
Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})
Returns:
[type] -- [description]
### Response:
def query... |
def tox_configure(config):
"""Check for the presence of the added options."""
if 'TRAVIS' not in os.environ:
return
ini = config._cfg
# envlist
if 'TOXENV' not in os.environ and not config.option.env:
envlist = detect_envlist(ini)
undeclared = set(envlist) - set(config.envc... | Check for the presence of the added options. | Below is the the instruction that describes the task:
### Input:
Check for the presence of the added options.
### Response:
def tox_configure(config):
"""Check for the presence of the added options."""
if 'TRAVIS' not in os.environ:
return
ini = config._cfg
# envlist
if 'TOXENV' not i... |
def assign_type(mol, force_recalc=False):
""" PATTY [Bush et al. J. Inf. Comput. Sci 33 (1993) 756-762]
TODO: not yet implemented
1:cation 2:anion 3:donor 4:acceptor
5:polar 6:hydrophobe 7:others
"""
if "PATTY" in mol.descriptors and not force_recalc:
return
mol.require("Phys_charge... | PATTY [Bush et al. J. Inf. Comput. Sci 33 (1993) 756-762]
TODO: not yet implemented
1:cation 2:anion 3:donor 4:acceptor
5:polar 6:hydrophobe 7:others | Below is the the instruction that describes the task:
### Input:
PATTY [Bush et al. J. Inf. Comput. Sci 33 (1993) 756-762]
TODO: not yet implemented
1:cation 2:anion 3:donor 4:acceptor
5:polar 6:hydrophobe 7:others
### Response:
def assign_type(mol, force_recalc=False):
""" PATTY [Bush et al. J. I... |
def _process_axsettings(self, hist, lims, ticks):
"""
Get axis settings options including ticks, x- and y-labels
and limits.
"""
axis_settings = dict(zip(self.axis_settings, [None, None, (None if self.overlaid else ticks)]))
return axis_settings | Get axis settings options including ticks, x- and y-labels
and limits. | Below is the the instruction that describes the task:
### Input:
Get axis settings options including ticks, x- and y-labels
and limits.
### Response:
def _process_axsettings(self, hist, lims, ticks):
"""
Get axis settings options including ticks, x- and y-labels
and limits.
... |
def write_newick(rootnode,
features=None,
format=1,
format_root_node=True,
is_leaf_fn=None,
dist_formatter=None,
support_formatter=None,
name_formatter=None):
"""
Iteratively export a tree structure and returns its NHX
representation.
"""
newick = []
leaf = is_leaf_fn if... | Iteratively export a tree structure and returns its NHX
representation. | Below is the the instruction that describes the task:
### Input:
Iteratively export a tree structure and returns its NHX
representation.
### Response:
def write_newick(rootnode,
features=None,
format=1,
format_root_node=True,
is_leaf_fn=None,
dist_formatter=None,
support_formatter=None,
... |
def children(self):
"""
The list of child messages and actions sorted by task level, excluding the
start and end messages.
"""
return pvector(
sorted(self._children.values(), key=lambda m: m.task_level)) | The list of child messages and actions sorted by task level, excluding the
start and end messages. | Below is the the instruction that describes the task:
### Input:
The list of child messages and actions sorted by task level, excluding the
start and end messages.
### Response:
def children(self):
"""
The list of child messages and actions sorted by task level, excluding the
start ... |
def feat_segments_to_2dfmc_max(feat_segments, offset=4):
"""From a list of feature segments, return a list of 2D-Fourier Magnitude
Coefs using the maximum segment size as main size and zero pad the rest.
Parameters
----------
feat_segments: list
List of segments, one for each boundary inter... | From a list of feature segments, return a list of 2D-Fourier Magnitude
Coefs using the maximum segment size as main size and zero pad the rest.
Parameters
----------
feat_segments: list
List of segments, one for each boundary interval.
offset: int >= 0
Number of frames to ignore fro... | Below is the the instruction that describes the task:
### Input:
From a list of feature segments, return a list of 2D-Fourier Magnitude
Coefs using the maximum segment size as main size and zero pad the rest.
Parameters
----------
feat_segments: list
List of segments, one for each boundary ... |
def atanh(x, context=None):
"""
Return the inverse hyperbolic tangent of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_atanh,
(BigFloat._implicit_convert(x),),
context,
) | Return the inverse hyperbolic tangent of x. | Below is the the instruction that describes the task:
### Input:
Return the inverse hyperbolic tangent of x.
### Response:
def atanh(x, context=None):
"""
Return the inverse hyperbolic tangent of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_atanh,
(... |
def _GetArgsFromRequest(self, request, method_metadata, route_args):
"""Builds args struct out of HTTP request."""
format_mode = GetRequestFormatMode(request, method_metadata)
if request.method in ["GET", "HEAD"]:
if method_metadata.args_type:
unprocessed_request = request.args
if has... | Builds args struct out of HTTP request. | Below is the the instruction that describes the task:
### Input:
Builds args struct out of HTTP request.
### Response:
def _GetArgsFromRequest(self, request, method_metadata, route_args):
"""Builds args struct out of HTTP request."""
format_mode = GetRequestFormatMode(request, method_metadata)
if requ... |
def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDirection.OUTGOING:
return self.device
if self.direction == TrafficDirection.INCOMING:
return self.ifb_device
rais... | Return a device name that associated network communication direction. | Below is the the instruction that describes the task:
### Input:
Return a device name that associated network communication direction.
### Response:
def get_tc_device(self):
"""
Return a device name that associated network communication direction.
"""
if self.direction == TrafficDi... |
def probe_async(self, callback):
"""Send advertisements for all connected devices.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
succes... | Send advertisements for all connected devices.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
failure_reason: ... | Below is the the instruction that describes the task:
### Input:
Send advertisements for all connected devices.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
... |
def load_fixture(self, body, attachment_bodies={}):
'''
Loads the document into the database from json string. Fakes the
attachments if necessary.'''
doc = json.loads(body)
self._documents[doc['_id']] = doc
self._attachments[doc['_id']] = dict()
for name in doc.ge... | Loads the document into the database from json string. Fakes the
attachments if necessary. | Below is the the instruction that describes the task:
### Input:
Loads the document into the database from json string. Fakes the
attachments if necessary.
### Response:
def load_fixture(self, body, attachment_bodies={}):
'''
Loads the document into the database from json string. Fakes the
... |
def compute(self, config, budget, **kwargs):
"""
Simple example for a compute function
The loss is just a the config + some noise (that decreases with the budget)
For dramatization, the function can sleep for a given interval to emphasizes
the speed ups achievable with parallel ... | Simple example for a compute function
The loss is just a the config + some noise (that decreases with the budget)
For dramatization, the function can sleep for a given interval to emphasizes
the speed ups achievable with parallel workers.
Args:
config: dictionary containing... | Below is the the instruction that describes the task:
### Input:
Simple example for a compute function
The loss is just a the config + some noise (that decreases with the budget)
For dramatization, the function can sleep for a given interval to emphasizes
the speed ups achievable with paral... |
def count_mnemonic(self, mnemonic, uwis=uwis, alias=None):
"""
Counts the wells that have a given curve, given the mnemonic and an
alias dict.
"""
all_mnemonics = self.get_mnemonics([mnemonic], uwis=uwis, alias=alias)
return len(list(filter(None, utils.flatten_list(all_mn... | Counts the wells that have a given curve, given the mnemonic and an
alias dict. | Below is the the instruction that describes the task:
### Input:
Counts the wells that have a given curve, given the mnemonic and an
alias dict.
### Response:
def count_mnemonic(self, mnemonic, uwis=uwis, alias=None):
"""
Counts the wells that have a given curve, given the mnemonic and an
... |
def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
"""Return parsed JSON data.
.. versionadded:: 0.22
"""
return loads(self.data) | Return parsed JSON data.
.. versionadded:: 0.22 | Below is the the instruction that describes the task:
### Input:
Return parsed JSON data.
.. versionadded:: 0.22
### Response:
def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
"""Return parsed JSON data.
.. versionadded:: 0.22
"""
... |
def area_difference(item_a, time_a, item_b, time_b, max_value):
"""
RMS Difference in object areas.
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in ObjectMatcher
time_b: Time integer bein... | RMS Difference in object areas.
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in ObjectMatcher
time_b: Time integer being evaluated
max_value: Maximum distance value used as scaling value ... | Below is the the instruction that describes the task:
### Input:
RMS Difference in object areas.
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in ObjectMatcher
time_b: Time integer being evalu... |
def parent_tags(self):
"""Provides tags of all parent HTML elements."""
tags = set()
for addr in self._addresses:
if addr.attr == 'text':
tags.add(addr.element.tag)
tags.update(el.tag for el in addr.element.iterancestors())
tags.discard(HTMLFragm... | Provides tags of all parent HTML elements. | Below is the the instruction that describes the task:
### Input:
Provides tags of all parent HTML elements.
### Response:
def parent_tags(self):
"""Provides tags of all parent HTML elements."""
tags = set()
for addr in self._addresses:
if addr.attr == 'text':
ta... |
def initialize(self, emt_id, emt_pass):
"""Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
... | Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon registration
emt_pass (str): Token given by the server upon re... | Below is the the instruction that describes the task:
### Input:
Manual initialization of the interface attributes.
This is useful when the interface must be declare but initialized later
on with parsed configuration values.
Args:
emt_id (str): ID given by the server upon regis... |
def _get_qvm_based_on_real_device(name: str, device: Device,
noisy: bool, connection: ForestConnection = None,
qvm_type: str = 'qvm'):
"""
A qvm with a based on a real device.
This is the most realistic QVM.
:param name: The full name... | A qvm with a based on a real device.
This is the most realistic QVM.
:param name: The full name of this QVM
:param device: The device from :py:func:`get_lattice`.
:param noisy: Whether to construct a noisy quantum computer by using the device's
associated noise model.
:param connection: An... | Below is the the instruction that describes the task:
### Input:
A qvm with a based on a real device.
This is the most realistic QVM.
:param name: The full name of this QVM
:param device: The device from :py:func:`get_lattice`.
:param noisy: Whether to construct a noisy quantum computer by using t... |
def get_next_invalid_time_from_t(self, timestamp):
"""Get next invalid time for time range
:param timestamp: time we compute from
:type timestamp: int
:return: timestamp of the next invalid time (LOCAL TIME)
:rtype: int
"""
if not self.is_time_valid(timestamp):
... | Get next invalid time for time range
:param timestamp: time we compute from
:type timestamp: int
:return: timestamp of the next invalid time (LOCAL TIME)
:rtype: int | Below is the the instruction that describes the task:
### Input:
Get next invalid time for time range
:param timestamp: time we compute from
:type timestamp: int
:return: timestamp of the next invalid time (LOCAL TIME)
:rtype: int
### Response:
def get_next_invalid_time_from_t(self... |
def create_sequence_readers(sources: List[str], target: str,
vocab_sources: List[vocab.Vocab],
vocab_target: vocab.Vocab) -> Tuple[List[SequenceReader], SequenceReader]:
"""
Create source readers with EOS and target readers with BOS.
:param sources: T... | Create source readers with EOS and target readers with BOS.
:param sources: The file names of source data and factors.
:param target: The file name of the target data.
:param vocab_sources: The source vocabularies.
:param vocab_target: The target vocabularies.
:return: The source sequence readers a... | Below is the the instruction that describes the task:
### Input:
Create source readers with EOS and target readers with BOS.
:param sources: The file names of source data and factors.
:param target: The file name of the target data.
:param vocab_sources: The source vocabularies.
:param vocab_target... |
def Free(self):
'''
Frees the memory used by all of the dynamically allocated C arrays.
'''
if self.arrays._calloc:
_dbl_free(self.arrays._time)
_dbl_free(self.arrays._flux)
_dbl_free(self.arrays._bflx)
_dbl_free(self.arrays._M)
_dbl_free(self.arrays._E)
_dbl_fr... | Frees the memory used by all of the dynamically allocated C arrays. | Below is the the instruction that describes the task:
### Input:
Frees the memory used by all of the dynamically allocated C arrays.
### Response:
def Free(self):
'''
Frees the memory used by all of the dynamically allocated C arrays.
'''
if self.arrays._calloc:
_dbl_free(self.arrays._t... |
def _load(self, load_dict):
"""Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explored, the exploration range of a... | Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explored, the exploration range of arrays is reconstructed
as it wa... | Below is the the instruction that describes the task:
### Input:
Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explor... |
def Tm_depression_eutectic(Tm, Hm, x=None, M=None, MW=None):
r'''Returns the freezing point depression caused by a solute in a solvent.
Can use either the mole fraction of the solute or its molality and the
molecular weight of the solvent. Assumes ideal system behavior.
.. math::
\Delta T_m = \... | r'''Returns the freezing point depression caused by a solute in a solvent.
Can use either the mole fraction of the solute or its molality and the
molecular weight of the solvent. Assumes ideal system behavior.
.. math::
\Delta T_m = \frac{R T_m^2 x}{\Delta H_m}
\Delta T_m = \frac{R T_m^2 (... | Below is the the instruction that describes the task:
### Input:
r'''Returns the freezing point depression caused by a solute in a solvent.
Can use either the mole fraction of the solute or its molality and the
molecular weight of the solvent. Assumes ideal system behavior.
.. math::
\Delta T_m... |
def to_dict(self):
"""Transforms the object to a Python dictionary.
Note:
If an Input hasn't been signed yet, this method returns a
dictionary representation.
Returns:
dict: The Input as an alternative serialization format.
"""
... | Transforms the object to a Python dictionary.
Note:
If an Input hasn't been signed yet, this method returns a
dictionary representation.
Returns:
dict: The Input as an alternative serialization format. | Below is the the instruction that describes the task:
### Input:
Transforms the object to a Python dictionary.
Note:
If an Input hasn't been signed yet, this method returns a
dictionary representation.
Returns:
dict: The Input as an alternati... |
def norm_l0(x, axis=None, eps=0.0):
r"""Compute the :math:`\ell_0` "norm" (it is not really a norm)
.. math::
\| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc}
0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0
\end{array} \right.
where :math:`x_i` is element :math:`i` of vector :ma... | r"""Compute the :math:`\ell_0` "norm" (it is not really a norm)
.. math::
\| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc}
0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0
\end{array} \right.
where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`.
Parameters
--... | Below is the the instruction that describes the task:
### Input:
r"""Compute the :math:`\ell_0` "norm" (it is not really a norm)
.. math::
\| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc}
0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0
\end{array} \right.
where :math:`x_i` is el... |
def run(self):
"""
Run the database seeds.
"""
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() | Run the database seeds. | Below is the the instruction that describes the task:
### Input:
Run the database seeds.
### Response:
def run(self):
"""
Run the database seeds.
"""
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() |
def _get_date_time_format(dt_string):
'''
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string
'''
valid_forma... | Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string | Below is the the instruction that describes the task:
### Input:
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string
### ... |
def ListChildren(self, urn, limit=None, age=NEWEST_TIME):
"""Lists bunch of directories efficiently.
Args:
urn: Urn to list children.
limit: Max number of children to list.
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Returns:
R... | Lists bunch of directories efficiently.
Args:
urn: Urn to list children.
limit: Max number of children to list.
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Returns:
RDFURNs instances of each child. | Below is the the instruction that describes the task:
### Input:
Lists bunch of directories efficiently.
Args:
urn: Urn to list children.
limit: Max number of children to list.
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Returns:
... |
def dump(self, raw=False):
''' Dump all output currently in the arm's output queue. '''
raw_out = self.ser.read(self.ser.in_waiting)
if raw:
return raw_out
return raw_out.decode(OUTPUT_ENCODING) | Dump all output currently in the arm's output queue. | Below is the the instruction that describes the task:
### Input:
Dump all output currently in the arm's output queue.
### Response:
def dump(self, raw=False):
''' Dump all output currently in the arm's output queue. '''
raw_out = self.ser.read(self.ser.in_waiting)
if raw:
return... |
def inquire_by_mech(self, mech, name=True, init_lifetime=True,
accept_lifetime=True, usage=True):
"""Inspect these credentials for per-mechanism information
This method inspects these credentials for per-mechanism information
about them.
Args:
mech (... | Inspect these credentials for per-mechanism information
This method inspects these credentials for per-mechanism information
about them.
Args:
mech (OID): the mechanism for which to retrive the information
name (bool): get the name associated with the credentials
... | Below is the the instruction that describes the task:
### Input:
Inspect these credentials for per-mechanism information
This method inspects these credentials for per-mechanism information
about them.
Args:
mech (OID): the mechanism for which to retrive the information
... |
def get(self, task_id=None, params=None):
"""
Retrieve information for a particular task.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_
:arg task_id: Return the task with specified id (node_id:task_number)
:arg wait_for_completion: Wait for the m... | Retrieve information for a particular task.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_
:arg task_id: Return the task with specified id (node_id:task_number)
:arg wait_for_completion: Wait for the matching tasks to complete
(default: false)
... | Below is the the instruction that describes the task:
### Input:
Retrieve information for a particular task.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_
:arg task_id: Return the task with specified id (node_id:task_number)
:arg wait_for_completion: Wait fo... |
def fully_scope_function_calls(node: ast.Tree, expression: ast.Expression, function_set: OrderedDict) -> ast.Expression:
"""
Turns the function references in this expression into fully scoped
references (e.g. relative to absolute). The component references of all
referenced functions are put into the fu... | Turns the function references in this expression into fully scoped
references (e.g. relative to absolute). The component references of all
referenced functions are put into the functions set.
:param node: collection for performing symbol lookup etc.
:param expression: original expression
:param fun... | Below is the the instruction that describes the task:
### Input:
Turns the function references in this expression into fully scoped
references (e.g. relative to absolute). The component references of all
referenced functions are put into the functions set.
:param node: collection for performing symbol ... |
def _detect_cms(self, tries=0):
"""
Detect CMS using whatcms.org.
Has a re-try mechanism because false negatives may occur
:param tries: Count of tries for CMS discovery
"""
# WhatCMS is under CloudFlare which detects and blocks proxied/Tor traffic, hence normal request.
... | Detect CMS using whatcms.org.
Has a re-try mechanism because false negatives may occur
:param tries: Count of tries for CMS discovery | Below is the the instruction that describes the task:
### Input:
Detect CMS using whatcms.org.
Has a re-try mechanism because false negatives may occur
:param tries: Count of tries for CMS discovery
### Response:
def _detect_cms(self, tries=0):
"""
Detect CMS using whatcms.org.
... |
def _setupParseTree(self, rowFrom, rowTo, colIndex, tree):
""" Build the search tree for multi-character encodings.
"""
if colIndex == self._longestEntry:
return
prevchar = None
rowIndex = rowFrom
while rowIndex <= rowTo:
if colIndex < len(self._pa... | Build the search tree for multi-character encodings. | Below is the the instruction that describes the task:
### Input:
Build the search tree for multi-character encodings.
### Response:
def _setupParseTree(self, rowFrom, rowTo, colIndex, tree):
""" Build the search tree for multi-character encodings.
"""
if colIndex == self._longestEntry:
... |
def cause_mip(self, mechanism, purview):
"""Return the irreducibility analysis for the cause MIP.
Alias for |find_mip()| with ``direction`` set to |CAUSE|.
"""
return self.find_mip(Direction.CAUSE, mechanism, purview) | Return the irreducibility analysis for the cause MIP.
Alias for |find_mip()| with ``direction`` set to |CAUSE|. | Below is the the instruction that describes the task:
### Input:
Return the irreducibility analysis for the cause MIP.
Alias for |find_mip()| with ``direction`` set to |CAUSE|.
### Response:
def cause_mip(self, mechanism, purview):
"""Return the irreducibility analysis for the cause MIP.
... |
def squareform_isfc(isfcs, iscs=None):
"""Converts square ISFCs to condensed ISFCs (and ISCs), and vice-versa
If input is a 2- or 3-dimensional array of square ISFC matrices, converts
this to the condensed off-diagonal ISFC values (i.e., the vectorized
triangle) and the diagonal ISC values. In this ca... | Converts square ISFCs to condensed ISFCs (and ISCs), and vice-versa
If input is a 2- or 3-dimensional array of square ISFC matrices, converts
this to the condensed off-diagonal ISFC values (i.e., the vectorized
triangle) and the diagonal ISC values. In this case, input must be a
single array of shape e... | Below is the the instruction that describes the task:
### Input:
Converts square ISFCs to condensed ISFCs (and ISCs), and vice-versa
If input is a 2- or 3-dimensional array of square ISFC matrices, converts
this to the condensed off-diagonal ISFC values (i.e., the vectorized
triangle) and the diagonal ... |
def change_cash(self, money):
"""
外部操作|高危|
"""
res = self.cash[-1] + money
if res >= 0:
# 高危操作
self.cash[-1] = res | 外部操作|高危| | Below is the the instruction that describes the task:
### Input:
外部操作|高危|
### Response:
def change_cash(self, money):
"""
外部操作|高危|
"""
res = self.cash[-1] + money
if res >= 0:
# 高危操作
self.cash[-1] = res |
def disconnect(self):
"""Disconnect from server."""
self.logger.info("DISCONNECT")
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.state = NC.CS_DISCONNECTING
ret = self.send_disconnect()
ret2, bytes_written = self.packet_write()
... | Disconnect from server. | Below is the the instruction that describes the task:
### Input:
Disconnect from server.
### Response:
def disconnect(self):
"""Disconnect from server."""
self.logger.info("DISCONNECT")
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.state = NC.CS_DISCONNEC... |
def ignore_exception(IgnoreException=Exception, DefaultVal=None):
""" Decorator for ignoring exception from a function
e.g. @ignore_exception(DivideByZero)
e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
borrowed from: http://stackoverflow.com/questions/2262333/is-there-a-built-in-or-more-pythonic-... | Decorator for ignoring exception from a function
e.g. @ignore_exception(DivideByZero)
e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
borrowed from: http://stackoverflow.com/questions/2262333/is-there-a-built-in-or-more-pythonic-way-to-try-to-parse-a-string-to-an-integer | Below is the the instruction that describes the task:
### Input:
Decorator for ignoring exception from a function
e.g. @ignore_exception(DivideByZero)
e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
borrowed from: http://stackoverflow.com/questions/2262333/is-there-a-built-in-or-more-pythonic-way-t... |
def parents(self, primary=None):
"""
:param primary: if None, then all parents are returned. If True, then only foreign keys composed of
primary key attributes are considered. If False, the only foreign keys including at least one non-primary
attribute are considered.
:r... | :param primary: if None, then all parents are returned. If True, then only foreign keys composed of
primary key attributes are considered. If False, the only foreign keys including at least one non-primary
attribute are considered.
:return: dict of tables referenced with self's foreign ... | Below is the the instruction that describes the task:
### Input:
:param primary: if None, then all parents are returned. If True, then only foreign keys composed of
primary key attributes are considered. If False, the only foreign keys including at least one non-primary
attribute are consid... |
def local_is_up(self, target):
"""
Check if a tunnel is up (remote target's host is reachable on TCP
target's port)
Arguments:
target (tuple):
tuple of type (``str``, ``int``) indicating the listen IP
address and port
Return:
... | Check if a tunnel is up (remote target's host is reachable on TCP
target's port)
Arguments:
target (tuple):
tuple of type (``str``, ``int``) indicating the listen IP
address and port
Return:
boolean
.. deprecated:: 0.1.0
... | Below is the the instruction that describes the task:
### Input:
Check if a tunnel is up (remote target's host is reachable on TCP
target's port)
Arguments:
target (tuple):
tuple of type (``str``, ``int``) indicating the listen IP
address and port
... |
def InformarCalidadCertificacion(self, coe):
"Informar calidad de un certificado (C1116A/RT)"
# llamo al webservice:
ret = self.client.cgInformarCalidad(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit'... | Informar calidad de un certificado (C1116A/RT) | Below is the the instruction that describes the task:
### Input:
Informar calidad de un certificado (C1116A/RT)
### Response:
def InformarCalidadCertificacion(self, coe):
"Informar calidad de un certificado (C1116A/RT)"
# llamo al webservice:
ret = self.client.cgInformarCalidad(
... |
def on_update_enabled(self, conf_evt):
"""Implements neighbor configuration change listener.
"""
enabled = conf_evt.value
# If we do not have any protocol bound and configuration asks us to
# enable this peer, we try to establish connection again.
if enabled:
... | Implements neighbor configuration change listener. | Below is the the instruction that describes the task:
### Input:
Implements neighbor configuration change listener.
### Response:
def on_update_enabled(self, conf_evt):
"""Implements neighbor configuration change listener.
"""
enabled = conf_evt.value
# If we do not have any protoco... |
def connect(self, node="", rpcuser="", rpcpassword="", **kwargs):
""" Connect to blockchain network (internal use only)
"""
if not node:
if "node" in self.config:
node = self.config["node"]
else:
raise ValueError("A Blockchain node needs to... | Connect to blockchain network (internal use only) | Below is the the instruction that describes the task:
### Input:
Connect to blockchain network (internal use only)
### Response:
def connect(self, node="", rpcuser="", rpcpassword="", **kwargs):
""" Connect to blockchain network (internal use only)
"""
if not node:
if "node" in ... |
def _parse_to_recoverable_signature(sig):
"""
Returns a parsed recoverable signature of length 65 bytes
"""
# Buffer for getting values of signature object
assert isinstance(sig, bytes)
assert len(sig) == 65
# Make a recoverable signature of 65 bytes
rec_sig = ffi.new("secp256k1_ecd... | Returns a parsed recoverable signature of length 65 bytes | Below is the the instruction that describes the task:
### Input:
Returns a parsed recoverable signature of length 65 bytes
### Response:
def _parse_to_recoverable_signature(sig):
"""
Returns a parsed recoverable signature of length 65 bytes
"""
# Buffer for getting values of signature object
... |
def ask_yesno(msg="Proceed?", dft=None):
"""Prompts the user for a yes or no answer. Returns True for yes, False
for no."""
yes = ["y", "yes", "Y", "YES"]
no = ["n", "no", "N", "NO"]
if dft != None:
dft = yes[0] if (dft in yes or dft == True) else no[0]
return ask(msg, dft=dft, vld=yes+n... | Prompts the user for a yes or no answer. Returns True for yes, False
for no. | Below is the the instruction that describes the task:
### Input:
Prompts the user for a yes or no answer. Returns True for yes, False
for no.
### Response:
def ask_yesno(msg="Proceed?", dft=None):
"""Prompts the user for a yes or no answer. Returns True for yes, False
for no."""
yes = ["y", "yes", ... |
def assertFileSizeNotAlmostEqual(
self, filename, size, places=None, msg=None, delta=None):
'''Fail unless ``filename`` does not have the given ``size``
as determined by their difference rounded to the given number
ofdecimal ``places`` (default 7) and comparing to zero, or if
... | Fail unless ``filename`` does not have the given ``size``
as determined by their difference rounded to the given number
ofdecimal ``places`` (default 7) and comparing to zero, or if
their difference is greater than a given ``delta``.
Parameters
----------
filename : str,... | Below is the the instruction that describes the task:
### Input:
Fail unless ``filename`` does not have the given ``size``
as determined by their difference rounded to the given number
ofdecimal ``places`` (default 7) and comparing to zero, or if
their difference is greater than a given ``de... |
def enumerate_reversed(sequence):
"""
Perform reverse enumeration, returning an iterator with decrementing
index/position values
Source: http://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python
"""
for index in reversed(xrange(len(sequence))):
yield index, se... | Perform reverse enumeration, returning an iterator with decrementing
index/position values
Source: http://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python | Below is the the instruction that describes the task:
### Input:
Perform reverse enumeration, returning an iterator with decrementing
index/position values
Source: http://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python
### Response:
def enumerate_reversed(sequence):
"""
... |
def __query(self, query, tagid=None):
"""
Extracts nodes that match the query from the Response
:param query: Xpath Expresion
:type query: String
:param tagid: Tag ID
:type query: String
:returns: The queried nodes
:rtype: list
"""
if se... | Extracts nodes that match the query from the Response
:param query: Xpath Expresion
:type query: String
:param tagid: Tag ID
:type query: String
:returns: The queried nodes
:rtype: list | Below is the the instruction that describes the task:
### Input:
Extracts nodes that match the query from the Response
:param query: Xpath Expresion
:type query: String
:param tagid: Tag ID
:type query: String
:returns: The queried nodes
:rtype: list
### Response: ... |
def is_sparse_file(filename):
"""Determine if the given filename indicates a dense or a sparse matrix
If pathname is xxx.coo.yyy return True otherwise False.
"""
dirname, basename = os.path.split(filename)
name, ext = os.path.splitext(basename)
matrix_name, matrix_ext = os.path.splitext(nam... | Determine if the given filename indicates a dense or a sparse matrix
If pathname is xxx.coo.yyy return True otherwise False. | Below is the the instruction that describes the task:
### Input:
Determine if the given filename indicates a dense or a sparse matrix
If pathname is xxx.coo.yyy return True otherwise False.
### Response:
def is_sparse_file(filename):
"""Determine if the given filename indicates a dense or a sparse matr... |
def create_tag(
tag,
escaper=EscapedHTMLString,
opening_only=False,
body=None,
escape_body=False,
escape_attr=True,
indent=0,
attrs=None,
**other_attrs):
"""
Create an XML/HTML tag.
This function create a full XML/HTML tag, putting tog... | Create an XML/HTML tag.
This function create a full XML/HTML tag, putting toghether an
optional inner body and a dictionary of attributes.
>>> print create_html_tag ("select", create_html_tag("h1",
... "hello", other_attrs={'class': "foo"}))
<select>
<h1 class="foo">
... | Below is the the instruction that describes the task:
### Input:
Create an XML/HTML tag.
This function create a full XML/HTML tag, putting toghether an
optional inner body and a dictionary of attributes.
>>> print create_html_tag ("select", create_html_tag("h1",
... "hello", other_attrs={'... |
def to_trip(
self,
smooth,
smooth_strategy,
smooth_noise,
seg,
seg_eps,
seg_min_time,
simplify,
simplify_max_dist_error,
simplify_max_speed_error
):
"""In-place, transformation of a tr... | In-place, transformation of a track into a trip
A trip is a more accurate depiction of reality than a
track.
For a track to become a trip it need to go through the
following steps:
+ noise removal
+ smoothing
+ spatio-temporal segmentation
... | Below is the the instruction that describes the task:
### Input:
In-place, transformation of a track into a trip
A trip is a more accurate depiction of reality than a
track.
For a track to become a trip it need to go through the
following steps:
+ noise removal
... |
def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if there is creep on the grid point. """
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self.state.creep[pos] != 0 | Returns True if there is creep on the grid point. | Below is the the instruction that describes the task:
### Input:
Returns True if there is creep on the grid point.
### Response:
def has_creep(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if there is creep on the grid point. """
assert isinstance(pos, (Point2, Point3, Unit))
... |
def get_overlay(self, overlay_name):
"""Return overlay as a dictionary.
:param overlay_name: name of the overlay
:returns: overlay as a dictionary
"""
url = self.http_manifest["overlays"][overlay_name]
return self._get_json_from_url(url) | Return overlay as a dictionary.
:param overlay_name: name of the overlay
:returns: overlay as a dictionary | Below is the the instruction that describes the task:
### Input:
Return overlay as a dictionary.
:param overlay_name: name of the overlay
:returns: overlay as a dictionary
### Response:
def get_overlay(self, overlay_name):
"""Return overlay as a dictionary.
:param overlay_name: na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.