INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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 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...
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, ...
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 ).
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.
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.
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.
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.
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.
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.
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.
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.
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 }.
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 dataset of the requested size.
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.
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.
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.
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.
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.
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 ...
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&#8230;" data = data.encode("ascii", "xmlcharrefreplace").decode("ascii") ...
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...
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)
Perform some basic checks to see whether the indicated file could be a valid distribution file.
def _is_valid_dist_file(filename, filetype): """ Perform some basic checks to see whether the indicated file could be a valid distribution file. """ # If our file is a zipfile, then ensure that it's members are only # compressed with supported compression methods. if zipfile.is_zipfile(file...
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.
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!
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.
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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....
Calculate block hash using transaction ids and previous block hash to be stored in the next block.
def end_block(self, request_end_block): """Calculate block hash using transaction ids and previous block hash to be stored in the next block. Args: height (int): new height of the chain. """ self.abort_if_abci_chain_is_not_synced() chain_shift = 0 if self.c...
Store the new height and along with block hash.
def commit(self): """Store the new height and along with block hash.""" self.abort_if_abci_chain_is_not_synced() data = self.block_txn_hash.encode('utf-8') # register a new block only when new transactions are received if self.block_txn_ids: self.bigchaindb.store_b...
For more details refer BEP - 21: https:// github. com/ bigchaindb/ BEPs/ tree/ master/ 21
def validate(self, bigchain, current_transactions=[]): """For more details refer BEP-21: https://github.com/bigchaindb/BEPs/tree/master/21 """ current_validators = self.get_validators(bigchain) super(ValidatorElection, self).validate(bigchain, current_transactions=current_transactions)...
Create a new queue for a specific combination of event types and return it.
def get_subscriber_queue(self, event_types=None): """Create a new queue for a specific combination of event types and return it. Returns: a :class:`multiprocessing.Queue`. Raises: RuntimeError if called after `run` """ try: self.start...
Given an event send it to all the subscribers.
def dispatch(self, event): """Given an event, send it to all the subscribers. Args event (:class:`~bigchaindb.events.EventTypes`): the event to dispatch to all the subscribers. """ for event_types, queues in self.queues.items(): if event.type & e...
Start the exchange
def run(self): """Start the exchange""" self.started_queue.put('STARTED') while True: event = self.publisher_queue.get() if event == POISON_PILL: return else: self.dispatch(event)
Initialize the configured backend for use with BigchainDB.
def init_database(connection=None, dbname=None): """Initialize the configured backend for use with BigchainDB. Creates a database with :attr:`dbname` with any required tables and supporting indexes. Args: connection (:class:`~bigchaindb.backend.connection.Connection`): an existing ...
Validate all nested language key in obj.
def validate_language_key(obj, key): """Validate all nested "language" key in `obj`. Args: obj (dict): dictionary whose "language" key is to be validated. Returns: None: validation successful Raises: ValidationError: will raise exception in case language is...
API endpoint to get details about a block.
def get(self, block_id): """API endpoint to get details about a block. Args: block_id (str): the id of the block. Return: A JSON string containing the data about the block. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain:...
API endpoint to get the related blocks for a transaction.
def get(self): """API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided". """ p...
Generate base58 encode public - private key pair from a hex encoded private key
def key_pair_from_ed25519_key(hex_private_key): """Generate base58 encode public-private key pair from a hex encoded private key""" priv_key = crypto.Ed25519SigningKey(bytes.fromhex(hex_private_key)[:32], encoding='bytes') public_key = priv_key.get_verifying_key() return CryptoKeypair(private_key=priv_k...
Generate base58 public key from hex encoded public key
def public_key_from_ed25519_key(hex_public_key): """Generate base58 public key from hex encoded public key""" public_key = crypto.Ed25519VerifyingKey(bytes.fromhex(hex_public_key), encoding='bytes') return public_key.encode(encoding='base58').decode('utf-8')
Encode a fulfillment as a details dictionary
def _fulfillment_to_details(fulfillment): """Encode a fulfillment as a details dictionary Args: fulfillment: Crypto-conditions Fulfillment object """ if fulfillment.type_name == 'ed25519-sha-256': return { 'type': 'ed25519-sha-256', 'public_key': base58.b58encod...
Load a fulfillment for a signing spec dictionary
def _fulfillment_from_details(data, _depth=0): """Load a fulfillment for a signing spec dictionary Args: data: tx.output[].condition.details dictionary """ if _depth == 100: raise ThresholdTooDeep() if data['type'] == 'ed25519-sha-256': public_key = base58.b58decode(data['p...
Transforms the object to a Python dictionary.
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 a Python dictionary to an Input object.
def from_dict(cls, data): """Transforms a Python dictionary to an Input object. Note: Optionally, this method can also serialize a Cryptoconditions- Fulfillment that is not yet signed. Args: data (dict): The Input to be transformed. ...
Transforms the object to a Python dictionary.
def to_dict(self): """Transforms the object to a Python dictionary. Returns: (dict|None): The link as an alternative serialization format. """ if self.txid is None and self.output is None: return None else: return { 'tr...
Transforms the object to a Python dictionary.
def to_dict(self): """Transforms the object to a Python dictionary. Note: A dictionary serialization of the Input the Output was derived from is always provided. Returns: dict: The Output as an alternative serialization format. ""...