INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
The database state created by this fixture is equivalent to the following operations using arctic 1.40
or previous:
arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month')
library = arctic.get_library('arctic_test.TEST')
df = pd.DataFrame([[1,2], [3,4]], index=['x','... | def multicolumn_store_with_uncompressed_write(mongo_server):
"""
The database state created by this fixture is equivalent to the following operations using arctic 1.40
or previous:
arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month')
library = arctic.get_library('... |
The database state created by this fixture is equivalent to the following operations using arctic 1.40
or previous:
arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month')
library = arctic.get_library('arctic_test.TEST')
arr = np.arange(2).astype([('abc', 'int64')])
... | def ndarray_store_with_uncompressed_write(mongo_server):
"""
The database state created by this fixture is equivalent to the following operations using arctic 1.40
or previous:
arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month')
library = arctic.get_library('arct... |
Return the symbols in this library.
Parameters
----------
all_symbols : `bool`
If True returns all symbols under all snapshots, even if the symbol has been deleted
in the current version (i.e. it exists under a snapshot... Default: False
snapshot : `str`
... | def list_symbols(self, all_symbols=False, snapshot=None, regex=None, **kwargs):
"""
Return the symbols in this library.
Parameters
----------
all_symbols : `bool`
If True returns all symbols under all snapshots, even if the symbol has been deleted
in the ... |
Return True if the 'symbol' exists in this library AND the symbol
isn't deleted in the specified as_of.
It's possible for a deleted symbol to exist in older snapshots.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `dat... | def has_symbol(self, symbol, as_of=None):
"""
Return True if the 'symbol' exists in this library AND the symbol
isn't deleted in the specified as_of.
It's possible for a deleted symbol to exist in older snapshots.
Parameters
----------
symbol : `str`
... |
Return the audit log associated with a given symbol
Parameters
----------
symbol : `str`
symbol name for the item | def read_audit_log(self, symbol=None, message=None):
"""
Return the audit log associated with a given symbol
Parameters
----------
symbol : `str`
symbol name for the item
"""
query = {}
if symbol:
if isinstance(symbol, six.string_t... |
Return a list of versions filtered by the passed in parameters.
Parameters
----------
symbol : `str`
Symbol to return versions for. If None returns versions across all
symbols in the library.
snapshot : `str`
Return the versions contained in the name... | def list_versions(self, symbol=None, snapshot=None, latest_only=False):
"""
Return a list of versions filtered by the passed in parameters.
Parameters
----------
symbol : `str`
Symbol to return versions for. If None returns versions across all
symbols in... |
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or `int` or `datetime.datetime`
Return the data as it was a... | def read(self, symbol, as_of=None, date_range=None, from_version=None, allow_secondary=None, **kwargs):
"""
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
... |
Reads and returns information about the data stored for symbol
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of the point in time.
`int` : specific version number... | def get_info(self, symbol, as_of=None):
"""
Reads and returns information about the data stored for symbol
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of th... |
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was a... | def get_arctic_version(self, symbol, as_of=None):
"""
Return the numerical representation of the arctic version used to write the last (or as_of) version for
the given symbol.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str`... |
Return the metadata saved for a symbol. This method is fast as it doesn't
actually load the data.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of the point in time.... | def read_metadata(self, symbol, as_of=None, allow_secondary=None):
"""
Return the metadata saved for a symbol. This method is fast as it doesn't
actually load the data.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or in... |
Append 'data' under the specified 'symbol' name to this library.
The exact meaning of 'append' is left up to the underlying store implementation.
Parameters
----------
symbol : `str`
symbol name for the item
data :
to be persisted
metadata : `dict... | def append(self, symbol, data, metadata=None, prune_previous_version=True, upsert=True, **kwargs):
"""
Append 'data' under the specified 'symbol' name to this library.
The exact meaning of 'append' is left up to the underlying store implementation.
Parameters
----------
... |
Write 'data' under the specified 'symbol' name to this library.
Parameters
----------
symbol : `str`
symbol name for the item
data :
to be persisted
metadata : `dict`
an optional dictionary of metadata to persist along with the symbol.
... | def write(self, symbol, data, metadata=None, prune_previous_version=True, **kwargs):
"""
Write 'data' under the specified 'symbol' name to this library.
Parameters
----------
symbol : `str`
symbol name for the item
data :
to be persisted
m... |
Write 'metadata' under the specified 'symbol' name to this library.
The data will remain unchanged. A new version will be created.
If the symbol is missing, it causes a write with empty data (None, pickled, can't append)
and the supplied metadata.
Returns a VersionedItem object only with... | def write_metadata(self, symbol, metadata, prune_previous_version=True, **kwargs):
"""
Write 'metadata' under the specified 'symbol' name to this library.
The data will remain unchanged. A new version will be created.
If the symbol is missing, it causes a write with empty data (None, pic... |
Restore the specified 'symbol' data and metadata to the state of a given version/snapshot/date.
Returns a VersionedItem object only with a metadata element.
Fast operation: Zero data/segment read/write operations.
Parameters
----------
symbol : `str`
symbol name for ... | def restore_version(self, symbol, as_of, prune_previous_version=True):
"""
Restore the specified 'symbol' data and metadata to the state of a given version/snapshot/date.
Returns a VersionedItem object only with a metadata element.
Fast operation: Zero data/segment read/write operations.... |
Find all non-snapshotted versions of a symbol that are older than a version that's at least keep_mins
minutes old.
Based on documents available on the secondary. | def _find_prunable_version_ids(self, symbol, keep_mins):
"""
Find all non-snapshotted versions of a symbol that are older than a version that's at least keep_mins
minutes old.
Based on documents available on the secondary.
"""
read_preference = ReadPreference.SECONDARY_P... |
Return all base_version_ids for a symbol that are not bases of version_ids | def _find_base_version_ids(self, symbol, version_ids):
"""
Return all base_version_ids for a symbol that are not bases of version_ids
"""
cursor = self._versions.find({'symbol': symbol,
'_id': {'$nin': version_ids},
... |
Prune versions, not pointed at by snapshots which are at least keep_mins old. Prune will never
remove all versions. | def _prune_previous_versions(self, symbol, keep_mins=120, keep_version=None, new_version_shas=None):
"""
Prune versions, not pointed at by snapshots which are at least keep_mins old. Prune will never
remove all versions.
"""
new_version_shas = new_version_shas if new_version_shas... |
Delete the n'th version of this symbol from the historical collection. | def _delete_version(self, symbol, version_num, do_cleanup=True):
"""
Delete the n'th version of this symbol from the historical collection.
"""
version = self._versions.find_one({'symbol': symbol, 'version': version_num})
if not version:
logger.error("Can't delete %s:... |
Delete all versions of the item from the current library which aren't
currently part of some snapshot.
Parameters
----------
symbol : `str`
symbol name to delete | def delete(self, symbol):
"""
Delete all versions of the item from the current library which aren't
currently part of some snapshot.
Parameters
----------
symbol : `str`
symbol name to delete
"""
logger.info("Deleting data item: %r from %r" % ... |
Creates an audit entry, which is much like a snapshot in that
it references versions and provides some history of the changes made. | def _write_audit(self, user, message, changed_version):
"""
Creates an audit entry, which is much like a snapshot in that
it references versions and provides some history of the changes made.
"""
audit = {'_id': bson.ObjectId(),
'user': user,
'me... |
Snapshot versions of symbols in the library. Can be used like:
Parameters
----------
snap_name : `str`
name of the snapshot
metadata : `dict`
an optional dictionary of metadata to persist along with the symbol.
skip_symbols : `collections.Iterable`
... | def snapshot(self, snap_name, metadata=None, skip_symbols=None, versions=None):
"""
Snapshot versions of symbols in the library. Can be used like:
Parameters
----------
snap_name : `str`
name of the snapshot
metadata : `dict`
an optional dictiona... |
Delete a named snapshot
Parameters
----------
symbol : `str`
The snapshot name to delete | def delete_snapshot(self, snap_name):
"""
Delete a named snapshot
Parameters
----------
symbol : `str`
The snapshot name to delete
"""
snapshot = self._snapshots.find_one({'name': snap_name})
if not snapshot:
raise NoDataFoundExcep... |
Return storage statistics about the library
Returns
-------
dictionary of storage stats | def stats(self):
"""
Return storage statistics about the library
Returns
-------
dictionary of storage stats
"""
res = {}
db = self._collection.database
conn = db.connection
res['sharding'] = {}
try:
sharding = conn.co... |
Run a consistency check on this VersionStore library. | def _fsck(self, dry_run):
"""
Run a consistency check on this VersionStore library.
"""
# Cleanup Orphaned Chunks
self._cleanup_orphaned_chunks(dry_run)
# Cleanup unreachable SHAs (forward pointers)
self._cleanup_unreachable_shas(dry_run)
# Cleanup Orphane... |
Fixes any chunks who have parent pointers to missing versions.
Removes the broken parent pointer and, if there are no other parent pointers for the chunk,
removes the chunk. | def _cleanup_orphaned_chunks(self, dry_run):
"""
Fixes any chunks who have parent pointers to missing versions.
Removes the broken parent pointer and, if there are no other parent pointers for the chunk,
removes the chunk.
"""
lib = self
chunks_coll = lib._collect... |
Fixes any versions who have parent pointers to missing snapshots.
Note, doesn't delete the versions, just removes the parent pointer if it no longer
exists in snapshots. | def _cleanup_orphaned_versions(self, dry_run):
"""
Fixes any versions who have parent pointers to missing snapshots.
Note, doesn't delete the versions, just removes the parent pointer if it no longer
exists in snapshots.
"""
lib = self
versions_coll = lib._collect... |
Set the global multithread compression mode
Parameters
----------
mode: `bool`
True: Use parallel compression. False: Use sequential compression | def enable_parallel_lz4(mode):
"""
Set the global multithread compression mode
Parameters
----------
mode: `bool`
True: Use parallel compression. False: Use sequential compression
"""
global ENABLE_PARALLEL
ENABLE_PARALLEL = bool(mode)
logger.info("Setting parallelis... |
Set the size of the compression workers thread pool.
If the pool is already created, it waits until all jobs are finished, and then proceeds with setting the new size.
Parameters
----------
pool_size : `int`
The size of the pool (must be a positive integer)
Returns
-------
... | def set_compression_pool_size(pool_size):
"""
Set the size of the compression workers thread pool.
If the pool is already created, it waits until all jobs are finished, and then proceeds with setting the new size.
Parameters
----------
pool_size : `int`
The size of the pool (mus... |
Compress an array of strings
Parameters
----------
str_list: `list[str]`
The input list of strings which need to be compressed.
withHC: `bool`
This flag controls whether lz4HC will be used.
Returns
-------
`list[str`
The list of the compressed strings. | def compress_array(str_list, withHC=LZ4_HIGH_COMPRESSION):
"""
Compress an array of strings
Parameters
----------
str_list: `list[str]`
The input list of strings which need to be compressed.
withHC: `bool`
This flag controls whether lz4HC will be used.
Retur... |
Decompress a list of strings | def decompress_array(str_list):
"""
Decompress a list of strings
"""
global _compress_thread_pool
if not str_list:
return str_list
if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL:
return [lz4_decompress(chunk) for chunk in str_list]
if _compress_thread_pool is No... |
Equivalent to numpy.split(array_2d, slices),
but avoids fancy indexing | def _split_arrs(array_2d, slices):
"""
Equivalent to numpy.split(array_2d, slices),
but avoids fancy indexing
"""
if len(array_2d) == 0:
return np.empty(0, dtype=np.object)
rtn = np.empty(len(slices) + 1, dtype=np.object)
start = 0
for i, s in enumerate(slices):
rtn[i] =... |
Checksum the passed in dictionary | def checksum(symbol, doc):
"""
Checksum the passed in dictionary
"""
sha = hashlib.sha1()
sha.update(symbol.encode('ascii'))
for k in sorted(iter(doc.keys()), reverse=True):
v = doc[k]
if isinstance(v, six.binary_type):
sha.update(doc[k])
else:
sha... |
Helper method for cleaning up chunks from a version store | def cleanup(arctic_lib, symbol, version_ids, versions_coll, shas_to_delete=None, pointers_cfgs=None):
"""
Helper method for cleaning up chunks from a version store
"""
pointers_cfgs = set(pointers_cfgs) if pointers_cfgs else set()
collection = arctic_lib.get_top_level_collection()
version_ids = ... |
Factory function to initialise the correct Pickle load function based on
the Pandas version. | def _define_compat_pickle_load():
"""Factory function to initialise the correct Pickle load function based on
the Pandas version.
"""
if pd.__version__.startswith("0.14"):
return pickle.load
return functools.partial(pickle_compat.load, compat=True) |
This is a utility function to produce text output with details about the versions of a given symbol.
It is useful for debugging corruption issues and to mark corrupted versions.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
The VersionStore instance against which the analys... | def analyze_symbol(l, sym, from_ver, to_ver, do_reads=False):
"""
This is a utility function to produce text output with details about the versions of a given symbol.
It is useful for debugging corruption issues and to mark corrupted versions.
Parameters
----------
l : `arctic.store.version_stor... |
This method hints whether the symbol/version are safe for appending in two ways:
1. It verifies whether the symbol is already corrupted (fast, doesn't read the data)
2. It verififes that the symbol is safe to append, i.e. there are no subsequent appends,
or dangling segments from a failed append.
Par... | def is_safe_to_append(l, sym, input_v):
"""
This method hints whether the symbol/version are safe for appending in two ways:
1. It verifies whether the symbol is already corrupted (fast, doesn't read the data)
2. It verififes that the symbol is safe to append, i.e. there are no subsequent appends,
... |
This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
The VersionStore instance against which ... | def is_corrupted(l, sym, input_v):
"""
This method can be used to check for a corrupted version.
Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption.
Parameters
----------
l : `arctic.store.version_store.VersionStore`
... |
Converts object arrays of strings to numpy string arrays | def _convert_types(self, a):
"""
Converts object arrays of strings to numpy string arrays
"""
# No conversion for scalar type
if a.dtype != 'object':
return a, None
# We can't infer the type of an empty array, so just
# assume strings
if len(a... |
Convert a Pandas DataFrame to SON.
Parameters
----------
df: DataFrame
The Pandas DataFrame to encode | def docify(self, df):
"""
Convert a Pandas DataFrame to SON.
Parameters
----------
df: DataFrame
The Pandas DataFrame to encode
"""
dtypes = {}
masks = {}
lengths = {}
columns = []
data = Binary(b'')
start = 0
... |
Decode a Pymongo SON object into an Pandas DataFrame | def objify(self, doc, columns=None):
"""
Decode a Pymongo SON object into an Pandas DataFrame
"""
cols = columns or doc[METADATA][COLUMNS]
data = {}
for col in cols:
# if there is missing data in a chunk, we can default to NaN
# and pandas will au... |
Deserializes SON to a DataFrame
Parameters
----------
data: SON data
columns: None, or list of strings
optionally you can deserialize a subset of the data in the SON. Index
columns are ALWAYS deserialized, and should not be specified
Returns
----... | def deserialize(self, data, columns=None):
"""
Deserializes SON to a DataFrame
Parameters
----------
data: SON data
columns: None, or list of strings
optionally you can deserialize a subset of the data in the SON. Index
columns are ALWAYS deserial... |
Create and initialize the keybinding manager.
:type get_fuzzy_match: callable
:param get_fuzzy_match: Gets the fuzzy matching config.
:type set_fuzzy_match: callable
:param set_fuzzy_match: Sets the fuzzy matching config.
:type get_enable_vi_bindings: callable
:param g... | def _create_key_manager(self, get_match_fuzzy, set_match_fuzzy,
get_enable_vi_bindings, set_enable_vi_bindings,
get_show_completion_columns,
set_show_completion_columns,
get_show_help, set_show_help,
... |
Describe operation and args needed for server side completion.
:type service: str
:param service: The AWS service name.
:type operation: str
:param operation: The AWS operation name.
:type param: str
:param param: The name of the parameter being completed. This must
... | def describe_autocomplete(self, service, operation, param):
"""Describe operation and args needed for server side completion.
:type service: str
:param service: The AWS service name.
:type operation: str
:param operation: The AWS operation name.
:type param: str
... |
Create a CompleterDescriber for a service.
:type service_name: str
:param service_name: The name of the service, e.g. 'ec2'
:return: A CompleterDescriber object. | def create_completer_query(self, service_name):
"""Create a CompleterDescriber for a service.
:type service_name: str
:param service_name: The name of the service, e.g. 'ec2'
:return: A CompleterDescriber object.
"""
if service_name not in self._describer_cache:
... |
Retrieve server side completions.
:type service: str
:param service: The service name, e.g. 'ec2', 'iam'.
:type operation: str
:param operation: The operation name, in the casing
used by the CLI (words separated by hyphens), e.g.
'describe-instances', 'delete-us... | def retrieve_candidate_values(self, service, operation, param):
"""Retrieve server side completions.
:type service: str
:param service: The service name, e.g. 'ec2', 'iam'.
:type operation: str
:param operation: The operation name, in the casing
used by the CLI (wor... |
Convert restructured text to basic text output.
This function removes most of the decorations added
in restructured text.
This function is used to generate documentation we
can show to users in a cross platform manner.
Basic indentation and list formatting are kept,
but many RST features are ... | def convert_rst_to_basic_text(contents):
"""Convert restructured text to basic text output.
This function removes most of the decorations added
in restructured text.
This function is used to generate documentation we
can show to users in a cross platform manner.
Basic indentation and list for... |
Read the config file if it exists, else read the default config.
Creates the user config file if it doesn't exist using the template.
:type config_template: str
:param config_template: The config template file name.
:type config_file: str
:param config_file: (Optional) The con... | def load(self, config_template, config_file=None):
"""Read the config file if it exists, else read the default config.
Creates the user config file if it doesn't exist using the template.
:type config_template: str
:param config_template: The config template file name.
:type c... |
Load the config file if it exists, else read the default config.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file path.
:rtype: :class:`configobj.ConfigObj`
:return: The conf... | def _load_template_or_config(self, template_path, config_path):
"""Load the config file if it exists, else read the default config.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file pa... |
Write the default config from a template.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path: The user's config file path.
:type overwrite: bool
:param overwrite: (Optional) Determines whether to over... | def _copy_template_to_config(self, template_path,
config_path, overwrite=False):
"""Write the default config from a template.
:type template_path: str
:param template_path: The template config file path.
:type config_path: str
:param config_path... |
Retrieve the specified pygments style.
If the specified style is not found, the vim style is returned.
:type style_name: str
:param style_name: The pygments style name.
:rtype: :class:`pygments.style.StyleMeta`
:return: Pygments style info. | def style_factory(self, style_name):
"""Retrieve the specified pygments style.
If the specified style is not found, the vim style is returned.
:type style_name: str
:param style_name: The pygments style name.
:rtype: :class:`pygments.style.StyleMeta`
:return: Pygments ... |
Change the profile used for server side completions. | def change_profile(self, profile_name):
"""Change the profile used for server side completions."""
self._server_side_completer = self._create_server_side_completer(
session=botocore.session.Session(profile=profile_name)) |
Given a line, return a list of suggestions. | def autocomplete(self, line):
"""Given a line, return a list of suggestions."""
current_length = len(line)
self._current_line = line
if current_length == 1 and self._last_position > 1:
# Reset state. This is likely from a user completing
# a previous command.
... |
Get or set the profile.
If .profile is called with no args, the current profile
is displayed. If the .profile command is called with a
single arg, then the current profile for the application
will be set to the new value. | def run(self, command, application):
"""Get or set the profile.
If .profile is called with no args, the current profile
is displayed. If the .profile command is called with a
single arg, then the current profile for the application
will be set to the new value.
"""
... |
Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application object. | def handle_cmd(self, command, application):
"""Handle running a given dot command from a user.
:type command: str
:param command: The full dot command string, e.g. ``.edit``,
of ``.profile prod``.
:type application: AWSShell
:param application: The application objec... |
Load the config from the config file or template. | def load_config(self):
"""Load the config from the config file or template."""
config = Config()
self.config_obj = config.load('awsshellrc')
self.config_section = self.config_obj['aws-shell']
self.model_completer.match_fuzzy = self.config_section.as_bool(
'match_fuzzy... |
Save the config to the config file. | def save_config(self):
"""Save the config to the config file."""
self.config_section['match_fuzzy'] = self.model_completer.match_fuzzy
self.config_section['enable_vi_bindings'] = self.enable_vi_bindings
self.config_section['show_completion_columns'] = \
self.show_completion_c... |
Create the :class:`KeyManager`.
The inputs to KeyManager are expected to be callable, so we can't
use the standard @property and @attrib.setter for these attributes.
Lambdas cannot contain assignments so we're forced to define setters.
:rtype: :class:`KeyManager`
:return: A Key... | def create_key_manager(self):
"""Create the :class:`KeyManager`.
The inputs to KeyManager are expected to be callable, so we can't
use the standard @property and @attrib.setter for these attributes.
Lambdas cannot contain assignments so we're forced to define setters.
:rtype: :... |
Calculate how well the search string matches the word. | def calculate_score(search_string, word):
"""Calculate how well the search string matches the word."""
# See the module docstring for a high level description
# of what we're trying to do.
# * If the search string is larger than the word, we know
# immediately that this can't be a match.
if le... |
Find all matches in the `collection` for the specified `word`.
If `word` is empty, returns all items in `collection`.
:type word: str
:param word: The substring to search for.
:type collection: collection, usually a list
:param collection: A collection of words to match.
:rtype: list of stri... | def substring_search(word, collection):
"""Find all matches in the `collection` for the specified `word`.
If `word` is empty, returns all items in `collection`.
:type word: str
:param word: The substring to search for.
:type collection: collection, usually a list
:param collection: A collecti... |
Create the toolbar handler.
:type get_fuzzy_match: callable
:param fuzzy_match: Gets the fuzzy matching config.
:type get_enable_vi_bindings: callable
:param get_enable_vi_bindings: Gets the vi (or emacs) key bindings
config.
:type get_show_completion_columns: call... | def _create_toolbar_handler(self, get_match_fuzzy, get_enable_vi_bindings,
get_show_completion_columns, get_show_help):
"""Create the toolbar handler.
:type get_fuzzy_match: callable
:param fuzzy_match: Gets the fuzzy matching config.
:type get_enable_vi... |
Generate default layout.
Returns a ``Layout`` instance.
:param message: Text to be used as prompt.
:param lexer: Lexer to be used for the highlighting.
:param is_password: `bool` or `CLIFilter`. When True, display input as '*'.
:param reserve_space_for_menu: When True, make sure that a minimal hei... | def create_default_layout(app, message='',
lexer=None, is_password=False,
reserve_space_for_menu=False,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
display_completions_in_columns... |
Cross platform temporary file creation.
This is an alternative to ``tempfile.NamedTemporaryFile`` that
also works on windows and avoids the "file being used by
another process" error. | def temporary_file(mode):
"""Cross platform temporary file creation.
This is an alternative to ``tempfile.NamedTemporaryFile`` that
also works on windows and avoids the "file being used by
another process" error.
"""
tempdir = tempfile.gettempdir()
basename = 'tmpfile-%s' % (uuid.uuid4())
... |
Return the file for a given filename.
If you want binary content use ``mode='rb'``. | def file_contents(self, filename, binary=False):
"""Return the file for a given filename.
If you want binary content use ``mode='rb'``.
"""
if binary:
mode = 'rb'
else:
mode = 'r'
try:
with open(filename, mode) as f:
r... |
Load the completion index for a given CLI version.
:type version_string: str
:param version_string: The AWS CLI version, e.g "1.9.2".
:raises: :class:`IndexLoadError <exceptions.IndexLoadError>` | def load_index(self, version_string):
"""Load the completion index for a given CLI version.
:type version_string: str
:param version_string: The AWS CLI version, e.g "1.9.2".
:raises: :class:`IndexLoadError <exceptions.IndexLoadError>`
"""
filename = self._filename_for_... |
Load completions from the completion index.
Updates the following attributes:
* commands
* subcommands
* global_opts
* args_opts | def load_completions(self):
"""Load completions from the completion index.
Updates the following attributes:
* commands
* subcommands
* global_opts
* args_opts
"""
try:
index_str = self.load_index(utils.AWSCLI_VERSION)
... |
Decrypt a block of cipher text using the AES block cipher. | def decrypt(self, ciphertext):
'Decrypt a block of cipher text using the AES block cipher.'
if len(ciphertext) != 16:
raise ValueError('wrong block length')
rounds = len(self._Kd) - 1
(s1, s2, s3) = [3, 2, 1]
a = [0, 0, 0, 0]
# Convert ciphertext to (ints ^... |
Increment the counter (overflow rolls back to 0). | def increment(self):
'''Increment the counter (overflow rolls back to 0).'''
for i in xrange(len(self._counter) - 1, -1, -1):
self._counter[i] += 1
if self._counter[i] < 256: break
# Carry the one
self._counter[i] = 0
# Overflow
else:
... |
Dump raw efuse data registers | def dump(esp, _efuses, args):
""" Dump raw efuse data registers """
for block in range(len(EFUSE_BLOCK_OFFS)):
print("EFUSE block %d:" % block)
offsets = [x + EFUSE_BLOCK_OFFS[block] for x in range(EFUSE_BLOCK_LEN[block])]
print(" ".join(["%08x" % esp.read_efuse(offs) for offs in offsets... |
Print a human-readable summary of efuse contents | def summary(esp, efuses, args):
""" Print a human-readable summary of efuse contents """
ROW_FORMAT = "%-22s %-50s%s= %s %s %s"
print(ROW_FORMAT.replace("-50", "-12") % ("EFUSE_NAME", "Description", "", "[Meaningful Value]", "[Readable/Writeable]", "(Hex Value)"))
print("-" * 88)
for category in set... |
Write the values in the efuse write registers to
the efuse hardware, then refresh the efuse read registers. | def write_efuses(self):
""" Write the values in the efuse write registers to
the efuse hardware, then refresh the efuse read registers.
"""
# Configure clock
apb_freq = self._esp.get_crystal_freq()
clk_sel0, clk_sel1, dac_clk_div = EFUSE_CLK_SETTINGS[apb_freq]
s... |
Return the raw (unformatted) numeric value of the efuse bits
Returns a simple integer or (for some subclasses) a bitstring. | def get_raw(self):
""" Return the raw (unformatted) numeric value of the efuse bits
Returns a simple integer or (for some subclasses) a bitstring.
"""
value = self.parent.read_efuse(self.data_reg_offs)
return (value & self.mask) >> self.shift |
Return true if the efuse is readable by software | def is_readable(self):
""" Return true if the efuse is readable by software """
if self.read_disable_bit is None:
return True # read cannot be disabled
value = (self.parent.read_efuse(0) >> 16) & 0xF # RD_DIS values
return (value & (1 << self.read_disable_bit)) == 0 |
This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00. | def calc_crc(raw_mac):
"""
This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00.
"""
result = 0x00
for b in struct.unpack("B" * 6, raw_mac):
result ^= b
for _ in rang... |
Takes 24 byte sequence to be represented in 3/4 encoding,
returns 8 words suitable for writing "encoded" to an efuse block | def apply_34_encoding(self, inbits):
""" Takes 24 byte sequence to be represented in 3/4 encoding,
returns 8 words suitable for writing "encoded" to an efuse block
"""
def popcnt(b):
""" Return number of "1" bits set in 'b' """
return len([x for x in bin(b) if... |
Is the point (x,y) on this curve? | def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 |
Return a new point that is twice the old. | def double( self ):
"""Return a new point that is twice the old."""
if self == INFINITY:
return INFINITY
# X9.62 B.3:
p = self.__curve.p()
a = self.__curve.a()
l = ( ( 3 * self.__x * self.__x + a ) * \
numbertheory.inverse_mod( 2 * self.__y, p ) ) % p
x3 = ( l * l - 2 * ... |
Scales timeouts which are size-specific | def timeout_per_mb(seconds_per_mb, size_bytes):
""" Scales timeouts which are size-specific """
result = seconds_per_mb * (size_bytes / 1e6)
if result < DEFAULT_TIMEOUT:
return DEFAULT_TIMEOUT
return result |
Decorator implementation that wraps a check around an ESPLoader
bootloader function to check if it's supported.
This is used to capture the multidimensional differences in
functionality between the ESP8266 & ESP32 ROM loaders, and the
software stub that runs on both. Not possible to do this cleanly
... | def check_supported_function(func, check_func):
"""
Decorator implementation that wraps a check around an ESPLoader
bootloader function to check if it's supported.
This is used to capture the multidimensional differences in
functionality between the ESP8266 & ESP32 ROM loaders, and the
software... |
Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2). | def LoadFirmwareImage(chip, filename):
""" Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwa... |
Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems. | def slip_reader(port, trace_function):
"""Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems.
"""
partial_packet = None
... |
Align the position in the file to the next block of specified size | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) |
Given a flash size of the type passed in args.flash_size
(ie 512KB or 1MB) then return the size in bytes. | def flash_size_bytes(size):
""" Given a flash size of the type passed in args.flash_size
(ie 512KB or 1MB) then return the size in bytes.
"""
if "MB" in size:
return int(size[:size.index("MB")]) * 1024 * 1024
elif "KB" in size:
return int(size[:size.index("KB")]) * 1024
else:
... |
Pad to the next alignment boundary | def pad_to(data, alignment, pad_character=b'\xFF'):
""" Pad to the next alignment boundary """
pad_mod = len(data) % alignment
if pad_mod != 0:
data += pad_character * (alignment - pad_mod)
return data |
Modify the flash mode & size bytes if this looks like an executable bootloader image | def _update_image_flash_params(esp, address, args, image):
""" Modify the flash mode & size bytes if this looks like an executable bootloader image """
if len(image) < 8:
return image # not long enough to be a bootloader image
# unpack the (potential) image header
magic, _, flash_mode, flash_... |
Main function for esptool
custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
becomes ['-b', '115200']. | def main(custom_commandline=None):
"""
Main function for esptool
custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
... |
Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line. | def expand_file_arguments():
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
expanded = False
... |
Use serial access to detect the chip type.
We use the UART's datecode register for this, it's mapped at
the same address on ESP8266 & ESP32 so we can use one
memory read and compare to the datecode register for each chip
type.
This routine automatically performs ESPLoader.conne... | def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False):
""" Use serial access to detect the chip type.
We use the UART's datecode register for this, it's mapped at
the same address on ESP8266 & ESP32 so we can use one
memory read and com... |
Execute a command with 'command', check the result code and throw an appropriate
FatalError if it fails.
Returns the "result" of a successful command. | def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT):
"""
Execute a command with 'command', check the result code and throw an appropriate
FatalError if it fails.
Returns the "result" of a successful command.
"""
val, data = self.com... |
A single connection attempt, with esp32r0 workaround options | def _connect_attempt(self, mode='default_reset', esp32r0_delay=False):
""" A single connection attempt, with esp32r0 workaround options """
# esp32r0_delay is a workaround for bugs with the most common auto reset
# circuit and Windows, if the EN pin on the dev board does not have
# enoug... |
Try connecting repeatedly until successful, or giving up | def connect(self, mode='default_reset'):
""" Try connecting repeatedly until successful, or giving up """
print('Connecting...', end='')
sys.stdout.flush()
last_error = None
try:
for _ in range(7):
last_error = self._connect_attempt(mode=mode, esp32r0... |
Read memory address in target | def read_reg(self, addr):
""" Read memory address in target """
# we don't call check_command here because read_reg() function is called
# when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
# for different chip types (!)
val, data = self... |
Write to memory address in target
Note: mask option is not supported by stub loaders, use update_reg() function. | def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0):
""" Write to memory address in target
Note: mask option is not supported by stub loaders, use update_reg() function.
"""
return self.check_command("write target memory", self.ESP_WRITE_REG,
... |
Update register at 'addr', replace the bits masked out by 'mask'
with new_val. new_val is shifted left to match the LSB of 'mask'
Returns just-written value of register. | def update_reg(self, addr, mask, new_val):
""" Update register at 'addr', replace the bits masked out by 'mask'
with new_val. new_val is shifted left to match the LSB of 'mask'
Returns just-written value of register.
"""
shift = _mask_to_shift(mask)
val = self.read_reg(a... |
Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write. | def flash_defl_begin(self, size, compsize, offset):
""" Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
"""
num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
erase_blocks = ... |
Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash_begin, ESP32 ROM
has it as a SPI command. | def flash_spi_attach(self, hspi_arg):
"""Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash_begin, ESP32 ROM
has it as a SPI command.
"""
# last 3 bytes in ESP_SPI_ATTACH argument are reserved values
arg = struct.pack('<I', hsp... |
Tell the ESP bootloader the parameters of the chip
Corresponds to the "flashchip" data structure that the ROM
has in RAM.
'size' is in bytes.
All other flash parameters are currently hardcoded (on ESP8266
these are mostly ignored by ROM code, on ESP32 I'm not sure.) | def flash_set_parameters(self, size):
"""Tell the ESP bootloader the parameters of the chip
Corresponds to the "flashchip" data structure that the ROM
has in RAM.
'size' is in bytes.
All other flash parameters are currently hardcoded (on ESP8266
these are mostly ignore... |
Run an arbitrary SPI flash command.
This function uses the "USR_COMMAND" functionality in the ESP
SPI hardware, rather than the precanned commands supported by
hardware. So the value of spiflash_command is an actual command
byte, sent over the wire.
After writing command byte, ... | def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0):
"""Run an arbitrary SPI flash command.
This function uses the "USR_COMMAND" functionality in the ESP
SPI hardware, rather than the precanned commands supported by
hardware. So the value of spiflash_command is an ac... |
Read up to 24 bits (num_bytes) of SPI flash status register contents
via RDSR, RDSR2, RDSR3 commands
Not all SPI flash supports all three commands. The upper 1 or 2
bytes may be 0xFF. | def read_status(self, num_bytes=2):
"""Read up to 24 bits (num_bytes) of SPI flash status register contents
via RDSR, RDSR2, RDSR3 commands
Not all SPI flash supports all three commands. The upper 1 or 2
bytes may be 0xFF.
"""
SPIFLASH_RDSR = 0x05
SPIFLASH_RDSR2... |
Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
bytes, esptool also sends a 16-byte WRSR command (as some
flash types use ... | def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
"""Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
... |
Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function | def chip_id(self):
""" Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """
id0 = self.read_reg(self.ESP_OTP_MAC0)
id1 = self.read_reg(self.ESP_OTP_MAC1)
return (id0 >> 24) | ((id1 & MAX_UINT24) << 8) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.