repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
tableau/document-api-python | tableaudocumentapi/connection.py | Connection.username | python | def username(self, value):
self._username = value
self._connectionXML.set('username', value) | Set the connection's username property.
Args:
value: New username value. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L91-L103 | null | class Connection(object):
"""A class representing connections inside Data Sources."""
def __init__(self, connxml):
"""Connection is usually instantiated by passing in connection elements
in a Data Source. If creating a connection from scratch you can call
`from_attributes` passing in th... |
tableau/document-api-python | tableaudocumentapi/connection.py | Connection.dbclass | python | def dbclass(self, value):
if not is_valid_dbclass(value):
raise AttributeError("'{}' is not a valid database type".format(value))
self._class = value
self._connectionXML.set('class', value) | Set the connection's dbclass property.
Args:
value: New dbclass value. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L116-L130 | [
"def is_valid_dbclass(dbclass):\n return dbclass in KNOWN_DB_CLASSES\n"
] | class Connection(object):
"""A class representing connections inside Data Sources."""
def __init__(self, connxml):
"""Connection is usually instantiated by passing in connection elements
in a Data Source. If creating a connection from scratch you can call
`from_attributes` passing in th... |
tableau/document-api-python | tableaudocumentapi/connection.py | Connection.port | python | def port(self, value):
self._port = value
# If port is None we remove the element and don't write it to XML
if value is None:
try:
del self._connectionXML.attrib['port']
except KeyError:
pass
else:
self._connectionXML.s... | Set the connection's port property.
Args:
value: New port value. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L138-L156 | null | class Connection(object):
"""A class representing connections inside Data Sources."""
def __init__(self, connxml):
"""Connection is usually instantiated by passing in connection elements
in a Data Source. If creating a connection from scratch you can call
`from_attributes` passing in th... |
tableau/document-api-python | tableaudocumentapi/connection.py | Connection.query_band | python | def query_band(self, value):
self._query_band = value
# If query band is None we remove the element and don't write it to XML
if value is None:
try:
del self._connectionXML.attrib['query-band-spec']
except KeyError:
pass
else:
... | Set the connection's query_band property.
Args:
value: New query_band value. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L164-L182 | null | class Connection(object):
"""A class representing connections inside Data Sources."""
def __init__(self, connxml):
"""Connection is usually instantiated by passing in connection elements
in a Data Source. If creating a connection from scratch you can call
`from_attributes` passing in th... |
tableau/document-api-python | tableaudocumentapi/connection.py | Connection.initial_sql | python | def initial_sql(self, value):
self._initial_sql = value
# If initial_sql is None we remove the element and don't write it to XML
if value is None:
try:
del self._connectionXML.attrib['one-time-sql']
except KeyError:
pass
else:
... | Set the connection's initial_sql property.
Args:
value: New initial_sql value. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/connection.py#L190-L208 | null | class Connection(object):
"""A class representing connections inside Data Sources."""
def __init__(self, connxml):
"""Connection is usually instantiated by passing in connection elements
in a Data Source. If creating a connection from scratch you can call
`from_attributes` passing in th... |
tableau/document-api-python | tableaudocumentapi/datasource.py | base36encode | python | def base36encode(number):
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(ALPHABET):
return sign + ALPHABET[number]
while number != 0:
number, i = divmod(number, len(ALPHA... | Converts an integer into a base36 string. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/datasource.py#L63-L82 | null | import collections
import itertools
import xml.etree.ElementTree as ET
import xml.sax.saxutils as sax
from uuid import uuid4
from tableaudocumentapi import Connection, xfile
from tableaudocumentapi import Field
from tableaudocumentapi.multilookup_dict import MultiLookupDict
from tableaudocumentapi.xfile import xml_ope... |
tableau/document-api-python | tableaudocumentapi/datasource.py | ConnectionParser.get_connections | python | def get_connections(self):
if float(self._dsversion) < 10:
connections = self._extract_legacy_connection()
else:
connections = self._extract_federated_connections()
return connections | Find and return all connections based on file format version. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/datasource.py#L108-L115 | null | class ConnectionParser(object):
"""Parser for detecting and extracting connections from differing Tableau file formats."""
def __init__(self, datasource_xml, version):
self._dsxml = datasource_xml
self._dsversion = version
def _extract_federated_connections(self):
connections = lis... |
tableau/document-api-python | tableaudocumentapi/datasource.py | Datasource.from_file | python | def from_file(cls, filename):
dsxml = xml_open(filename, 'datasource').getroot()
return cls(dsxml, filename) | Initialize datasource from file (.tds ot .tdsx) | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/datasource.py#L142-L146 | [
"def xml_open(filename, expected_root=None):\n \"\"\"Opens the provided 'filename'. Handles detecting if the file is an archive,\n detecting the document version, and validating the root tag.\"\"\"\n\n # Is the file a zip (.twbx or .tdsx)\n if zipfile.is_zipfile(filename):\n tree = get_xml_from_a... | class Datasource(object):
"""A class representing Tableau Data Sources, embedded in workbook files or
in TDS files.
"""
def __init__(self, dsxml, filename=None):
"""
Constructor. Default is to create datasource from xml.
"""
self._filename = filename
self._dat... |
tableau/document-api-python | tableaudocumentapi/datasource.py | Datasource.from_connections | python | def from_connections(cls, caption, connections):
root = ET.Element('datasource', caption=caption, version='10.0', inline='true')
outer_connection = ET.SubElement(root, 'connection')
outer_connection.set('class', 'federated')
named_conns = ET.SubElement(outer_connection, 'named-connectio... | Create a new Data Source give a list of Connections. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/datasource.py#L149-L162 | [
"def _make_unique_name(dbclass):\n rand_part = base36encode(uuid4().int)\n name = dbclass + '.' + rand_part\n return name\n"
] | class Datasource(object):
"""A class representing Tableau Data Sources, embedded in workbook files or
in TDS files.
"""
def __init__(self, dsxml, filename=None):
"""
Constructor. Default is to create datasource from xml.
"""
self._filename = filename
self._dat... |
tableau/document-api-python | tableaudocumentapi/datasource.py | Datasource.save_as | python | def save_as(self, new_filename):
xfile._save_file(self._filename, self._datasourceTree, new_filename) | Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/datasource.py#L180-L192 | [
"def _save_file(container_file, xml_tree, new_filename=None):\n\n if new_filename is None:\n new_filename = container_file\n\n if zipfile.is_zipfile(container_file):\n save_into_archive(xml_tree, container_file, new_filename)\n else:\n xml_tree.write(new_filename, encoding=\"utf-8\", x... | class Datasource(object):
"""A class representing Tableau Data Sources, embedded in workbook files or
in TDS files.
"""
def __init__(self, dsxml, filename=None):
"""
Constructor. Default is to create datasource from xml.
"""
self._filename = filename
self._dat... |
tableau/document-api-python | tableaudocumentapi/workbook.py | Workbook.save_as | python | def save_as(self, new_filename):
xfile._save_file(
self._filename, self._workbookTree, new_filename) | Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/workbook.py#L60-L72 | [
"def _save_file(container_file, xml_tree, new_filename=None):\n\n if new_filename is None:\n new_filename = container_file\n\n if zipfile.is_zipfile(container_file):\n save_into_archive(xml_tree, container_file, new_filename)\n else:\n xml_tree.write(new_filename, encoding=\"utf-8\", x... | class Workbook(object):
"""A class for writing Tableau workbook files."""
def __init__(self, filename):
"""Open the workbook at `filename`. This will handle packaged and unpacked
workbook files automatically. This will also parse Data Sources and Worksheets
for access.
"""
... |
tableau/document-api-python | tableaudocumentapi/field.py | Field.name | python | def name(self):
alias = getattr(self, 'alias', None)
if alias:
return alias
caption = getattr(self, 'caption', None)
if caption:
return caption
return self.id | Provides a nice name for the field which is derived from the alias, caption, or the id.
The name resolves as either the alias if it's defined, or the caption if alias is not defined,
and finally the id which is the underlying name if neither of the fields exist. | train | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/field.py#L99-L112 | null | class Field(object):
""" Represents a field in a datasource """
def __init__(self, column_xml=None, metadata_xml=None):
# Initialize all the possible attributes
for attrib in _ATTRIBUTES:
setattr(self, '_{}'.format(attrib), None)
for attrib in _METADATA_ATTRIBUTES:
... |
metacloud/gilt | gilt/config.py | config | python | def config(filename):
Config = collections.namedtuple('Config', [
'git',
'lock_file',
'version',
'name',
'src',
'dst',
'files',
'post_commands',
])
return [Config(**d) for d in _get_config_generator(filename)] | Construct `Config` object and return a list.
:parse filename: A string containing the path to YAML file.
:return: list | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L41-L59 | [
"def _get_config_generator(filename):\n \"\"\"\n A generator which populates and return a dict.\n\n :parse filename: A string containing the path to YAML file.\n :return: dict\n \"\"\"\n for d in _get_config(filename):\n repo = d['git']\n parsedrepo = giturlparse.parse(repo)\n ... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/config.py | _get_files_config | python | def _get_files_config(src_dir, files_list):
FilesConfig = collections.namedtuple('FilesConfig',
['src', 'dst', 'post_commands'])
return [
FilesConfig(**d) for d in _get_files_generator(src_dir, files_list)
] | Construct `FileConfig` object and return a list.
:param src_dir: A string containing the source directory.
:param files_list: A list of dicts containing the src/dst mapping of files
to overlay.
:return: list | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L62-L76 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/config.py | _get_config_generator | python | def _get_config_generator(filename):
for d in _get_config(filename):
repo = d['git']
parsedrepo = giturlparse.parse(repo)
name = '{}.{}'.format(parsedrepo.owner, parsedrepo.name)
src_dir = os.path.join(_get_clone_dir(), name)
files = d.get('files')
post_commands = d.g... | A generator which populates and return a dict.
:parse filename: A string containing the path to YAML file.
:return: dict | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L79-L105 | [
"def _get_files_config(src_dir, files_list):\n \"\"\"\n Construct `FileConfig` object and return a list.\n\n :param src_dir: A string containing the source directory.\n :param files_list: A list of dicts containing the src/dst mapping of files\n to overlay.\n :return: list\n \"\"\"\n FilesC... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/config.py | _get_files_generator | python | def _get_files_generator(src_dir, files_list):
if files_list:
for d in files_list:
yield {
'src': os.path.join(src_dir, d['src']),
'dst': _get_dst_dir(d['dst']),
'post_commands': d.get('post_commands', []),
} | A generator which populates and return a dict.
:param src_dir: A string containing the source directory.
:param files_list: A list of dicts containing the src/dst mapping of files
to overlay.
:return: dict | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L108-L123 | [
"def _get_dst_dir(dst_dir):\n \"\"\"\n Prefix the provided string with working directory and return a\n str.\n\n :param dst_dir: A string to be prefixed with the working dir.\n :return: str\n \"\"\"\n wd = os.getcwd()\n _makedirs(dst_dir)\n\n return os.path.join(wd, dst_dir)\n"
] | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/config.py | _get_config | python | def _get_config(filename):
i = interpolation.Interpolator(interpolation.TemplateWithDefaults,
os.environ)
with open(filename, 'r') as stream:
try:
interpolated_config = i.interpolate(stream.read())
return yaml.safe_load(interpolated_config)
... | Parse the provided YAML file and return a dict.
:parse filename: A string containing the path to YAML file.
:return: dict | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L126-L142 | [
"def interpolate(self, string):\n try:\n return self.templater(string).substitute(self.mapping)\n except ValueError:\n raise InvalidInterpolation(string)\n"
] | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/config.py | _get_dst_dir | python | def _get_dst_dir(dst_dir):
wd = os.getcwd()
_makedirs(dst_dir)
return os.path.join(wd, dst_dir) | Prefix the provided string with working directory and return a
str.
:param dst_dir: A string to be prefixed with the working dir.
:return: str | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L145-L156 | [
"def _makedirs(path):\n \"\"\"\n Create a base directory of the provided path and return None.\n\n :param path: A string containing a path to be deconstructed and basedir\n created.\n :return: None\n \"\"\"\n dirname, _ = os.path.split(path)\n try:\n os.makedirs(dirname)\n except ... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/config.py | _makedirs | python | def _makedirs(path):
dirname, _ = os.path.split(path)
try:
os.makedirs(dirname)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise | Create a base directory of the provided path and return None.
:param path: A string containing a path to be deconstructed and basedir
created.
:return: None | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L193-L208 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/shell.py | main | python | def main(ctx, config, debug): # pragma: no cover
ctx.obj = {}
ctx.obj['args'] = {}
ctx.obj['args']['debug'] = debug
ctx.obj['args']['config'] = config | gilt - A GIT layering tool. | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/shell.py#L50-L55 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/shell.py | overlay | python | def overlay(ctx): # pragma: no cover
args = ctx.obj.get('args')
filename = args.get('config')
debug = args.get('debug')
_setup(filename)
for c in config.config(filename):
with fasteners.InterProcessLock(c.lock_file):
util.print_info('{}:'.format(c.name))
if not os.p... | Install gilt dependencies | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/shell.py#L60-L87 | [
"def config(filename):\n \"\"\"\n Construct `Config` object and return a list.\n\n :parse filename: A string containing the path to YAML file.\n :return: list\n \"\"\"\n Config = collections.namedtuple('Config', [\n 'git',\n 'lock_file',\n 'version',\n 'name',\n ... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/git.py | clone | python | def clone(name, repository, destination, debug=False):
msg = ' - cloning {} to {}'.format(name, destination)
util.print_info(msg)
cmd = sh.git.bake('clone', repository, destination)
util.run_command(cmd, debug=debug) | Clone the specified repository into a temporary directory and return None.
:param name: A string containing the name of the repository being cloned.
:param repository: A string containing the repository to clone.
:param destination: A string containing the directory to clone the
repository into.
:... | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L32-L46 | [
"def print_info(msg):\n \"\"\" Print the given message to STDOUT. \"\"\"\n print(msg)\n",
"def run_command(cmd, debug=False):\n \"\"\"\n Execute the given command and return None.\n\n :param cmd: A `sh.Command` object to execute.\n :param debug: An optional bool to toggle debug output.\n :ret... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/git.py | extract | python | def extract(repository, destination, version, debug=False):
with util.saved_cwd():
if os.path.isdir(destination):
shutil.rmtree(destination)
os.chdir(repository)
_get_version(version, debug)
cmd = sh.git.bake(
'checkout-index', force=True, all=True, prefix=de... | Extract the specified repository/version into the given directory and
return None.
:param repository: A string containing the path to the repository to be
extracted.
:param destination: A string containing the directory to clone the
repository into. Relative to the directory ``gilt`` is running
... | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L49-L74 | [
"def print_info(msg):\n \"\"\" Print the given message to STDOUT. \"\"\"\n print(msg)\n",
"def run_command(cmd, debug=False):\n \"\"\"\n Execute the given command and return None.\n\n :param cmd: A `sh.Command` object to execute.\n :param debug: An optional bool to toggle debug output.\n :ret... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/git.py | overlay | python | def overlay(repository, files, version, debug=False):
with util.saved_cwd():
os.chdir(repository)
_get_version(version, debug)
for fc in files:
if '*' in fc.src:
for filename in glob.glob(fc.src):
util.copy(filename, fc.dst)
... | Overlay files from the specified repository/version into the given
directory and return None.
:param repository: A string containing the path to the repository to be
extracted.
:param files: A list of `FileConfig` objects.
:param version: A string containing the branch/tag/sha to be exported.
... | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L77-L106 | [
"def copy(src, dst):\n \"\"\"\n Handle the copying of a file or directory.\n\n The destination basedir _must_ exist.\n\n :param src: A string containing the path of the source to copy. If the\n source ends with a '/', will become a recursive directory copy of source.\n :param dst: A string conta... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/git.py | _get_version | python | def _get_version(version, debug=False):
if not any(
(_has_branch(version, debug), _has_tag(version, debug), _has_commit(
version, debug))):
cmd = sh.git.bake('fetch')
util.run_command(cmd, debug=debug)
cmd = sh.git.bake('checkout', version)
util.run_command(cmd, debug=deb... | Handle switching to the specified version and return None.
1. Fetch the origin.
2. Checkout the specified version.
3. Clean the repository before we begin.
4. Pull the origin when a branch; _not_ a commit id.
:param version: A string containing the branch/tag/sha to be exported.
:param debug: ... | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L109-L133 | [
"def run_command(cmd, debug=False):\n \"\"\"\n Execute the given command and return None.\n\n :param cmd: A `sh.Command` object to execute.\n :param debug: An optional bool to toggle debug output.\n :return: None\n \"\"\"\n if debug:\n msg = ' PWD: {}'.format(os.getcwd())\n print... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/git.py | _has_commit | python | def _has_commit(version, debug=False):
if _has_tag(version, debug) or _has_branch(version, debug):
return False
cmd = sh.git.bake('cat-file', '-e', version)
try:
util.run_command(cmd, debug=debug)
return True
except sh.ErrorReturnCode:
return False | Determine a version is a local git commit sha or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L136-L151 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/git.py | _has_tag | python | def _has_tag(version, debug=False):
cmd = sh.git.bake('show-ref', '--verify', '--quiet',
"refs/tags/{}".format(version))
try:
util.run_command(cmd, debug=debug)
return True
except sh.ErrorReturnCode:
return False | Determine a version is a local git tag name or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L154-L168 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/util.py | run_command | python | def run_command(cmd, debug=False):
if debug:
msg = ' PWD: {}'.format(os.getcwd())
print_warn(msg)
msg = ' COMMAND: {}'.format(cmd)
print_warn(msg)
cmd() | Execute the given command and return None.
:param cmd: A `sh.Command` object to execute.
:param debug: An optional bool to toggle debug output.
:return: None | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L46-L59 | [
"def print_warn(msg):\n \"\"\" Print the given message to STDOUT in YELLOW. \"\"\"\n print('{}{}'.format(colorama.Fore.YELLOW, msg))\n"
] | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/util.py | build_sh_cmd | python | def build_sh_cmd(cmd, cwd=None):
args = cmd.split()
return getattr(sh, args[0]).bake(_cwd=cwd, *args[1:]) | Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command` | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L62-L70 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
metacloud/gilt | gilt/util.py | copy | python | def copy(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc:
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else:
raise | Handle the copying of a file or directory.
The destination basedir _must_ exist.
:param src: A string containing the path of the source to copy. If the
source ends with a '/', will become a recursive directory copy of source.
:param dst: A string containing the path to the destination. If the
... | train | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L83-L101 | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation th... |
cyface/django-termsandconditions | termsandconditions/middleware.py | is_path_protected | python | def is_path_protected(path):
protected = True
for exclude_path in TERMS_EXCLUDE_URL_PREFIX_LIST:
if path.startswith(exclude_path):
protected = False
for contains_path in TERMS_EXCLUDE_URL_CONTAINS_LIST:
if contains_path in path:
protected = False
if path in TER... | returns True if given path is to be protected, otherwise False
The path is not to be protected when it appears on:
TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as
ACCEPT_TERMS_PATH | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/middleware.py#L49-L74 | null | """Terms and Conditions Middleware"""
from .models import TermsAndConditions
from django.conf import settings
import logging
from .pipeline import redirect_to_terms_accept
from django import VERSION as DJANGO_VERSION
if DJANGO_VERSION >= (1, 10, 0):
from django.utils.deprecation import MiddlewareMixin
else:
Mi... |
cyface/django-termsandconditions | termsandconditions/middleware.py | TermsAndConditionsRedirectMiddleware.process_request | python | def process_request(self, request):
LOGGER.debug('termsandconditions.middleware')
current_path = request.META['PATH_INFO']
if DJANGO_VERSION <= (2, 0, 0):
user_authenticated = request.user.is_authenticated()
else:
user_authenticated = request.user.is_authentica... | Process each request to app to ensure terms have been accepted | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/middleware.py#L27-L46 | [
"def redirect_to_terms_accept(current_path='/', slug='default'):\n \"\"\"Redirect the user to the terms and conditions accept page.\"\"\"\n redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))\n if slug != 'default':\n redirect_url_parts[2] += slug\n querystring = QueryDict(redirect_url_parts[4... | class TermsAndConditionsRedirectMiddleware(MiddlewareMixin):
"""
This middleware checks to see if the user is logged in, and if so,
if they have accepted all the active terms.
"""
|
cyface/django-termsandconditions | termsandconditions/views.py | GetTermsViewMixin.get_terms | python | def get_terms(self, kwargs):
slug = kwargs.get("slug")
version = kwargs.get("version")
if slug and version:
terms = [TermsAndConditions.objects.filter(slug=slug, version_number=version).latest('date_active')]
elif slug:
terms = [TermsAndConditions.get_active(slu... | Checks URL parameters for slug and/or version to pull the right TermsAndConditions object | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L28-L41 | [
"def get_active(slug=DEFAULT_TERMS_SLUG):\n \"\"\"Finds the latest of a particular terms and conditions\"\"\"\n\n active_terms = cache.get('tandc.active_terms_' + slug)\n if active_terms is None:\n try:\n active_terms = TermsAndConditions.objects.filter(\n date_active__isnu... | class GetTermsViewMixin(object):
"""Checks URL parameters for slug and/or version to pull the right TermsAndConditions object"""
|
cyface/django-termsandconditions | termsandconditions/views.py | TermsView.get_context_data | python | def get_context_data(self, **kwargs):
context = super(TermsView, self).get_context_data(**kwargs)
context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE)
return context | Pass additional context data | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L53-L57 | null | class TermsView(DetailView, GetTermsViewMixin):
"""
View Terms and Conditions View
url: /terms/view
"""
template_name = "termsandconditions/tc_view_terms.html"
context_object_name = 'terms_list'
def get_object(self, queryset=None):
"""Override of DetailView method, queries for whi... |
cyface/django-termsandconditions | termsandconditions/views.py | AcceptTermsView.get_initial | python | def get_initial(self):
LOGGER.debug('termsandconditions.views.AcceptTermsView.get_initial')
terms = self.get_terms(self.kwargs)
return_to = self.request.GET.get('returnTo', '/')
return {'terms': terms, 'returnTo': return_to} | Override of CreateView method, queries for which T&C to accept and catches returnTo from URL | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L82-L89 | null | class AcceptTermsView(CreateView, GetTermsViewMixin):
"""
Terms and Conditions Acceptance view
url: /terms/accept
"""
model = UserTermsAndConditions
form_class = UserTermsAndConditionsModelForm
template_name = "termsandconditions/tc_accept_terms.html"
def get_context_data(self, **kwar... |
cyface/django-termsandconditions | termsandconditions/views.py | AcceptTermsView.post | python | def post(self, request, *args, **kwargs):
return_url = request.POST.get('returnTo', '/')
terms_ids = request.POST.getlist('terms')
if not terms_ids: # pragma: nocover
return HttpResponseRedirect(return_url)
if DJANGO_VERSION <= (2, 0, 0):
user_authenticated = r... | Handles POST request. | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L91-L133 | null | class AcceptTermsView(CreateView, GetTermsViewMixin):
"""
Terms and Conditions Acceptance view
url: /terms/accept
"""
model = UserTermsAndConditions
form_class = UserTermsAndConditionsModelForm
template_name = "termsandconditions/tc_accept_terms.html"
def get_context_data(self, **kwar... |
cyface/django-termsandconditions | termsandconditions/views.py | EmailTermsView.form_valid | python | def form_valid(self, form):
LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid')
template = get_template("termsandconditions/tc_email_terms.html")
template_rendered = template.render({"terms": form.cleaned_data.get('terms')})
LOGGER.debug("Email Terms Body:")
LOGG... | Override of CreateView method, sends the email. | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L162-L184 | null | class EmailTermsView(FormView, GetTermsViewMixin):
"""
Email Terms and Conditions View
url: /terms/email
"""
template_name = "termsandconditions/tc_email_terms_form.html"
form_class = EmailTermsForm
def get_context_data(self, **kwargs):
"""Pass additional context data"""
c... |
cyface/django-termsandconditions | termsandconditions/views.py | EmailTermsView.form_invalid | python | def form_invalid(self, form):
LOGGER.debug("Invalid Email Form Submitted")
messages.add_message(self.request, messages.ERROR, _("Invalid Email Address."))
return super(EmailTermsView, self).form_invalid(form) | Override of CreateView method, logs invalid email form submissions. | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L186-L190 | null | class EmailTermsView(FormView, GetTermsViewMixin):
"""
Email Terms and Conditions View
url: /terms/email
"""
template_name = "termsandconditions/tc_email_terms_form.html"
form_class = EmailTermsForm
def get_context_data(self, **kwargs):
"""Pass additional context data"""
c... |
cyface/django-termsandconditions | termsandconditions/decorators.py | terms_required | python | def terms_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
"""Method to wrap the view passed in"""
# If user has not logged in, or if they have logged in and already agreed to the terms, let the view through
if DJAN... | This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms. | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/decorators.py#L11-L36 | null | """View Decorators for termsandconditions module"""
from django import VERSION as DJANGO_VERSION
from future.moves.urllib.parse import urlparse, urlunparse
from functools import wraps
from django.http import HttpResponseRedirect, QueryDict
from django.utils.decorators import available_attrs
from .models import TermsAnd... |
cyface/django-termsandconditions | termsandconditions/models.py | TermsAndConditions.get_active | python | def get_active(slug=DEFAULT_TERMS_SLUG):
active_terms = cache.get('tandc.active_terms_' + slug)
if active_terms is None:
try:
active_terms = TermsAndConditions.objects.filter(
date_active__isnull=False,
date_active__lte=timezone.now(),... | Finds the latest of a particular terms and conditions | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L75-L90 | null | class TermsAndConditions(models.Model):
"""Holds Versions of TermsAndConditions
Active one for a given slug is: date_active is not Null and is latest not in future"""
slug = models.SlugField(default=DEFAULT_TERMS_SLUG)
name = models.TextField(max_length=255)
users = models.ManyToManyField(settings.A... |
cyface/django-termsandconditions | termsandconditions/models.py | TermsAndConditions.get_active_terms_ids | python | def get_active_terms_ids():
active_terms_ids = cache.get('tandc.active_terms_ids')
if active_terms_ids is None:
active_terms_dict = {}
active_terms_ids = []
active_terms_set = TermsAndConditions.objects.filter(date_active__isnull=False, date_active__lte=timezone.now... | Returns a list of the IDs of of all terms and conditions | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L93-L112 | null | class TermsAndConditions(models.Model):
"""Holds Versions of TermsAndConditions
Active one for a given slug is: date_active is not Null and is latest not in future"""
slug = models.SlugField(default=DEFAULT_TERMS_SLUG)
name = models.TextField(max_length=255)
users = models.ManyToManyField(settings.A... |
cyface/django-termsandconditions | termsandconditions/models.py | TermsAndConditions.get_active_terms_list | python | def get_active_terms_list():
active_terms_list = cache.get('tandc.active_terms_list')
if active_terms_list is None:
active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_by('slug')
cache.set('tandc.active_terms_list', activ... | Returns all the latest active terms and conditions | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L115-L123 | [
"def get_active_terms_ids():\n \"\"\"Returns a list of the IDs of of all terms and conditions\"\"\"\n\n active_terms_ids = cache.get('tandc.active_terms_ids')\n if active_terms_ids is None:\n active_terms_dict = {}\n active_terms_ids = []\n\n active_terms_set = TermsAndConditions.objec... | class TermsAndConditions(models.Model):
"""Holds Versions of TermsAndConditions
Active one for a given slug is: date_active is not Null and is latest not in future"""
slug = models.SlugField(default=DEFAULT_TERMS_SLUG)
name = models.TextField(max_length=255)
users = models.ManyToManyField(settings.A... |
cyface/django-termsandconditions | termsandconditions/models.py | TermsAndConditions.get_active_terms_not_agreed_to | python | def get_active_terms_not_agreed_to(user):
if TERMS_EXCLUDE_USERS_WITH_PERM is not None:
if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser:
# Django's has_perm() returns True if is_superuser, we don't want that
return []
not_agreed_ter... | Checks to see if a specified user has agreed to all the latest terms and conditions | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L126-L146 | [
"def get_active_terms_list():\n \"\"\"Returns all the latest active terms and conditions\"\"\"\n\n active_terms_list = cache.get('tandc.active_terms_list')\n if active_terms_list is None:\n active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_... | class TermsAndConditions(models.Model):
"""Holds Versions of TermsAndConditions
Active one for a given slug is: date_active is not Null and is latest not in future"""
slug = models.SlugField(default=DEFAULT_TERMS_SLUG)
name = models.TextField(max_length=255)
users = models.ManyToManyField(settings.A... |
cyface/django-termsandconditions | termsandconditions/templatetags/terms_tags.py | show_terms_if_not_agreed | python | def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD):
request = context['request']
url = urlparse(request.META[field])
not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(request.user)
if not_agreed_terms and is_path_protected(url.path):
return {'not_agreed_terms'... | Displays a modal on a current page if a user has not yet agreed to the
given terms. If terms are not specified, the default slug is used.
A small snippet is included into your template if a user
who requested the view has not yet agreed the terms. The snippet takes
care of displaying a respective modal... | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/templatetags/terms_tags.py#L15-L30 | [
"def is_path_protected(path):\n \"\"\"\n returns True if given path is to be protected, otherwise False\n\n The path is not to be protected when it appears on:\n TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as\n ACCEPT_TERMS_PATH\n \"\"\"\n protected... | """Django Tags"""
from django import template
from ..models import TermsAndConditions
from ..middleware import is_path_protected
from django.conf import settings
from future.moves.urllib.parse import urlparse
register = template.Library()
DEFAULT_HTTP_PATH_FIELD = 'PATH_INFO'
TERMS_HTTP_PATH_FIELD = getattr(settings, ... |
cyface/django-termsandconditions | termsandconditions/pipeline.py | user_accept_terms | python | def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs):
LOGGER.debug('user_accept_terms')
if TermsAndConditions.get_active_terms_not_agreed_to(user):
return redirect_to_terms_accept('/')
else:
return {'social_user': social_user, 'user': user} | Check if the user has accepted the terms and conditions after creation. | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L17-L25 | [
"def redirect_to_terms_accept(current_path='/', slug='default'):\n \"\"\"Redirect the user to the terms and conditions accept page.\"\"\"\n redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))\n if slug != 'default':\n redirect_url_parts[2] += slug\n querystring = QueryDict(redirect_url_parts[4... | """This file contains functions used as part of a user creation pipeline, such as django-social-auth."""
# pylint: disable=W0613
from future.moves.urllib.parse import urlparse, urlunparse
from .models import TermsAndConditions
from django.http import HttpResponseRedirect, QueryDict
from django.conf import settings
im... |
cyface/django-termsandconditions | termsandconditions/pipeline.py | redirect_to_terms_accept | python | def redirect_to_terms_accept(current_path='/', slug='default'):
redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))
if slug != 'default':
redirect_url_parts[2] += slug
querystring = QueryDict(redirect_url_parts[4], mutable=True)
querystring[TERMS_RETURNTO_PARAM] = current_path
redirect_ur... | Redirect the user to the terms and conditions accept page. | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L28-L36 | null | """This file contains functions used as part of a user creation pipeline, such as django-social-auth."""
# pylint: disable=W0613
from future.moves.urllib.parse import urlparse, urlunparse
from .models import TermsAndConditions
from django.http import HttpResponseRedirect, QueryDict
from django.conf import settings
im... |
cyface/django-termsandconditions | termsandconditions/signals.py | user_terms_updated | python | def user_terms_updated(sender, **kwargs):
LOGGER.debug("User T&C Updated Signal Handler")
if kwargs.get('instance').user:
cache.delete('tandc.not_agreed_terms_' + kwargs.get('instance').user.get_username()) | Called when user terms and conditions is changed - to force cache clearing | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L15-L19 | null | """ Signals for Django """
# pylint: disable=C1001,E0202,W0613
import logging
from django.core.cache import cache
from django.dispatch import receiver
from .models import TermsAndConditions, UserTermsAndConditions
from django.db.models.signals import post_delete, post_save
LOGGER = logging.getLogger(name='termsandco... |
cyface/django-termsandconditions | termsandconditions/signals.py | terms_updated | python | def terms_updated(sender, **kwargs):
LOGGER.debug("T&C Updated Signal Handler")
cache.delete('tandc.active_terms_ids')
cache.delete('tandc.active_terms_list')
if kwargs.get('instance').slug:
cache.delete('tandc.active_terms_' + kwargs.get('instance').slug)
for utandc in UserTermsAndCondition... | Called when terms and conditions is changed - to force cache clearing | train | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L23-L31 | null | """ Signals for Django """
# pylint: disable=C1001,E0202,W0613
import logging
from django.core.cache import cache
from django.dispatch import receiver
from .models import TermsAndConditions, UserTermsAndConditions
from django.db.models.signals import post_delete, post_save
LOGGER = logging.getLogger(name='termsandco... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx4.py | compute_transformed | python | def compute_transformed(context):
key_composite = compute_key_composite(
password=context._._.password,
keyfile=context._._.keyfile
)
kdf_parameters = context._.header.value.dynamic_header.kdf_parameters.data.dict
if context._._.transformed_key is not None:
transformed_key = co... | Compute transformed key for opening database | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx4.py#L31-L62 | [
"def aes_kdf(key, rounds, password=None, keyfile=None):\n \"\"\"Set up a context for AES128-ECB encryption to find transformed_key\"\"\"\n\n cipher = AES.new(key, AES.MODE_ECB)\n key_composite = compute_key_composite(\n password=password,\n keyfile=keyfile\n )\n\n # get the number of ro... | #!/bin/env python3
# Evan Widloski - 2018-04-11
# keepass decrypt experimentation
import struct
import hashlib
import argon2
import hmac
from construct import (
Byte, Bytes, Int32ul, RepeatUntil, GreedyBytes, Struct, this, Mapping,
Switch, Flag, Prefixed, Int64ul, Int32sl, Int64sl, GreedyString, Padding,
P... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx4.py | compute_header_hmac_hash | python | def compute_header_hmac_hash(context):
return hmac.new(
hashlib.sha512(
b'\xff' * 8 +
hashlib.sha512(
context._.header.value.dynamic_header.master_seed.data +
context.transformed_key +
b'\x01'
).digest()
).digest(),... | Compute HMAC-SHA256 hash of header.
Used to prevent header tampering. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx4.py#L64-L79 | null | #!/bin/env python3
# Evan Widloski - 2018-04-11
# keepass decrypt experimentation
import struct
import hashlib
import argon2
import hmac
from construct import (
Byte, Bytes, Int32ul, RepeatUntil, GreedyBytes, Struct, this, Mapping,
Switch, Flag, Prefixed, Int64ul, Int32sl, Int64sl, GreedyString, Padding,
P... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx4.py | compute_payload_block_hash | python | def compute_payload_block_hash(this):
return hmac.new(
hashlib.sha512(
struct.pack('<Q', this._index) +
hashlib.sha512(
this._._.header.value.dynamic_header.master_seed.data +
this._.transformed_key + b'\x01'
).digest()
).digest(),... | Compute hash of each payload block.
Used to prevent payload corruption and tampering. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx4.py#L156-L171 | null | #!/bin/env python3
# Evan Widloski - 2018-04-11
# keepass decrypt experimentation
import struct
import hashlib
import argon2
import hmac
from construct import (
Byte, Bytes, Int32ul, RepeatUntil, GreedyBytes, Struct, this, Mapping,
Switch, Flag, Prefixed, Int64ul, Int32sl, Int64sl, GreedyString, Padding,
P... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx3.py | compute_transformed | python | def compute_transformed(context):
if context._._.transformed_key is not None:
transformed_key = context._._transformed_key
else:
transformed_key = aes_kdf(
context._.header.value.dynamic_header.transform_seed.data,
context._.header.value.dynamic_header.transform_rounds.d... | Compute transformed key for opening database | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx3.py#L26-L39 | [
"def aes_kdf(key, rounds, password=None, keyfile=None):\n \"\"\"Set up a context for AES128-ECB encryption to find transformed_key\"\"\"\n\n cipher = AES.new(key, AES.MODE_ECB)\n key_composite = compute_key_composite(\n password=password,\n keyfile=keyfile\n )\n\n # get the number of ro... | #!/bin/env python3
# Evan Widloski - 2018-04-11
# keepass decrypt experimentation
import hashlib
from construct import (
Byte, Bytes, Int16ul, Int32ul, RepeatUntil, GreedyBytes, Struct, this,
Mapping, Switch, Prefixed, Padding, Checksum, Computed, IfThenElse,
Pointer, Tell, len_
)
from .common import (
... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/pytwofish.py | Twofish.set_key | python | def set_key(self, key):
key_len = len(key)
if key_len not in [16, 24, 32]:
# XXX: add padding?
raise KeyError("key must be 16, 24 or 32 bytes")
if key_len % 4:
# XXX: add padding?
raise KeyError("key not a multiple of 4")
if key_len > 32:
... | Init. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/pytwofish.py#L55-L78 | [
"def set_key(pkey, in_key, key_len):\n pkey.qt_gen = 0\n if not pkey.qt_gen:\n gen_qtab(pkey)\n pkey.qt_gen = 1\n pkey.mt_gen = 0\n if not pkey.mt_gen:\n gen_mtab(pkey)\n pkey.mt_gen = 1\n pkey.k_len = int((key_len * 8) / 64)\n\n a = 0\n b = 0\n me_key = [0,0,0,0]... | class Twofish:
def __init__(self, key=None):
"""Twofish."""
if key:
self.set_key(key)
def decrypt(self, block):
"""Decrypt blocks."""
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
plaintext = b''
while ... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/pytwofish.py | Twofish.decrypt | python | def decrypt(self, block):
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
plaintext = b''
while block:
a, b, c, d = struct.unpack("<4L", block[:16])
temp = [a, b, c, d]
decrypt(self.context, temp)
plaintex... | Decrypt blocks. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/pytwofish.py#L81-L96 | [
"def decrypt(pkey, in_blk):\n blk = [0, 0, 0, 0]\n\n if WORD_BIGENDIAN:\n blk[0] = byteswap32(in_blk[0]) ^ pkey.l_key[4];\n blk[1] = byteswap32(in_blk[1]) ^ pkey.l_key[5];\n blk[2] = byteswap32(in_blk[2]) ^ pkey.l_key[6];\n blk[3] = byteswap32(in_blk[3]) ^ pkey.l_key[7];\n else:... | class Twofish:
def __init__(self, key=None):
"""Twofish."""
if key:
self.set_key(key)
def set_key(self, key):
"""Init."""
key_len = len(key)
if key_len not in [16, 24, 32]:
# XXX: add padding?
raise KeyError("key must be 16, 24 or ... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/pytwofish.py | Twofish.encrypt | python | def encrypt(self, block):
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
ciphertext = b''
while block:
a, b, c, d = struct.unpack("<4L", block[0:16])
temp = [a, b, c, d]
encrypt(self.context, temp)
cipher... | Encrypt blocks. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/pytwofish.py#L99-L114 | [
"def encrypt(pkey, in_blk):\n blk = [0, 0, 0, 0]\n\n if WORD_BIGENDIAN:\n blk[0] = byteswap32(in_blk[0]) ^ pkey.l_key[0];\n blk[1] = byteswap32(in_blk[1]) ^ pkey.l_key[1];\n blk[2] = byteswap32(in_blk[2]) ^ pkey.l_key[2];\n blk[3] = byteswap32(in_blk[3]) ^ pkey.l_key[3];\n else:... | class Twofish:
def __init__(self, key=None):
"""Twofish."""
if key:
self.set_key(key)
def set_key(self, key):
"""Init."""
key_len = len(key)
if key_len not in [16, 24, 32]:
# XXX: add padding?
raise KeyError("key must be 16, 24 or ... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | aes_kdf | python | def aes_kdf(key, rounds, password=None, keyfile=None):
cipher = AES.new(key, AES.MODE_ECB)
key_composite = compute_key_composite(
password=password,
keyfile=keyfile
)
# get the number of rounds from the header and transform the key_composite
transformed_key = key_composite
for ... | Set up a context for AES128-ECB encryption to find transformed_key | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L84-L98 | [
"def compute_key_composite(password=None, keyfile=None):\n \"\"\"Compute composite key.\n Used in header verification and payload decryption.\"\"\"\n\n # hash the password\n if password:\n password_composite = hashlib.sha256(password.encode('utf-8')).digest()\n else:\n password_composit... | from Crypto.Cipher import AES, ChaCha20, Salsa20
from .twofish import Twofish
from Crypto.Util import Padding as CryptoPadding
import hashlib
from construct import (
Adapter, BitStruct, BitsSwapped, Container, Flag, Padding, RepeatUntil,
Subconstruct, Construct, ListContainer, Mapping, GreedyBytes, Int32ul,
... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | compute_key_composite | python | def compute_key_composite(password=None, keyfile=None):
# hash the password
if password:
password_composite = hashlib.sha256(password.encode('utf-8')).digest()
else:
password_composite = b''
# hash the keyfile
if keyfile:
# try to read XML keyfile
try:
wi... | Compute composite key.
Used in header verification and payload decryption. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L101-L144 | null | from Crypto.Cipher import AES, ChaCha20, Salsa20
from .twofish import Twofish
from Crypto.Util import Padding as CryptoPadding
import hashlib
from construct import (
Adapter, BitStruct, BitsSwapped, Container, Flag, Padding, RepeatUntil,
Subconstruct, Construct, ListContainer, Mapping, GreedyBytes, Int32ul,
... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | compute_master | python | def compute_master(context):
# combine the transformed key with the header master seed to find the master_key
master_key = hashlib.sha256(
context._.header.value.dynamic_header.master_seed.data +
context.transformed_key).digest()
return master_key | Computes master key from transformed key and master seed.
Used in payload decryption. | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L146-L154 | null | from Crypto.Cipher import AES, ChaCha20, Salsa20
from .twofish import Twofish
from Crypto.Util import Padding as CryptoPadding
import hashlib
from construct import (
Adapter, BitStruct, BitsSwapped, Container, Flag, Padding, RepeatUntil,
Subconstruct, Construct, ListContainer, Mapping, GreedyBytes, Int32ul,
... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | Unprotect | python | def Unprotect(protected_stream_id, protected_stream_key, subcon):
return Switch(
protected_stream_id,
{'arcfourvariant': ARCFourVariantStream(protected_stream_key, subcon),
'salsa20': Salsa20Stream(protected_stream_key, subcon),
'chacha20': ChaCha20Stream(protected_stream_key, sub... | Select stream cipher based on protected_stream_id | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L231-L241 | null | from Crypto.Cipher import AES, ChaCha20, Salsa20
from .twofish import Twofish
from Crypto.Util import Padding as CryptoPadding
import hashlib
from construct import (
Adapter, BitStruct, BitsSwapped, Container, Flag, Padding, RepeatUntil,
Subconstruct, Construct, ListContainer, Mapping, GreedyBytes, Int32ul,
... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | BlockCipher.encrypt | python | def encrypt(self,plaintext,n=''):
#self.ed = 'e' if chain is encrypting, 'd' if decrypting,
# None if nothing happened with the chain yet
#assert self.ed in ('e',None)
# makes sure you don't encrypt with a cipher that has started decrypting
self.ed = 'e'
if self.mode == ... | Encrypt some plaintext
plaintext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The encrypt function will encrypt the supplied plaintext.
The behavior varies slightly depending on the chaining mode.
ECB, CBC:
---------... | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L114-L159 | [
"def update(self, data, ed):\n \"\"\"Processes the given ciphertext/plaintext\n\n Inputs:\n data: raw string of any length\n ed: 'e' for encryption, 'd' for decryption\n Output:\n processed raw string block(s), if any\n\n When the supplied data is not a multiple of the blocksize\n... | class BlockCipher():
""" Base class for all blockciphers
"""
MODE_ECB = MODE_ECB
MODE_CBC = MODE_CBC
MODE_CFB = MODE_CFB
MODE_OFB = MODE_OFB
MODE_CTR = MODE_CTR
MODE_XTS = MODE_XTS
MODE_CMAC = MODE_CMAC
key_error_message = "Wrong key size" #should be overwritten in child classes... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | BlockCipher.decrypt | python | def decrypt(self,ciphertext,n=''):
#self.ed = 'e' if chain is encrypting, 'd' if decrypting,
# None if nothing happened with the chain yet
#assert self.ed in ('d',None)
# makes sure you don't decrypt with a cipher that has started encrypting
self.ed = 'd'
if self.mode == ... | Decrypt some ciphertext
ciphertext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The decrypt function will decrypt the supplied ciphertext.
The behavior varies slightly depending on the chaining mode.
ECB, CBC:
-------... | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L161-L204 | [
"def update(self, data, ed):\n \"\"\"Processes the given ciphertext/plaintext\n\n Inputs:\n data: raw string of any length\n ed: 'e' for encryption, 'd' for decryption\n Output:\n processed raw string block(s), if any\n\n When the supplied data is not a multiple of the blocksize\n... | class BlockCipher():
""" Base class for all blockciphers
"""
MODE_ECB = MODE_ECB
MODE_CBC = MODE_CBC
MODE_CFB = MODE_CFB
MODE_OFB = MODE_OFB
MODE_CTR = MODE_CTR
MODE_XTS = MODE_XTS
MODE_CMAC = MODE_CMAC
key_error_message = "Wrong key size" #should be overwritten in child classes... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | BlockCipher.final | python | def final(self,style='pkcs7'):
# TODO: after calling final, reset the IV? so the cipher is as good as new?
assert self.mode not in (MODE_XTS, MODE_CMAC) # finalizing (=padding) doesn't make sense when in XTS or CMAC mode
if self.ed == b'e':
# when the chain is in encryption mode, fin... | Finalizes the encryption by padding the cache
padfct = padding function
import from CryptoPlus.Util.padding
For ECB, CBC: the remaining bytes in the cache will be padded and
encrypted.
For OFB,CFB, CTR: an encrypted padding will be returned, makin... | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L206-L237 | [
"def update(self, data, ed):\n \"\"\"Processes the given ciphertext/plaintext\n\n Inputs:\n data: raw string of any length\n ed: 'e' for encryption, 'd' for decryption\n Output:\n processed raw string block(s), if any\n\n When the supplied data is not a multiple of the blocksize\n... | class BlockCipher():
""" Base class for all blockciphers
"""
MODE_ECB = MODE_ECB
MODE_CBC = MODE_CBC
MODE_CFB = MODE_CFB
MODE_OFB = MODE_OFB
MODE_CTR = MODE_CTR
MODE_XTS = MODE_XTS
MODE_CMAC = MODE_CMAC
key_error_message = "Wrong key size" #should be overwritten in child classes... |
pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | CBC.update | python | def update(self, data, ed):
if ed == 'e':
encrypted_blocks = b''
self.cache += data
if len(self.cache) < self.blocksize:
return b''
for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
self.IV = self.codebook.encrypt... | Processes the given ciphertext/plaintext
Inputs:
data: raw string of any length
ed: 'e' for encryption, 'd' for decryption
Output:
processed raw string block(s), if any
When the supplied data is not a multiple of the blocksize
of the cipher, then... | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L249-L284 | null | class CBC:
"""CBC chaining mode
"""
def __init__(self, codebook, blocksize, IV):
self.IV = IV
self.cache = b''
self.codebook = codebook
self.blocksize = blocksize
|
pschmitt/pykeepass | pykeepass/baseelement.py | BaseElement._datetime_to_utc | python | def _datetime_to_utc(self, dt):
if not dt.tzinfo:
dt = dt.replace(tzinfo=tz.gettz())
return dt.astimezone(tz.gettz('UTC')) | Convert naive datetimes to UTC | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/baseelement.py#L92-L97 | null | class BaseElement(object):
"""Entry and Group inherit from this class"""
def __init__(self, element=None, kp=None, icon=None, expires=False,
expiry_time=None):
self._element = element
self._element.append(
E.UUID(base64.b64encode(uuid.uuid1().bytes).decode('utf-8')... |
pschmitt/pykeepass | pykeepass/baseelement.py | BaseElement._encode_time | python | def _encode_time(self, value):
if self._kp.version >= (4, 0):
diff_seconds = int(
(
self._datetime_to_utc(value) -
datetime(
year=1,
month=1,
day=1,
... | Convert datetime to base64 or plaintext string | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/baseelement.py#L99-L118 | [
"def _datetime_to_utc(self, dt):\n \"\"\"Convert naive datetimes to UTC\"\"\"\n\n if not dt.tzinfo:\n dt = dt.replace(tzinfo=tz.gettz())\n return dt.astimezone(tz.gettz('UTC'))\n"
] | class BaseElement(object):
"""Entry and Group inherit from this class"""
def __init__(self, element=None, kp=None, icon=None, expires=False,
expiry_time=None):
self._element = element
self._element.append(
E.UUID(base64.b64encode(uuid.uuid1().bytes).decode('utf-8')... |
pschmitt/pykeepass | pykeepass/baseelement.py | BaseElement._decode_time | python | def _decode_time(self, text):
if self._kp.version >= (4, 0):
# decode KDBX4 date from b64 format
try:
return (
datetime(year=1, month=1, day=1, tzinfo=tz.gettz('UTC')) +
timedelta(
seconds = struct.unpack('<... | Convert base64 time or plaintext time to datetime | train | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/baseelement.py#L120-L141 | null | class BaseElement(object):
"""Entry and Group inherit from this class"""
def __init__(self, element=None, kp=None, icon=None, expires=False,
expiry_time=None):
self._element = element
self._element.append(
E.UUID(base64.b64encode(uuid.uuid1().bytes).decode('utf-8')... |
goldmann/docker-squash | docker_squash/image.py | Image.cleanup | python | def cleanup(self):
self.log.debug("Cleaning up %s temporary directory" % self.tmp_dir)
shutil.rmtree(self.tmp_dir, ignore_errors=True) | Cleanup the temporary directory | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L82-L86 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._validate_number_of_layers | python | def _validate_number_of_layers(self, number_of_layers):
# Only positive numbers are correct
if number_of_layers <= 0:
raise SquashError(
"Number of layers to squash cannot be less or equal 0, provided: %s" % number_of_layers)
# Do not squash if provided number of la... | Makes sure that the specified number of layers to squash
is a valid number | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L125-L140 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._files_in_layers | python | def _files_in_layers(self, layers, directory):
files = {}
for layer in layers:
self.log.debug("Generating list of files in layer '%s'..." % layer)
tar_file = os.path.join(directory, layer, "layer.tar")
with tarfile.open(tar_file, 'r', format=tarfile.PAX_FORMAT) as ta... | Prepare a list of files in all layers | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L260-L274 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._prepare_tmp_directory | python | def _prepare_tmp_directory(self, tmp_dir):
if tmp_dir:
if os.path.exists(tmp_dir):
raise SquashError(
"The '%s' directory already exists, please remove it before you proceed" % tmp_dir)
os.makedirs(tmp_dir)
else:
tmp_dir = tempfile... | Creates temporary directory that is used to work on layers | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L276-L289 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._layers_to_squash | python | def _layers_to_squash(self, layers, from_layer):
to_squash = []
to_leave = []
should_squash = True
for l in reversed(layers):
if l == from_layer:
should_squash = False
if should_squash:
to_squash.append(l)
else:
... | Prepares a list of layer IDs that should be squashed | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L319-L337 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._save_image | python | def _save_image(self, image_id, directory):
for x in [0, 1, 2]:
self.log.info("Saving image %s to %s directory..." %
(image_id, directory))
self.log.debug("Try #%s..." % (x + 1))
try:
image = self.docker.get_image(image_id)
... | Saves the image as a tar archive under specified name | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L343-L386 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._unpack | python | def _unpack(self, tar_file, directory):
self.log.info("Unpacking %s tar file to %s directory" %
(tar_file, directory))
with tarfile.open(tar_file, 'r') as tar:
tar.extractall(path=directory)
self.log.info("Archive unpacked!") | Unpacks tar archive to selected directory | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L388-L397 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._read_layers | python | def _read_layers(self, layers, image_id):
for layer in self.docker.history(image_id):
layers.append(layer['Id']) | Reads the JSON metadata for specified layer / image id | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L399-L403 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._parse_image_name | python | def _parse_image_name(self, image):
if ':' in image and '/' not in image.split(':')[-1]:
image_tag = image.split(':')[-1]
image_name = image[:-(len(image_tag) + 1)]
else:
image_tag = "latest"
image_name = image
return (image_name, image_tag) | Parses the provided image name and splits it in the
name and tag part, if possible. If no tag is provided
'latest' is used. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L405-L418 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._dump_json | python | def _dump_json(self, data, new_line=False):
# We do not want any spaces between keys and values in JSON
json_data = json.dumps(data, separators=(',', ':'))
if new_line:
json_data = "%s\n" % json_data
# Generate sha256sum of the JSON data, may be handy
sha = hashlib... | Helper function to marshal object into JSON string.
Additionally a sha256sum of the created JSON string is generated. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L420-L435 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._move_layers | python | def _move_layers(self, layers, src, dest):
for layer in layers:
layer_id = layer.replace('sha256:', '')
self.log.debug("Moving unmodified layer '%s'..." % layer_id)
shutil.move(os.path.join(src, layer_id), dest) | This moves all the layers that should be copied as-is.
In other words - all layers that are not meant to be squashed will be
moved from the old image to the new image untouched. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L475-L485 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._marker_files | python | def _marker_files(self, tar, members):
marker_files = {}
self.log.debug(
"Searching for marker files in '%s' archive..." % tar.name)
for member in members:
if '.wh.' in member.name:
self.log.debug("Found '%s' marker file" % member.name)
m... | Searches for marker files in the specified archive.
Docker marker files are files taht have the .wh. prefix in the name.
These files mark the corresponding file to be removed (hidden) when
we start a container from the image. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L501-L521 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/image.py | Image._add_markers | python | def _add_markers(self, markers, tar, files_in_layers, added_symlinks):
if markers:
self.log.debug("Marker files to add: %s" %
[o.name for o in markers.keys()])
else:
# No marker files to add
return
# https://github.com/goldmann/doc... | This method is responsible for adding back all markers that were not
added to the squashed layer AND files they refer to can be found in layers
we do not squash. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/image.py#L523-L582 | null | class Image(object):
"""
Base class for all Docker image formats. Contains many functions that are handy
while squashing the image.
This class should not be used directly.
"""
FORMAT = None
""" Image format version """
def __init__(self, log, docker, image, from_layer, tmp_dir=None, t... |
goldmann/docker-squash | docker_squash/lib/xtarfile.py | _proc_pax | python | def _proc_pax(self, filetar):
# Read the header information.
buf = filetar.fileobj.read(self._block(self.size))
# A pax header stores supplemental information for either
# the following file (extended) or all following files
# (global).
if self.type == tarfile.XGLTYPE:
pax_headers = fil... | Process an extended or global header as described in POSIX.1-2001. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/lib/xtarfile.py#L20-L81 | null | """
This is a monkey patching for Python 2 that is required to handle PAX headers
in TAR files that are not decodable to UTF8. It leaves it undecoded and when
adding back to the tar archive the header is not encoded preserving the
original headers.
Reported in RH Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1... |
goldmann/docker-squash | docker_squash/lib/xtarfile.py | _create_pax_generic_header | python | def _create_pax_generic_header(cls, pax_headers, type=tarfile.XHDTYPE):
records = []
for keyword, value in pax_headers.iteritems():
try:
keyword = keyword.encode("utf8")
except Exception:
pass
try:
value = value.encode("utf8")
except Exceptio... | Return a POSIX.1-2001 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be unicode objects. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/lib/xtarfile.py#L84-L122 | null | """
This is a monkey patching for Python 2 that is required to handle PAX headers
in TAR files that are not decodable to UTF8. It leaves it undecoded and when
adding back to the tar archive the header is not encoded preserving the
original headers.
Reported in RH Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1... |
goldmann/docker-squash | docker_squash/v2_image.py | V2Image._read_json_file | python | def _read_json_file(self, json_file):
self.log.debug("Reading '%s' JSON file..." % json_file)
with open(json_file, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict) | Helper function to read JSON file as OrderedDict | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/v2_image.py#L122-L128 | null | class V2Image(Image):
FORMAT = 'v2'
def _before_squashing(self):
super(V2Image, self)._before_squashing()
# Read old image manifest file
self.old_image_manifest = self._read_json_file(
os.path.join(self.old_image_dir, "manifest.json"))[0]
# Read old image config fi... |
goldmann/docker-squash | docker_squash/v2_image.py | V2Image._read_layer_paths | python | def _read_layer_paths(self, old_image_config, old_image_manifest, layers_to_move):
# In manifest.json we do not have listed all layers
# but only layers that do contain some data.
current_manifest_layer = 0
layer_paths_to_move = []
layer_paths_to_squash = []
# Iterate ... | In case of v2 format, layer id's are not the same as the id's
used in the exported tar archive to name directories for layers.
These id's can be found in the configuration files saved with
the image - we need to read them. | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/v2_image.py#L130-L163 | null | class V2Image(Image):
FORMAT = 'v2'
def _before_squashing(self):
super(V2Image, self)._before_squashing()
# Read old image manifest file
self.old_image_manifest = self._read_json_file(
os.path.join(self.old_image_dir, "manifest.json"))[0]
# Read old image config fi... |
goldmann/docker-squash | docker_squash/v2_image.py | V2Image._generate_squashed_layer_path_id | python | def _generate_squashed_layer_path_id(self):
# Using OrderedDict, because order of JSON elements is important
v1_metadata = OrderedDict(self.old_image_config)
# Update image creation date
v1_metadata['created'] = self.date
# Remove unnecessary elements
# Do not fail if ... | This function generates the id used to name the directory to
store the squashed layer content in the archive.
This mimics what Docker does here: https://github.com/docker/docker/blob/v1.10.0-rc1/image/v1/imagev1.go#L42
To make it simpler we do reuse old image metadata and
modify it to w... | train | https://github.com/goldmann/docker-squash/blob/89e0297942be268791aff2098b7ebfa50d82f8e8/docker_squash/v2_image.py#L215-L273 | null | class V2Image(Image):
FORMAT = 'v2'
def _before_squashing(self):
super(V2Image, self)._before_squashing()
# Read old image manifest file
self.old_image_manifest = self._read_json_file(
os.path.join(self.old_image_dir, "manifest.json"))[0]
# Read old image config fi... |
ahawker/ulid | ulid/ulid.py | Timestamp.datetime | python | def datetime(self) -> hints.Datetime:
mills = self.int
return datetime.datetime.utcfromtimestamp(mills // 1000.0).replace(microsecond=mills % 1000 * 1000) | Creates a :class:`~datetime.datetime` instance (assumes UTC) from the Unix time value of the timestamp
with millisecond precision.
:return: Timestamp in datetime form.
:rtype: :class:`~datetime.datetime` | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/ulid.py#L182-L191 | null | class Timestamp(MemoryView):
"""
Represents the timestamp portion of a ULID.
* Unix time (time since epoch) in milliseconds.
* First 48 bits of ULID when in binary format.
* First 10 characters of ULID when in string format.
"""
__slots__ = MemoryView.__slots__
@property
def str(s... |
ahawker/ulid | ulid/api.py | new | python | def new() -> ulid.ULID:
timestamp = int(time.time() * 1000).to_bytes(6, byteorder='big')
randomness = os.urandom(10)
return ulid.ULID(timestamp + randomness) | Create a new :class:`~ulid.ulid.ULID` instance.
The timestamp is created from :func:`~time.time`.
The randomness is created from :func:`~os.urandom`.
:return: ULID from current timestamp
:rtype: :class:`~ulid.ulid.ULID` | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L35-L47 | null | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | parse | python | def parse(value: ULIDPrimitive) -> ulid.ULID:
if isinstance(value, ulid.ULID):
return value
if isinstance(value, uuid.UUID):
return from_uuid(value)
if isinstance(value, str):
len_value = len(value)
if len_value == 36:
return from_uuid(uuid.UUID(value))
if... | Create a new :class:`~ulid.ulid.ULID` instance from the given value.
.. note:: This method should only be used when the caller is trying to parse a ULID from
a value when they're unsure what format/primitive type it will be given in.
:param value: ULID value of any supported type
:type value: :class:`... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L50-L86 | [
"def from_bytes(value: hints.Buffer) -> ulid.ULID:\n \"\"\"\n Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~bytes`,\n :class:`~bytearray`, or :class:`~memoryview` value.\n\n :param value: 16 bytes\n :type value: :class:`~bytes`, :class:`~bytearray`, or :class:`~memoryview`\n ... | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | from_bytes | python | def from_bytes(value: hints.Buffer) -> ulid.ULID:
length = len(value)
if length != 16:
raise ValueError('Expects bytes to be 128 bits; got {} bytes'.format(length))
return ulid.ULID(value) | Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~bytes`,
:class:`~bytearray`, or :class:`~memoryview` value.
:param value: 16 bytes
:type value: :class:`~bytes`, :class:`~bytearray`, or :class:`~memoryview`
:return: ULID from buffer value
:rtype: :class:`~ulid.ulid.ULID`
:... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L89-L104 | null | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | from_int | python | def from_int(value: int) -> ulid.ULID:
if value < 0:
raise ValueError('Expects positive integer')
length = (value.bit_length() + 7) // 8
if length > 16:
raise ValueError('Expects integer to be 128 bits; got {} bytes'.format(length))
return ulid.ULID(value.to_bytes(16, byteorder='big')) | Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~int` value.
:param value: 128 bit integer
:type value: :class:`~int`
:return: ULID from integer value
:rtype: :class:`~ulid.ulid.ULID`
:raises ValueError: when the value is not a 128 bit integer | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L107-L124 | null | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | from_str | python | def from_str(value: str) -> ulid.ULID:
return ulid.ULID(base32.decode_ulid(value)) | Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~str` value.
:param value: Base32 encoded string
:type value: :class:`~str`
:return: ULID from string value
:rtype: :class:`~ulid.ulid.ULID`
:raises ValueError: when the value is not 26 characters or malformed | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L127-L137 | [
"def decode_ulid(value: str) -> bytes:\n \"\"\"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID\n strings specifically and is not meant for arbitrary decoding.\n\n :param value: S... | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | from_uuid | python | def from_uuid(value: uuid.UUID) -> ulid.ULID:
return ulid.ULID(value.bytes) | Create a new :class:`~ulid.ulid.ULID` instance from the given :class:`~uuid.UUID` value.
:param value: UUIDv4 value
:type value: :class:`~uuid.UUID`
:return: ULID from UUID value
:rtype: :class:`~ulid.ulid.ULID` | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L140-L149 | null | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | from_timestamp | python | def from_timestamp(timestamp: TimestampPrimitive) -> ulid.ULID:
if isinstance(timestamp, datetime.datetime):
timestamp = timestamp.timestamp()
if isinstance(timestamp, (int, float)):
timestamp = int(timestamp * 1000.0).to_bytes(6, byteorder='big')
elif isinstance(timestamp, str):
tim... | Create a new :class:`~ulid.ulid.ULID` instance using a timestamp value of a supported type.
The following types are supported for timestamp values:
* :class:`~datetime.datetime`
* :class:`~int`
* :class:`~float`
* :class:`~str`
* :class:`~memoryview`
* :class:`~ulid.ulid.Timestamp`
* :... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L152-L198 | null | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/api.py | from_randomness | python | def from_randomness(randomness: RandomnessPrimitive) -> ulid.ULID:
if isinstance(randomness, (int, float)):
randomness = int(randomness).to_bytes(10, byteorder='big')
elif isinstance(randomness, str):
randomness = base32.decode_randomness(randomness)
elif isinstance(randomness, memoryview):
... | Create a new :class:`~ulid.ulid.ULID` instance using the given randomness value of a supported type.
The following types are supported for randomness values:
* :class:`~int`
* :class:`~float`
* :class:`~str`
* :class:`~memoryview`
* :class:`~ulid.ulid.Randomness`
* :class:`~ulid.ulid.ULID`... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/api.py#L201-L244 | [
"def decode_randomness(randomness: str) -> bytes:\n \"\"\"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n The given :class:`~str` are expected to represent the last 16 characters of a ULID, which\n are cryptographically secure random values.\n\n .. note:: This uses a... | """
ulid/api
~~~~~~~~
Defines the public API of the `ulid` package.
"""
import datetime
import os
import time
import typing
import uuid
from . import base32, hints, ulid
__all__ = ['new', 'parse', 'from_bytes', 'from_int', 'from_str', 'from_uuid', 'from_timestamp', 'from_randomness']
#: Type hint that ... |
ahawker/ulid | ulid/base32.py | encode | python | def encode(value: hints.Buffer) -> str:
length = len(value)
# Order here is based on assumed hot path.
if length == 16:
return encode_ulid(value)
if length == 6:
return encode_timestamp(value)
if length == 10:
return encode_randomness(value)
raise ValueError('Expects by... | Encode the given :class:`~bytes` instance to a :class:`~str` using Base32 encoding.
.. note:: You should only use this method if you've got a :class:`~bytes` instance
and you are unsure of what it represents. If you know the the _meaning_ of the
:class:`~bytes` instance, you should call the `encode... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L55-L80 | [
"def encode_ulid(value: hints.Buffer) -> str:\n \"\"\"\n Encode the given buffer to a :class:`~str` using Base32 encoding.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID\n bytes specifically and is not meant for arbitrary encoding.\n\n :param value: Bytes... | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | encode_ulid | python | def encode_ulid(value: hints.Buffer) -> str:
length = len(value)
if length != 16:
raise ValueError('Expects 16 bytes for timestamp + randomness; got {}'.format(length))
encoding = ENCODING
return \
encoding[(value[0] & 224) >> 5] + \
encoding[value[0] & 31] + \
encoding... | Encode the given buffer to a :class:`~str` using Base32 encoding.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is not meant for arbitrary encoding.
:param value: Bytes to encode
:type value: :class:`~bytes`, :class:`~bytearray`, or :cl... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L83-L128 | null | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | encode_timestamp | python | def encode_timestamp(timestamp: hints.Buffer) -> str:
length = len(timestamp)
if length != 6:
raise ValueError('Expects 6 bytes for timestamp; got {}'.format(length))
encoding = ENCODING
return \
encoding[(timestamp[0] & 224) >> 5] + \
encoding[timestamp[0] & 31] + \
en... | Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the first 6 bytes of a ULID, which
are a timestamp in milliseconds.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is n... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L131-L163 | null | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | encode_randomness | python | def encode_randomness(randomness: hints.Buffer) -> str:
length = len(randomness)
if length != 10:
raise ValueError('Expects 10 bytes for randomness; got {}'.format(length))
encoding = ENCODING
return \
encoding[(randomness[0] & 248) >> 3] + \
encoding[((randomness[0] & 7) << 2)... | Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the last 10 bytes of a ULID, which
are cryptographically secure random values.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifical... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L166-L204 | null | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | decode | python | def decode(value: str) -> bytes:
length = len(value)
# Order here is based on assumed hot path.
if length == 26:
return decode_ulid(value)
if length == 10:
return decode_timestamp(value)
if length == 16:
return decode_randomness(value)
raise ValueError('Expects string i... | Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.
.. note:: You should only use this method if you've got a :class:`~str` instance
and you are unsure of what it represents. If you know the the _meaning_ of the
:class:`~str` instance, you should call the `decode_*` method ex... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L207-L233 | [
"def decode_ulid(value: str) -> bytes:\n \"\"\"\n Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.\n\n .. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID\n strings specifically and is not meant for arbitrary decoding.\n\n :param value: S... | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | decode_ulid | python | def decode_ulid(value: str) -> bytes:
encoded = str_to_bytes(value, 26)
decoding = DECODING
return bytes((
((decoding[encoded[0]] << 5) | decoding[encoded[1]]) & 0xFF,
((decoding[encoded[2]] << 3) | (decoding[encoded[3]] >> 2)) & 0xFF,
((decoding[encoded[3]] << 6) | (decoding[encod... | Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.
.. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID
strings specifically and is not meant for arbitrary decoding.
:param value: String to decode
:type value: :class:`~str`
:return: Value... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L236-L271 | [
"def str_to_bytes(value: str, expected_length: int) -> bytes:\n \"\"\"\n Convert the given string to bytes and validate it is within the Base32 character set.\n\n :param value: String to convert to bytes\n :type value: :class:`~str`\n :param expected_length: Expected length of the input string\n :... | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
ahawker/ulid | ulid/base32.py | decode_timestamp | python | def decode_timestamp(timestamp: str) -> bytes:
encoded = str_to_bytes(timestamp, 10)
decoding = DECODING
return bytes((
((decoding[encoded[0]] << 5) | decoding[encoded[1]]) & 0xFF,
((decoding[encoded[2]] << 3) | (decoding[encoded[3]] >> 2)) & 0xFF,
((decoding[encoded[3]] << 6) | (d... | Decode the given Base32 encoded :class:`~str` instance to :class:`~bytes`.
The given :class:`~str` are expected to represent the first 10 characters of a ULID, which
are the timestamp in milliseconds.
.. note:: This uses an optimized strategy from the `NUlid` project for decoding ULID
strings spec... | train | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L274-L302 | [
"def str_to_bytes(value: str, expected_length: int) -> bytes:\n \"\"\"\n Convert the given string to bytes and validate it is within the Base32 character set.\n\n :param value: String to convert to bytes\n :type value: :class:`~str`\n :param expected_length: Expected length of the input string\n :... | """
ulid/base32
~~~~~~~~~~~
Functionality for encoding/decoding ULID strings/bytes using Base32 format.
.. note:: This module makes the trade-off of code duplication for inline
computations over multiple function calls for performance reasons. I'll
check metrics in the future to see ho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.