INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
A search that keeps searching up until timeout for a
specific number of matches to a search. If timeout is not
specified we use the default. If count= is not specified we
will fail. Return values are the same as search(), except for count=0,
where we will return an empty list. Use this ... | def search_for_count(self, ** args):
"""
A search that keeps searching up until timeout for a
specific number of matches to a search. If timeout is not
specified we use the default. If count= is not specified we
will fail. Return values are the same as search(), except for count... |
Given a message number, return the Email.Message object.
@Params
msgnum - message number to find
@Returns
Email.Message object for the given message number | def fetch_message(self, msgnum):
"""
Given a message number, return the Email.Message object.
@Params
msgnum - message number to find
@Returns
Email.Message object for the given message number
"""
self.imap_connect()
status, data = self.mailbox.fet... |
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type - Type of content to get from the email
@Return
String cont... | def get_content_type(self, msg, content_type="HTML"):
"""
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type -... |
Checks email inbox every 15 seconds that match the criteria
up until timeout.
Search criteria should be keyword args eg
TO="selenium@gmail.com". See __imap_search docstring for list
of valid criteria. If content_type is not defined, will return
a list of msg numbers.
O... | def search(self, ** args):
"""
Checks email inbox every 15 seconds that match the criteria
up until timeout.
Search criteria should be keyword args eg
TO="selenium@gmail.com". See __imap_search docstring for list
of valid criteria. If content_type is not defined, will r... |
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace | def remove_whitespace(self, html):
"""
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace
"""
# Does python have a better way to do exactly this?
clean_html = html
for cha... |
Replace htmlentities with unicode characters
@Params
html - html source to replace entities in
@Returns
String html with entities replaced | def replace_entities(self, html):
"""
Replace htmlentities with unicode characters
@Params
html - html source to replace entities in
@Returns
String html with entities replaced
"""
def fixup(text):
"""replace the htmlentities in some text"""
... |
If "jQuery is not defined", use this method to activate it for use.
This happens because jQuery is not always defined on web sites. | def activate_jquery(driver):
""" If "jQuery is not defined", use this method to activate it for use.
This happens because jQuery is not always defined on web sites. """
try:
# Let's first find out if jQuery is already defined.
driver.execute_script("jQuery('html')")
# Since that ... |
re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javascript calls. | def escape_quotes_if_needed(string):
"""
re.escape() works differently in Python 3.7.0 than earlier versions:
Python 3.6.5:
>>> import re
>>> re.escape('"')
'\\"'
Python 3.7.0:
>>> import re
>>> re.escape('"')
'"'
SeleniumBase needs quotes to be properly escaped for Javasc... |
When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. | def safe_execute_script(driver, script):
""" When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. """
try:
driver.execute_script(script)
except Exception:
... |
A helper method to post a message on the screen with Messenger.
(Should only be called from post_message() in base_case.py) | def post_message(driver, message, msg_dur, style="info"):
""" A helper method to post a message on the screen with Messenger.
(Should only be called from post_message() in base_case.py) """
if not msg_dur:
msg_dur = settings.DEFAULT_MESSAGE_DURATION
msg_dur = float(msg_dur)
message = re.... |
DEPRECATED - Use re.escape() instead, which performs the intended action.
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
If you just want to escape quotes, there's escape_quotes_if_needed().
This is similar to ... | def _jq_format(code):
"""
DEPRECATED - Use re.escape() instead, which performs the intended action.
Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.
Selectors with quotes inside of quotes would otherwise break jQuery.
If you just want to escape quotes, there's escape_quotes_if... |
When testing_base is specified, but none of the log options to save are
specified (basic_test_info, screen_shots, page_source), then save them
all by default. Otherwise, save only selected ones from their plugins. | def __log_all_options_if_none_specified(self, test):
"""
When testing_base is specified, but none of the log options to save are
specified (basic_test_info, screen_shots, page_source), then save them
all by default. Otherwise, save only selected ones from their plugins.
"""
... |
Since Skip, Blocked, and Deprecated are all technically errors, but not
error states, we want to make sure that they don't show up in
the nose output as errors. | def addError(self, test, err, capt=None):
"""
Since Skip, Blocked, and Deprecated are all technically errors, but not
error states, we want to make sure that they don't show up in
the nose output as errors.
"""
if (err[0] == errors.BlockedTest or (
err[0] ... |
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base. | def handleError(self, test, err, capt=None):
"""
If the database plugin is not present, we have to handle capturing
"errors" that shouldn't be reported as such in base.
"""
if not hasattr(test.test, "testcase_guid"):
if err[0] == errors.BlockedTest:
ra... |
Executes a db query, gets all the values, and closes the connection. | def query_fetch_all(self, query, values):
"""
Executes a db query, gets all the values, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchall()
self.__close_db()
return retval |
Executes a db query, gets the first value, and closes the connection. | def query_fetch_one(self, query, values):
"""
Executes a db query, gets the first value, and closes the connection.
"""
self.cursor.execute(query, values)
retval = self.cursor.fetchone()
self.__close_db()
return retval |
Executes a query to the test_db and closes the connection afterwards. | def execute_query(self, query, values):
"""
Executes a query to the test_db and closes the connection afterwards.
"""
retval = self.cursor.execute(query, values)
self.__close_db()
return retval |
Combines the domain base href with the html source.
This is needed for the page html to render correctly. | def get_html_source_with_base_href(driver, page_source):
''' Combines the domain base href with the html source.
This is needed for the page html to render correctly. '''
last_page = get_last_page(driver)
if '://' in last_page:
base_href_html = get_base_href_html(last_page)
return '%... |
Handle Logging | def log_folder_setup(log_path, archive_logs=False):
""" Handle Logging """
if log_path.endswith("/"):
log_path = log_path[:-1]
if not os.path.exists(log_path):
try:
os.makedirs(log_path)
except Exception:
pass # Should only be reachable during multi-threaded ... |
Downloads the Selenium Server JAR file from its
online location and stores it locally. | def download_selenium_server():
"""
Downloads the Selenium Server JAR file from its
online location and stores it locally.
"""
try:
local_file = open(JAR_FILE, 'wb')
remote_file = urlopen(SELENIUM_JAR)
print('Downloading the Selenium Server JAR file...\n')
local_file.... |
At the end of the run, we want to
update the DB row with the execution time. | def finalize(self, result):
""" At the end of the run, we want to
update the DB row with the execution time. """
runtime = int(time.time() * 1000) - self.execution_start_time
self.testcase_manager.update_execution_data(self.execution_guid,
... |
At the start of the run, we want to record the test
execution information in the database. | def begin(self):
""" At the start of the run, we want to record the test
execution information in the database. """
exec_payload = ExecutionQueryPayload()
exec_payload.execution_start_time = int(time.time() * 1000)
self.execution_start_time = exec_payload.execution_start_time... |
After test completion, we want to record testcase run information. | def addSuccess(self, test, capt):
"""
After test completion, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.PASS, test) |
After a test error, we want to record testcase run information. | def addError(self, test, err, capt=None):
"""
After a test error, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.ERROR, test, err) |
After a test error, we want to record testcase run information.
"Error" also encompasses any states other than Pass or Fail, so we
check for those first. | def handleError(self, test, err, capt=None):
"""
After a test error, we want to record testcase run information.
"Error" also encompasses any states other than Pass or Fail, so we
check for those first.
"""
if err[0] == errors.BlockedTest:
self.__insert_test_r... |
After a test failure, we want to record testcase run information. | def addFailure(self, test, err, capt=None, tbinfo=None):
"""
After a test failure, we want to record testcase run information.
"""
self.__insert_test_result(constants.State.FAILURE, test, err) |
Implementation of https://stackoverflow.com/a/35293284 for
https://stackoverflow.com/questions/12848327/
(Run Selenium on a proxy server that requires authentication.) | def _add_chrome_proxy_extension(
chrome_options, proxy_string, proxy_user, proxy_pass):
""" Implementation of https://stackoverflow.com/a/35293284 for
https://stackoverflow.com/questions/12848327/
(Run Selenium on a proxy server that requires authentication.) """
if not "".join(sys.argv)... |
Spins up a new web browser and returns the driver.
Can also be used to spin up additional browsers for the same test. | def get_local_driver(
browser_name, headless, proxy_string, proxy_auth,
proxy_user, proxy_pass, user_agent, disable_csp):
'''
Spins up a new web browser and returns the driver.
Can also be used to spin up additional browsers for the same test.
'''
downloads_path = download_helper.get... |
Get the options. | def configure(self, options, conf):
""" Get the options. """
super(S3Logging, self).configure(options, conf)
self.options = options |
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output. | def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
... |
Returns an active user that matches the payload's user id and email. | def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
User = get_user_model()
username = jwt_get_username_from_payload(payload)
if not username:
msg = _('Invalid payload.')
raise ... |
Scan a single row from an Excel file, and return the list of ranges
corresponding to each consecutive span of non-empty cells in this row.
If all cells are empty, return an empty list. Each "range" in the list
is a tuple of the form `(startcol, endcol)`.
For example, if the row is the following:
... | def _parse_row(rowvalues, rowtypes):
"""
Scan a single row from an Excel file, and return the list of ranges
corresponding to each consecutive span of non-empty cells in this row.
If all cells are empty, return an empty list. Each "range" in the list
is a tuple of the form `(startcol, endcol)`.
... |
This function takes a list of row-ranges (as returned by `_parse_row`)
ordered by rows, and produces a list of distinct rectangular ranges
within this grid.
Within this function we define a 2d-range as a rectangular set of cells
such that:
- there are no empty rows / columns within this rectangle... | def _combine_ranges(ranges):
"""
This function takes a list of row-ranges (as returned by `_parse_row`)
ordered by rows, and produces a list of distinct rectangular ranges
within this grid.
Within this function we define a 2d-range as a rectangular set of cells
such that:
- there are no e... |
Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`
and merge them into `ranges[ja]`. Finally, return the new index of the
ja-th range within the `ranges` list. | def _collapse_ranges(ranges, ja):
"""
Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`
and merge them into `ranges[ja]`. Finally, return the new index of the
ja-th range within the `ranges` list.
"""
arow0, _, acol0, acol1 = ranges[ja]
jb = 0
while jb < len(ra... |
This function attempts to locate the required link libraries, and returns
them as a list of absolute paths. | def find_linked_dynamic_libraries():
"""
This function attempts to locate the required link libraries, and returns
them as a list of absolute paths.
"""
with TaskContext("Find the required dynamic libraries") as log:
llvm = get_llvm()
libs = required_link_libraries()
resolved... |
Listen to user's keystrokes and return them to caller one at a time.
The produced values are instances of blessed.keyboard.Keystroke class.
If the user did not press anything with the last `refresh_rate` seconds
the generator will yield `None`, allowing the caller to perform any
updates... | def wait_for_keypresses(self, refresh_rate=1):
"""
Listen to user's keystrokes and return them to caller one at a time.
The produced values are instances of blessed.keyboard.Keystroke class.
If the user did not press anything with the last `refresh_rate` seconds
the generator wi... |
Return the slice tuple normalized for an ``n``-element object.
:param e: a slice object representing a selector
:param n: number of elements in a sequence to which ``e`` is applied
:returns: tuple ``(start, count, step)`` derived from ``e``. | def normalize_slice(e, n):
"""
Return the slice tuple normalized for an ``n``-element object.
:param e: a slice object representing a selector
:param n: number of elements in a sequence to which ``e`` is applied
:returns: tuple ``(start, count, step)`` derived from ``e``.
"""
if n == 0:
... |
Return the range tuple normalized for an ``n``-element object.
The semantics of a range is slightly different than that of a slice.
In particular, a range is similar to a list in meaning (and on Py2 it was
eagerly expanded into a list). Thus we do not allow the range to generate
indices that would be ... | def normalize_range(e, n):
"""
Return the range tuple normalized for an ``n``-element object.
The semantics of a range is slightly different than that of a slice.
In particular, a range is similar to a list in meaning (and on Py2 it was
eagerly expanded into a list). Thus we do not allow the range... |
Import and return the requested module. | def load_module(module):
"""
Import and return the requested module.
"""
try:
m = importlib.import_module(module)
return m
except ModuleNotFoundError: # pragma: no cover
raise TImportError("Module `%s` is not installed. It is required for "
"runnin... |
Convert given number of bytes into a human readable representation, i.e. add
prefix such as KB, MB, GB, etc. The `size` argument must be a non-negative
integer.
:param size: integer representing byte size of something
:return: string representation of the size, in human-readable form | def humanize_bytes(size):
"""
Convert given number of bytes into a human readable representation, i.e. add
prefix such as KB, MB, GB, etc. The `size` argument must be a non-negative
integer.
:param size: integer representing byte size of something
:return: string representation of the size, in ... |
Retrieve frame data within the current view window.
This method will adjust the view window if it goes out-of-bounds. | def _fetch_data(self):
"""
Retrieve frame data within the current view window.
This method will adjust the view window if it goes out-of-bounds.
"""
self._view_col0 = clamp(self._view_col0, 0, self._max_col0)
self._view_row0 = clamp(self._view_row0, 0, self._max_row0)
... |
Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc". | def get_files():
"""
Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc".
"""
sources = []
headers = ["datatable/include/datatable.h"]
assert os.path.isfile(headers[0])
for di... |
Find user includes (no system includes) requested from given source file.
All .h files will be given relative to the current folder, e.g.
["c/rowindex.h", "c/column.h"]. | def find_includes(filename):
"""
Find user includes (no system includes) requested from given source file.
All .h files will be given relative to the current folder, e.g.
["c/rowindex.h", "c/column.h"].
"""
includes = []
with open(filename, "r", encoding="utf-8") as inp:
for line in... |
Construct dictionary {header_file : set_of_included_files}.
This function operates on "real" set of includes, in the sense that it
parses each header file to check which files are included from there. | def build_headermap(headers):
"""
Construct dictionary {header_file : set_of_included_files}.
This function operates on "real" set of includes, in the sense that it
parses each header file to check which files are included from there.
"""
# TODO: what happens if some headers are circularly depe... |
Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files). | def build_sourcemap(sources):
"""
Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files).
"""
sourcemap = {}
for sfile in sources:
inc = find_includes(sfile)
sourcemap[sfile] = set(inc)
return sourcemap |
Find all C/C++ source files in the `folder` directory. | def get_c_sources(folder, include_headers=False):
"""Find all C/C++ source files in the `folder` directory."""
allowed_extensions = [".c", ".C", ".cc", ".cpp", ".cxx", ".c++"]
if include_headers:
allowed_extensions += [".h", ".hpp"]
sources = []
for root, _, files in os.walk(folder):
... |
Invoked from the C level, this function will return either the name of
the folder where the datatable is to be saved; or None, indicating that
the datatable should be read into RAM. This function may also raise an
exception if it determines that it cannot find a good strategy to
handle a... | def _get_destination(self, estimated_size):
"""
Invoked from the C level, this function will return either the name of
the folder where the datatable is to be saved; or None, indicating that
the datatable should be read into RAM. This function may also raise an
exception if it de... |
Save Frame in binary NFF/Jay format.
:param dest: destination where the Frame should be saved.
:param _strategy: one of "mmap", "write" or "auto" | def save_nff(self, dest, _strategy="auto"):
"""
Save Frame in binary NFF/Jay format.
:param dest: destination where the Frame should be saved.
:param _strategy: one of "mmap", "write" or "auto"
"""
if _strategy not in ("auto", "write", "mmap"):
raise TValueError("Invalid parameter _stra... |
Send an event. | def event(
title,
text,
alert_type=None,
aggregation_key=None,
source_type_name=None,
date_happened=None,
priority=None,
tags=None,
hostname=None,
):
"""
Send an event.
""" |
Return all the projects for which the user is a sole owner | def user_projects(request):
""" Return all the projects for which the user is a sole owner """
projects_owned = (
request.db.query(Project.id)
.join(Role.project)
.filter(Role.role_name == "Owner", Role.user == request.user)
.subquery()
)
with_sole_owner = (
requ... |
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision. | def merge(config, revisions, **kwargs):
"""
Merge one or more revisions.
Takes one or more revisions or "heads" for all heads and merges them into
a single revision.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
ale... |
Return a series of WHERE clauses against a given column that break it into
windows.
Result is an iterable of tuples, consisting of ((start, end), whereclause),
where (start, end) are the ids.
Requires a database that supports window functions, i.e. Postgresql,
SQL Server, Oracle.
Enhance this... | def column_windows(session, column, windowsize):
"""
Return a series of WHERE clauses against a given column that break it into
windows.
Result is an iterable of tuples, consisting of ((start, end), whereclause),
where (start, end) are the ids.
Requires a database that supports window function... |
Break a Query into windows on a given column. | def windowed_query(q, column, windowsize):
""""
Break a Query into windows on a given column.
"""
for whereclause in column_windows(q.session, column, windowsize):
for row in q.filter(whereclause).order_by(column):
yield row |
Filters given query with the below regex
and returns lists of quoted and unquoted strings | def filter_query(s):
"""
Filters given query with the below regex
and returns lists of quoted and unquoted strings
"""
matches = re.findall(r'(?:"([^"]*)")|([^"]*)', s)
result_quoted = [t[0].strip() for t in matches if t[0]]
result_unquoted = [t[1].strip() for t in matches if t[1]]
retur... |
Returns a multi match query | def form_query(query_type, query):
"""
Returns a multi match query
"""
fields = [
field + "^" + str(SEARCH_BOOSTS[field]) if field in SEARCH_BOOSTS else field
for field in SEARCH_FIELDS
]
return Q("multi_match", fields=fields, query=query, type=query_type) |
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | def run_migrations_offline():
"""
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit ... |
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | def run_migrations_online():
"""
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = context.config.attributes.get("connection", None)
if connectable is None:
options = context.config.get_secti... |
Show current branch points. | def branches(config, **kwargs):
"""
Show current branch points.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.branches(alembic_config, **kwargs) |
Upgrade database. | def upgrade(config, revision, **kwargs):
"""
Upgrade database.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.upgrade(alembic_config, revision, **kwargs) |
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url. | def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url.
"""
if url is not None:
url = url.strip()
if not url:
return False
# Chrome ... |
Submit metrics. | def submit_xmlrpc_metrics(method=None):
"""
Submit metrics.
"""
def decorator(f):
def wrapped(context, request):
metrics = request.find_service(IMetricsService, context=None)
metrics.increment("warehouse.xmlrpc.call", tags=[f"rpc_method:{method}"])
with metri... |
Sanitize any user-submitted data to ensure that it can be used in XML | def _clean_for_xml(data):
""" Sanitize any user-submitted data to ensure that it can be used in XML """
# If data is None or an empty string, don't bother
if data:
# This turns a string like "Hello…" into "Hello…"
data = data.encode("ascii", "xmlcharrefreplace").decode("ascii")
... |
Support multiple endpoints serving the same views by chaining calls to
xmlrpc_method | def xmlrpc_method(**kwargs):
"""
Support multiple endpoints serving the same views by chaining calls to
xmlrpc_method
"""
# Add some default arguments
kwargs.update(
require_csrf=False,
require_methods=["POST"],
decorator=(submit_xmlrpc_metrics(method=kwargs["method"]),),... |
Display the current revision for a database. | def current(config, **kwargs):
"""
Display the current revision for a database.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.current(alembic_config, **kwargs) |
Check to see if file already exists, and if it's content matches.
A file is considered to exist if its filename *or* blake2 digest are
present in a file row in the database.
Returns:
- True: This file is a duplicate and all further processing should halt.
- False: This file exists, but it is not a ... | def _is_duplicate_file(db_session, filename, hashes):
"""
Check to see if file already exists, and if it's content matches.
A file is considered to exist if its filename *or* blake2 digest are
present in a file row in the database.
Returns:
- True: This file is a duplicate and all further proce... |
Open up a Python shell with Warehouse preconfigured in it. | def shell(config, type_):
"""
Open up a Python shell with Warehouse preconfigured in it.
"""
# Imported here because we don't want to trigger an import from anything
# but warehouse.cli at the module scope.
from warehouse.db import Session
if type_ is None:
type_ = autodetect()
... |
This decorator is used to turn an e function into an email sending function!
The name parameter is the name of the email we're going to be sending (used to
locate the templates on the file system).
The allow_unverified kwarg flags whether we will send this email to an unverified
email or not. We gener... | def _email(name, *, allow_unverified=False):
"""
This decorator is used to turn an e function into an email sending function!
The name parameter is the name of the email we're going to be sending (used to
locate the templates on the file system).
The allow_unverified kwarg flags whether we will se... |
List changeset scripts in chronological order. | def history(config, revision_range, **kwargs):
"""
List changeset scripts in chronological order.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.history(alembic_config, revision_range, **kwargs) |
Recreate the Search Index. | def reindex(config):
"""
Recreate the Search Index.
"""
request = config.task(_reindex).get_request()
config.task(_reindex).run(request) |
Show current available heads. | def heads(config, **kwargs):
"""
Show current available heads.
"""
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.heads(alembic_config, **kwargs) |
Recreate the Search Index. | def reindex(self, request):
"""
Recreate the Search Index.
"""
r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"])
try:
with SearchLock(r, timeout=30 * 60, blocking_timeout=30):
p = urllib.parse.urlparse(request.registry.settings["elasticsearch.url"]... |
API endpoint to retrieve a list of links to transaction
outputs.
Returns:
A :obj:`list` of :cls:`str` of links to outputs. | def get(self):
"""API endpoint to retrieve a list of links to transaction
outputs.
Returns:
A :obj:`list` of :cls:`str` of links to outputs.
"""
parser = reqparse.RequestParser()
parser.add_argument('public_key', type=parameters.valid_ed25519,
... |
Show the current configuration | def run_show_config(args):
"""Show the current configuration"""
# TODO Proposal: remove the "hidden" configuration. Only show config. If
# the system needs to be configured, then display information on how to
# configure the system.
config = copy.deepcopy(bigchaindb.config)
del config['CONFIGURE... |
Run a script to configure the current node. | def run_configure(args):
"""Run a script to configure the current node."""
config_path = args.config or bigchaindb.config_utils.CONFIG_DEFAULT_PATH
config_file_exists = False
# if the config path is `-` then it's stdout
if config_path != '-':
config_file_exists = os.path.exists(config_path)... |
Initiates an election to add/update/remove a validator to an existing BigchainDB network
:param args: dict
args = {
'public_key': the public key of the proposed peer, (str)
'power': the proposed validator power for the new peer, (str)
'node_id': the node_id of the new peer (str)
... | def run_election_new_upsert_validator(args, bigchain):
"""Initiates an election to add/update/remove a validator to an existing BigchainDB network
:param args: dict
args = {
'public_key': the public key of the proposed peer, (str)
'power': the proposed validator power for the new peer, ... |
Approve an election
:param args: dict
args = {
'election_id': the election_id of the election (str)
'sk': the path to the private key of the signer (str)
}
:param bigchain: an instance of BigchainDB
:return: success log message or `False` in case of error | def run_election_approve(args, bigchain):
"""Approve an election
:param args: dict
args = {
'election_id': the election_id of the election (str)
'sk': the path to the private key of the signer (str)
}
:param bigchain: an instance of BigchainDB
:return: success log messag... |
Retrieves information about an election
:param args: dict
args = {
'election_id': the transaction_id for an election (str)
}
:param bigchain: an instance of BigchainDB | def run_election_show(args, bigchain):
"""Retrieves information about an election
:param args: dict
args = {
'election_id': the transaction_id for an election (str)
}
:param bigchain: an instance of BigchainDB
"""
election = bigchain.get_transaction(args.election_id)
if... |
Drop the database | def run_drop(args):
"""Drop the database"""
dbname = bigchaindb.config['database']['name']
if not args.yes:
response = input_on_stderr('Do you want to drop `{}` database? [y/n]: '.format(dbname))
if response != 'y':
return
conn = backend.connect()
dbname = bigchaindb.co... |
Start the processes to run the node | def run_start(args):
"""Start the processes to run the node"""
# Configure Logging
setup_logging()
logger.info('BigchainDB Version %s', bigchaindb.__version__)
run_recover(bigchaindb.lib.BigchainDB())
if not args.skip_initialize_database:
logger.info('Initializing database')
_... |
Show the supported Tendermint version(s) | def run_tendermint_version(args):
"""Show the supported Tendermint version(s)"""
supported_tm_ver = {
'description': 'BigchainDB supports the following Tendermint version(s)',
'tendermint': __tm_supported_versions__,
}
print(json.dumps(supported_tm_ver, indent=4, sort_keys=True)) |
Return all the assets that match the text search.
The results are sorted by text score.
For more information about the behavior of text search on MongoDB see
https://docs.mongodb.com/manual/reference/operator/query/text/#behavior
Args:
search (str): Text search string to query the text index
... | def text_search(conn, search, *, language='english', case_sensitive=False,
diacritic_sensitive=False, text_score=False, limit=0, table=None):
"""Return all the assets that match the text search.
The results are sorted by text score.
For more information about the behavior of text search on ... |
Main function | def main():
""" Main function """
ctx = {}
def pretty_json(data):
return json.dumps(data, indent=2, sort_keys=True)
client = server.create_app().test_client()
host = 'example.com:9984'
# HTTP Index
res = client.get('/', environ_overrides={'HTTP_HOST': host})
res_data = json.... |
Serialize a dict into a JSON formatted string.
This function enforces rules like the separator and order of keys.
This ensures that all dicts are serialized in the same way.
This is specially important for hashing data. We need to make sure that
everyone serializes their data in the sa... | def serialize(data):
"""Serialize a dict into a JSON formatted string.
This function enforces rules like the separator and order of keys.
This ensures that all dicts are serialized in the same way.
This is specially important for hashing data. We need to make sure that
everyone ser... |
Validate value of `key` in `obj` using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
key (str): key to be validated in `obj`.
validation_fun (function): function used to validate the value
of `k... | def validate_txn_obj(obj_name, obj, key, validation_fun):
"""Validate value of `key` in `obj` using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
key (str): key to be validated in `obj`.
validation_fun ... |
Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indica... | def validate_all_keys_in_obj(obj_name, obj, validation_fun):
"""Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the va... |
Validate value for all (nested) occurrence of `key` in `obj`
using `validation_fun`.
Args:
obj (dict): dictionary object.
key (str): key whose value is to be validated.
validation_fun (function): function used to validate the value
of `key`.
Rais... | def validate_all_values_for_key_in_obj(obj, key, validation_fun):
"""Validate value for all (nested) occurrence of `key` in `obj`
using `validation_fun`.
Args:
obj (dict): dictionary object.
key (str): key whose value is to be validated.
validation_fun (function)... |
Check if `key` contains ".", "$" or null characters.
https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
Args:
obj_name (str): object name to use when raising exception
key (str): key to validated
Returns:
None: validation successfu... | def validate_key(obj_name, key):
"""Check if `key` contains ".", "$" or null characters.
https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
Args:
obj_name (str): object name to use when raising exception
key (str): key to validated
Returns... |
Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flask application. | def create_app(*, debug=False, threads=1, bigchaindb_factory=None):
"""Return an instance of the Flask application.
Args:
debug (bool): a flag to activate the debug mode for the app
(default: False).
threads (int): number of threads to use
Return:
an instance of the Flas... |
Wrap and return an application ready to be run.
Args:
settings (dict): a dictionary containing the settings, more info
here http://docs.gunicorn.org/en/latest/settings.html
Return:
an initialized instance of the application. | def create_server(settings, log_config=None, bigchaindb_factory=None):
"""Wrap and return an application ready to be run.
Args:
settings (dict): a dictionary containing the settings, more info
here http://docs.gunicorn.org/en/latest/settings.html
Return:
an initialized instance... |
Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`bigchaindb.config` at the mo... | def setup_logging():
"""Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`... |
Return a dict with all the information specific for the v1 of the
api. | def get_api_v1_info(api_prefix):
"""Return a dict with all the information specific for the v1 of the
api.
"""
websocket_root = base_ws_uri() + EVENTS_ENDPOINT
docs_url = [
'https://docs.bigchaindb.com/projects/server/en/v',
version.__version__,
'/http-client-server-api.html'... |
Decorator to be used by command line functions, such that the
configuration of bigchaindb is performed before the execution of
the command.
Args:
command: The command to decorate.
Returns:
The command wrapper function. | def configure_bigchaindb(command):
"""Decorator to be used by command line functions, such that the
configuration of bigchaindb is performed before the execution of
the command.
Args:
command: The command to decorate.
Returns:
The command wrapper function.
"""
@functools.w... |
Output a string to stderr and wait for input.
Args:
prompt (str): the message to display.
default: the default value to return if the user
leaves the field empty
convert (callable): a callable to be used to convert
the value the user inserted. If None, the type of
... | def input_on_stderr(prompt='', default=None, convert=None):
"""Output a string to stderr and wait for input.
Args:
prompt (str): the message to display.
default: the default value to return if the user
leaves the field empty
convert (callable): a callable to be used to conve... |
Utility function to execute a subcommand.
The function will look up in the ``scope``
if there is a function called ``run_<parser.args.command>``
and will run it using ``parser.args`` as first positional argument.
Args:
parser: an ArgumentParser instance.
argv: the list of command line ... | def start(parser, argv, scope):
"""Utility function to execute a subcommand.
The function will look up in the ``scope``
if there is a function called ``run_<parser.args.command>``
and will run it using ``parser.args`` as first positional argument.
Args:
parser: an ArgumentParser instance.
... |
API endpoint to perform a text search on the assets.
Args:
search (str): Text search string to query the text index
limit (int, optional): Limit the number of returned documents.
Return:
A list of assets that match the query. | def get(self):
"""API endpoint to perform a text search on the assets.
Args:
search (str): Text search string to query the text index
limit (int, optional): Limit the number of returned documents.
Return:
A list of assets that match the query.
"""
... |
Initialize chain upon genesis or a migration | def init_chain(self, genesis):
"""Initialize chain upon genesis or a migration"""
app_hash = ''
height = 0
known_chain = self.bigchaindb.get_latest_abci_chain()
if known_chain is not None:
chain_id = known_chain['chain_id']
if known_chain['is_synced']:
... |
Return height of the latest committed block. | def info(self, request):
"""Return height of the latest committed block."""
self.abort_if_abci_chain_is_not_synced()
# Check if BigchainDB supports the Tendermint version
if not (hasattr(request, 'version') and tendermint_version_is_compatible(request.version)):
logger.erro... |
Validate the transaction before entry into
the mempool.
Args:
raw_tx: a raw string (in bytes) transaction. | def check_tx(self, raw_transaction):
"""Validate the transaction before entry into
the mempool.
Args:
raw_tx: a raw string (in bytes) transaction.
"""
self.abort_if_abci_chain_is_not_synced()
logger.debug('check_tx: %s', raw_transaction)
transaction... |
Initialize list of transaction.
Args:
req_begin_block: block object which contains block header
and block hash. | def begin_block(self, req_begin_block):
"""Initialize list of transaction.
Args:
req_begin_block: block object which contains block header
and block hash.
"""
self.abort_if_abci_chain_is_not_synced()
chain_shift = 0 if self.chain is None else self.chain['... |
Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction. | def deliver_tx(self, raw_transaction):
"""Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction.
"""
self.abort_if_abci_chain_is_not_synced()
logger.debug('deliver_tx: %s', raw_transaction)
transaction = self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.