id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,500 | crs4/hl7apy | hl7apy/core.py | Message.to_mllp | def to_mllp(self, encoding_chars=None, trailing_children=False):
"""
Returns the er7 representation of the message wrapped with mllp encoding characters
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)
:type trailing_children: ``bool``
:param trailing_children: if ``True``, trailing children will be added even if their value is ``None``
:return: the ER7-encoded string wrapped with the mllp encoding characters
"""
if encoding_chars is None:
encoding_chars = self.encoding_chars
return "{0}{1}{2}{3}{2}".format(MLLP_ENCODING_CHARS.SB,
self.to_er7(encoding_chars, trailing_children),
MLLP_ENCODING_CHARS.CR,
MLLP_ENCODING_CHARS.EB) | python | def to_mllp(self, encoding_chars=None, trailing_children=False):
if encoding_chars is None:
encoding_chars = self.encoding_chars
return "{0}{1}{2}{3}{2}".format(MLLP_ENCODING_CHARS.SB,
self.to_er7(encoding_chars, trailing_children),
MLLP_ENCODING_CHARS.CR,
MLLP_ENCODING_CHARS.EB) | [
"def",
"to_mllp",
"(",
"self",
",",
"encoding_chars",
"=",
"None",
",",
"trailing_children",
"=",
"False",
")",
":",
"if",
"encoding_chars",
"is",
"None",
":",
"encoding_chars",
"=",
"self",
".",
"encoding_chars",
"return",
"\"{0}{1}{2}{3}{2}\"",
".",
"format",
... | Returns the er7 representation of the message wrapped with mllp encoding characters
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)
:type trailing_children: ``bool``
:param trailing_children: if ``True``, trailing children will be added even if their value is ``None``
:return: the ER7-encoded string wrapped with the mllp encoding characters | [
"Returns",
"the",
"er7",
"representation",
"of",
"the",
"message",
"wrapped",
"with",
"mllp",
"encoding",
"characters"
] | 91be488e9274f6ec975519a1d9c17045bc91bf74 | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L1969-L1988 |
20,501 | playpauseandstop/Flask-And-Redis | flask_redis.py | Redis.get_app | def get_app(self):
"""Get current app from Flast stack to use.
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin.
"""
# First see to connection stack
ctx = connection_stack.top
if ctx is not None:
return ctx.app
# Next return app from instance cache
if self.app is not None:
return self.app
# Something went wrong, in most cases app just not instantiated yet
# and we cannot locate it
raise RuntimeError(
'Flask application not registered on Redis instance '
'and no applcation bound to current context') | python | def get_app(self):
# First see to connection stack
ctx = connection_stack.top
if ctx is not None:
return ctx.app
# Next return app from instance cache
if self.app is not None:
return self.app
# Something went wrong, in most cases app just not instantiated yet
# and we cannot locate it
raise RuntimeError(
'Flask application not registered on Redis instance '
'and no applcation bound to current context') | [
"def",
"get_app",
"(",
"self",
")",
":",
"# First see to connection stack",
"ctx",
"=",
"connection_stack",
".",
"top",
"if",
"ctx",
"is",
"not",
"None",
":",
"return",
"ctx",
".",
"app",
"# Next return app from instance cache",
"if",
"self",
".",
"app",
"is",
... | Get current app from Flast stack to use.
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin. | [
"Get",
"current",
"app",
"from",
"Flast",
"stack",
"to",
"use",
"."
] | 878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5 | https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L79-L98 |
20,502 | playpauseandstop/Flask-And-Redis | flask_redis.py | Redis.init_app | def init_app(self, app, config_prefix=None):
"""
Actual method to read redis settings from app configuration, initialize
Redis connection and copy all public connection methods to current
instance.
:param app: :class:`flask.Flask` application instance.
:param config_prefix: Config prefix to use. By default: ``REDIS``
"""
# Put redis to application extensions
if 'redis' not in app.extensions:
app.extensions['redis'] = {}
# Which config prefix to use, custom or default one?
self.config_prefix = config_prefix = config_prefix or 'REDIS'
# No way to do registration two times
if config_prefix in app.extensions['redis']:
raise ValueError('Already registered config prefix {0!r}.'.
format(config_prefix))
# Start reading configuration, define converters to use and key func
# to prepend config prefix to key value
converters = {'port': int}
convert = lambda arg, value: (converters[arg](value)
if arg in converters
else value)
key = lambda param: '{0}_{1}'.format(config_prefix, param)
# Which redis connection class to use?
klass = app.config.get(key('CLASS'), RedisClass)
# Import connection class if it stil path notation
if isinstance(klass, string_types):
klass = import_string(klass)
# Should we use URL configuration
url = app.config.get(key('URL'))
# If should, parse URL and store values to application config to later
# reuse if necessary
if url:
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(url)
# URL could contains host, port, user, password and db values
app.config[key('HOST')] = url.hostname
app.config[key('PORT')] = url.port or 6379
app.config[key('USER')] = url.username
app.config[key('PASSWORD')] = url.password
db = url.path.replace('/', '')
app.config[key('DB')] = db if db.isdigit() else None
# Host is not a mandatory key if you want to use connection pool. But
# when present and starts with file:// or / use it as unix socket path
host = app.config.get(key('HOST'))
if host and (host.startswith('file://') or host.startswith('/')):
app.config.pop(key('HOST'))
app.config[key('UNIX_SOCKET_PATH')] = host
args = self._build_connection_args(klass)
kwargs = dict([(arg, convert(arg, app.config[key(arg.upper())]))
for arg in args
if key(arg.upper()) in app.config])
# Initialize connection and store it to extensions
connection = klass(**kwargs)
app.extensions['redis'][config_prefix] = connection
# Include public methods to current instance
self._include_public_methods(connection) | python | def init_app(self, app, config_prefix=None):
# Put redis to application extensions
if 'redis' not in app.extensions:
app.extensions['redis'] = {}
# Which config prefix to use, custom or default one?
self.config_prefix = config_prefix = config_prefix or 'REDIS'
# No way to do registration two times
if config_prefix in app.extensions['redis']:
raise ValueError('Already registered config prefix {0!r}.'.
format(config_prefix))
# Start reading configuration, define converters to use and key func
# to prepend config prefix to key value
converters = {'port': int}
convert = lambda arg, value: (converters[arg](value)
if arg in converters
else value)
key = lambda param: '{0}_{1}'.format(config_prefix, param)
# Which redis connection class to use?
klass = app.config.get(key('CLASS'), RedisClass)
# Import connection class if it stil path notation
if isinstance(klass, string_types):
klass = import_string(klass)
# Should we use URL configuration
url = app.config.get(key('URL'))
# If should, parse URL and store values to application config to later
# reuse if necessary
if url:
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(url)
# URL could contains host, port, user, password and db values
app.config[key('HOST')] = url.hostname
app.config[key('PORT')] = url.port or 6379
app.config[key('USER')] = url.username
app.config[key('PASSWORD')] = url.password
db = url.path.replace('/', '')
app.config[key('DB')] = db if db.isdigit() else None
# Host is not a mandatory key if you want to use connection pool. But
# when present and starts with file:// or / use it as unix socket path
host = app.config.get(key('HOST'))
if host and (host.startswith('file://') or host.startswith('/')):
app.config.pop(key('HOST'))
app.config[key('UNIX_SOCKET_PATH')] = host
args = self._build_connection_args(klass)
kwargs = dict([(arg, convert(arg, app.config[key(arg.upper())]))
for arg in args
if key(arg.upper()) in app.config])
# Initialize connection and store it to extensions
connection = klass(**kwargs)
app.extensions['redis'][config_prefix] = connection
# Include public methods to current instance
self._include_public_methods(connection) | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"config_prefix",
"=",
"None",
")",
":",
"# Put redis to application extensions",
"if",
"'redis'",
"not",
"in",
"app",
".",
"extensions",
":",
"app",
".",
"extensions",
"[",
"'redis'",
"]",
"=",
"{",
"}",
"# ... | Actual method to read redis settings from app configuration, initialize
Redis connection and copy all public connection methods to current
instance.
:param app: :class:`flask.Flask` application instance.
:param config_prefix: Config prefix to use. By default: ``REDIS`` | [
"Actual",
"method",
"to",
"read",
"redis",
"settings",
"from",
"app",
"configuration",
"initialize",
"Redis",
"connection",
"and",
"copy",
"all",
"public",
"connection",
"methods",
"to",
"current",
"instance",
"."
] | 878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5 | https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L100-L170 |
20,503 | playpauseandstop/Flask-And-Redis | flask_redis.py | Redis._build_connection_args | def _build_connection_args(self, klass):
"""Read connection args spec, exclude self from list of possible
:param klass: Redis connection class.
"""
bases = [base for base in klass.__bases__ if base is not object]
all_args = []
for cls in [klass] + bases:
try:
args = inspect.getfullargspec(cls.__init__).args
except AttributeError:
args = inspect.getargspec(cls.__init__).args
for arg in args:
if arg in all_args:
continue
all_args.append(arg)
all_args.remove('self')
return all_args | python | def _build_connection_args(self, klass):
bases = [base for base in klass.__bases__ if base is not object]
all_args = []
for cls in [klass] + bases:
try:
args = inspect.getfullargspec(cls.__init__).args
except AttributeError:
args = inspect.getargspec(cls.__init__).args
for arg in args:
if arg in all_args:
continue
all_args.append(arg)
all_args.remove('self')
return all_args | [
"def",
"_build_connection_args",
"(",
"self",
",",
"klass",
")",
":",
"bases",
"=",
"[",
"base",
"for",
"base",
"in",
"klass",
".",
"__bases__",
"if",
"base",
"is",
"not",
"object",
"]",
"all_args",
"=",
"[",
"]",
"for",
"cls",
"in",
"[",
"klass",
"]... | Read connection args spec, exclude self from list of possible
:param klass: Redis connection class. | [
"Read",
"connection",
"args",
"spec",
"exclude",
"self",
"from",
"list",
"of",
"possible"
] | 878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5 | https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L172-L189 |
20,504 | playpauseandstop/Flask-And-Redis | flask_redis.py | Redis._include_public_methods | def _include_public_methods(self, connection):
"""Include public methods from Redis connection to current instance.
:param connection: Redis connection instance.
"""
for attr in dir(connection):
value = getattr(connection, attr)
if attr.startswith('_') or not callable(value):
continue
self.__dict__[attr] = self._wrap_public_method(attr) | python | def _include_public_methods(self, connection):
for attr in dir(connection):
value = getattr(connection, attr)
if attr.startswith('_') or not callable(value):
continue
self.__dict__[attr] = self._wrap_public_method(attr) | [
"def",
"_include_public_methods",
"(",
"self",
",",
"connection",
")",
":",
"for",
"attr",
"in",
"dir",
"(",
"connection",
")",
":",
"value",
"=",
"getattr",
"(",
"connection",
",",
"attr",
")",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
")",
"or",
"... | Include public methods from Redis connection to current instance.
:param connection: Redis connection instance. | [
"Include",
"public",
"methods",
"from",
"Redis",
"connection",
"to",
"current",
"instance",
"."
] | 878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5 | https://github.com/playpauseandstop/Flask-And-Redis/blob/878bb193ae4a8c3497f6f1ff1511a3b8c96d08b5/flask_redis.py#L191-L200 |
20,505 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.prepare | def prepare(self):
'''Prepare to run the docker command'''
self.__make_scubadir()
if self.is_remote_docker:
'''
Docker is running remotely (e.g. boot2docker on OSX).
We don't need to do any user setup whatsoever.
TODO: For now, remote instances won't have any .scubainit
See:
https://github.com/JonathonReinhart/scuba/issues/17
'''
raise ScubaError('Remote docker not supported (DOCKER_HOST is set)')
# Docker is running natively
self.__setup_native_run()
# Apply environment vars from .scuba.yml
self.env_vars.update(self.context.environment) | python | def prepare(self):
'''Prepare to run the docker command'''
self.__make_scubadir()
if self.is_remote_docker:
'''
Docker is running remotely (e.g. boot2docker on OSX).
We don't need to do any user setup whatsoever.
TODO: For now, remote instances won't have any .scubainit
See:
https://github.com/JonathonReinhart/scuba/issues/17
'''
raise ScubaError('Remote docker not supported (DOCKER_HOST is set)')
# Docker is running natively
self.__setup_native_run()
# Apply environment vars from .scuba.yml
self.env_vars.update(self.context.environment) | [
"def",
"prepare",
"(",
"self",
")",
":",
"self",
".",
"__make_scubadir",
"(",
")",
"if",
"self",
".",
"is_remote_docker",
":",
"'''\n Docker is running remotely (e.g. boot2docker on OSX).\n We don't need to do any user setup whatsoever.\n\n TODO: For ... | Prepare to run the docker command | [
"Prepare",
"to",
"run",
"the",
"docker",
"command"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L119-L139 |
20,506 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.add_env | def add_env(self, name, val):
'''Add an environment variable to the docker run invocation
'''
if name in self.env_vars:
raise KeyError(name)
self.env_vars[name] = val | python | def add_env(self, name, val):
'''Add an environment variable to the docker run invocation
'''
if name in self.env_vars:
raise KeyError(name)
self.env_vars[name] = val | [
"def",
"add_env",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"if",
"name",
"in",
"self",
".",
"env_vars",
":",
"raise",
"KeyError",
"(",
"name",
")",
"self",
".",
"env_vars",
"[",
"name",
"]",
"=",
"val"
] | Add an environment variable to the docker run invocation | [
"Add",
"an",
"environment",
"variable",
"to",
"the",
"docker",
"run",
"invocation"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L176-L181 |
20,507 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.__locate_scubainit | def __locate_scubainit(self):
'''Determine path to scubainit binary
'''
pkg_path = os.path.dirname(__file__)
self.scubainit_path = os.path.join(pkg_path, 'scubainit')
if not os.path.isfile(self.scubainit_path):
raise ScubaError('scubainit not found at "{}"'.format(self.scubainit_path)) | python | def __locate_scubainit(self):
'''Determine path to scubainit binary
'''
pkg_path = os.path.dirname(__file__)
self.scubainit_path = os.path.join(pkg_path, 'scubainit')
if not os.path.isfile(self.scubainit_path):
raise ScubaError('scubainit not found at "{}"'.format(self.scubainit_path)) | [
"def",
"__locate_scubainit",
"(",
"self",
")",
":",
"pkg_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"self",
".",
"scubainit_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pkg_path",
",",
"'scubainit'",
")",
"if",
"not",
"os... | Determine path to scubainit binary | [
"Determine",
"path",
"to",
"scubainit",
"binary"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L198-L205 |
20,508 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.__load_config | def __load_config(self):
'''Find and load .scuba.yml
'''
# top_path is where .scuba.yml is found, and becomes the top of our bind mount.
# top_rel is the relative path from top_path to the current working directory,
# and is where we'll set the working directory in the container (relative to
# the bind mount point).
try:
top_path, top_rel = find_config()
self.config = load_config(os.path.join(top_path, SCUBA_YML))
except ConfigNotFoundError as cfgerr:
# SCUBA_YML can be missing if --image was given.
# In this case, we assume a default config
if not self.image_override:
raise ScubaError(str(cfgerr))
top_path, top_rel = os.getcwd(), ''
self.config = ScubaConfig(image=None)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
# Mount scuba root directory at the same path in the container...
self.add_volume(top_path, top_path)
# ...and set the working dir relative to it
self.set_workdir(os.path.join(top_path, top_rel))
self.add_env('SCUBA_ROOT', top_path) | python | def __load_config(self):
'''Find and load .scuba.yml
'''
# top_path is where .scuba.yml is found, and becomes the top of our bind mount.
# top_rel is the relative path from top_path to the current working directory,
# and is where we'll set the working directory in the container (relative to
# the bind mount point).
try:
top_path, top_rel = find_config()
self.config = load_config(os.path.join(top_path, SCUBA_YML))
except ConfigNotFoundError as cfgerr:
# SCUBA_YML can be missing if --image was given.
# In this case, we assume a default config
if not self.image_override:
raise ScubaError(str(cfgerr))
top_path, top_rel = os.getcwd(), ''
self.config = ScubaConfig(image=None)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
# Mount scuba root directory at the same path in the container...
self.add_volume(top_path, top_path)
# ...and set the working dir relative to it
self.set_workdir(os.path.join(top_path, top_rel))
self.add_env('SCUBA_ROOT', top_path) | [
"def",
"__load_config",
"(",
"self",
")",
":",
"# top_path is where .scuba.yml is found, and becomes the top of our bind mount.",
"# top_rel is the relative path from top_path to the current working directory,",
"# and is where we'll set the working directory in the container (relative to",
"# the... | Find and load .scuba.yml | [
"Find",
"and",
"load",
".",
"scuba",
".",
"yml"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L208-L235 |
20,509 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.__make_scubadir | def __make_scubadir(self):
'''Make temp directory where all ancillary files are bind-mounted
'''
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath) | python | def __make_scubadir(self):
'''Make temp directory where all ancillary files are bind-mounted
'''
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath) | [
"def",
"__make_scubadir",
"(",
"self",
")",
":",
"self",
".",
"__scubadir_hostpath",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'scubadir'",
")",
"self",
".",
"__scubadir_contpath",
"=",
"'/.scuba'",
"self",
".",
"add_volume",
"(",
"self",
".",
"_... | Make temp directory where all ancillary files are bind-mounted | [
"Make",
"temp",
"directory",
"where",
"all",
"ancillary",
"files",
"are",
"bind",
"-",
"mounted"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L237-L242 |
20,510 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.__setup_native_run | def __setup_native_run(self):
# These options are appended to mounted volume arguments
# NOTE: This tells Docker to re-label the directory for compatibility
# with SELinux. See `man docker-run` for more information.
self.vol_opts = ['z']
# Pass variables to scubainit
self.add_env('SCUBAINIT_UMASK', '{:04o}'.format(get_umask()))
if not self.as_root:
self.add_env('SCUBAINIT_UID', os.getuid())
self.add_env('SCUBAINIT_GID', os.getgid())
if self.verbose:
self.add_env('SCUBAINIT_VERBOSE', 1)
# Copy scubainit into the container
# We make a copy because Docker 1.13 gets pissed if we try to re-label
# /usr, and Fedora 28 gives an AVC denial.
scubainit_cpath = self.copy_scubadir_file('scubainit', self.scubainit_path)
# Hooks
for name in ('root', 'user', ):
self.__generate_hook_script(name)
# allocate TTY if scuba's output is going to a terminal
# and stdin is not redirected
if sys.stdout.isatty() and sys.stdin.isatty():
self.add_option('--tty')
# Process any aliases
try:
context = self.config.process_command(self.user_command)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
if self.image_override:
context.image = self.image_override
'''
Normally, if the user provides no command to "docker run", the image's
default CMD is run. Because we set the entrypiont, scuba must emulate the
default behavior itself.
'''
if not context.script:
# No user-provided command; we want to run the image's default command
verbose_msg('No user command; getting command from image')
default_cmd = get_image_command(context.image)
if not default_cmd:
raise ScubaError('No command given and no image-specified command')
verbose_msg('{} Cmd: "{}"'.format(context.image, default_cmd))
context.script = [shell_quote_cmd(default_cmd)]
# Make scubainit the real entrypoint, and use the defined entrypoint as
# the docker command (if it exists)
self.add_option('--entrypoint={}'.format(scubainit_cpath))
self.docker_cmd = []
if self.entrypoint_override is not None:
# --entrypoint takes precedence
if self.entrypoint_override != '':
self.docker_cmd = [self.entrypoint_override]
elif context.entrypoint is not None:
# then .scuba.yml
if context.entrypoint != '':
self.docker_cmd = [context.entrypoint]
else:
ep = get_image_entrypoint(context.image)
if ep:
self.docker_cmd = ep
# The user command is executed via a generated shell script
with self.open_scubadir_file('command.sh', 'wt') as f:
self.docker_cmd += ['/bin/sh', f.container_path]
writeln(f, '#!/bin/sh')
writeln(f, '# Auto-generated from scuba')
writeln(f, 'set -e')
for cmd in context.script:
writeln(f, cmd)
self.context = context | python | def __setup_native_run(self):
# These options are appended to mounted volume arguments
# NOTE: This tells Docker to re-label the directory for compatibility
# with SELinux. See `man docker-run` for more information.
self.vol_opts = ['z']
# Pass variables to scubainit
self.add_env('SCUBAINIT_UMASK', '{:04o}'.format(get_umask()))
if not self.as_root:
self.add_env('SCUBAINIT_UID', os.getuid())
self.add_env('SCUBAINIT_GID', os.getgid())
if self.verbose:
self.add_env('SCUBAINIT_VERBOSE', 1)
# Copy scubainit into the container
# We make a copy because Docker 1.13 gets pissed if we try to re-label
# /usr, and Fedora 28 gives an AVC denial.
scubainit_cpath = self.copy_scubadir_file('scubainit', self.scubainit_path)
# Hooks
for name in ('root', 'user', ):
self.__generate_hook_script(name)
# allocate TTY if scuba's output is going to a terminal
# and stdin is not redirected
if sys.stdout.isatty() and sys.stdin.isatty():
self.add_option('--tty')
# Process any aliases
try:
context = self.config.process_command(self.user_command)
except ConfigError as cfgerr:
raise ScubaError(str(cfgerr))
if self.image_override:
context.image = self.image_override
'''
Normally, if the user provides no command to "docker run", the image's
default CMD is run. Because we set the entrypiont, scuba must emulate the
default behavior itself.
'''
if not context.script:
# No user-provided command; we want to run the image's default command
verbose_msg('No user command; getting command from image')
default_cmd = get_image_command(context.image)
if not default_cmd:
raise ScubaError('No command given and no image-specified command')
verbose_msg('{} Cmd: "{}"'.format(context.image, default_cmd))
context.script = [shell_quote_cmd(default_cmd)]
# Make scubainit the real entrypoint, and use the defined entrypoint as
# the docker command (if it exists)
self.add_option('--entrypoint={}'.format(scubainit_cpath))
self.docker_cmd = []
if self.entrypoint_override is not None:
# --entrypoint takes precedence
if self.entrypoint_override != '':
self.docker_cmd = [self.entrypoint_override]
elif context.entrypoint is not None:
# then .scuba.yml
if context.entrypoint != '':
self.docker_cmd = [context.entrypoint]
else:
ep = get_image_entrypoint(context.image)
if ep:
self.docker_cmd = ep
# The user command is executed via a generated shell script
with self.open_scubadir_file('command.sh', 'wt') as f:
self.docker_cmd += ['/bin/sh', f.container_path]
writeln(f, '#!/bin/sh')
writeln(f, '# Auto-generated from scuba')
writeln(f, 'set -e')
for cmd in context.script:
writeln(f, cmd)
self.context = context | [
"def",
"__setup_native_run",
"(",
"self",
")",
":",
"# These options are appended to mounted volume arguments",
"# NOTE: This tells Docker to re-label the directory for compatibility",
"# with SELinux. See `man docker-run` for more information.",
"self",
".",
"vol_opts",
"=",
"[",
"'z'",... | Normally, if the user provides no command to "docker run", the image's
default CMD is run. Because we set the entrypiont, scuba must emulate the
default behavior itself. | [
"Normally",
"if",
"the",
"user",
"provides",
"no",
"command",
"to",
"docker",
"run",
"the",
"image",
"s",
"default",
"CMD",
"is",
"run",
".",
"Because",
"we",
"set",
"the",
"entrypiont",
"scuba",
"must",
"emulate",
"the",
"default",
"behavior",
"itself",
"... | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L244-L326 |
20,511 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.open_scubadir_file | def open_scubadir_file(self, name, mode):
'''Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object.
'''
path = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(path)
# Make any directories required
mkdir_p(os.path.dirname(path))
f = File(path, mode)
f.container_path = os.path.join(self.__scubadir_contpath, name)
return f | python | def open_scubadir_file(self, name, mode):
'''Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object.
'''
path = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(path)
# Make any directories required
mkdir_p(os.path.dirname(path))
f = File(path, mode)
f.container_path = os.path.join(self.__scubadir_contpath, name)
return f | [
"def",
"open_scubadir_file",
"(",
"self",
",",
"name",
",",
"mode",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__scubadir_hostpath",
",",
"name",
")",
"assert",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",... | Opens a file in the 'scubadir'
This file will automatically be bind-mounted into the container,
at a path given by the 'container_path' property on the returned file object. | [
"Opens",
"a",
"file",
"in",
"the",
"scubadir"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L330-L344 |
20,512 | JonathonReinhart/scuba | scuba/__main__.py | ScubaDive.copy_scubadir_file | def copy_scubadir_file(self, name, source):
'''Copies source into the scubadir
Returns the container-path of the copied file
'''
dest = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(dest)
shutil.copy2(source, dest)
return os.path.join(self.__scubadir_contpath, name) | python | def copy_scubadir_file(self, name, source):
'''Copies source into the scubadir
Returns the container-path of the copied file
'''
dest = os.path.join(self.__scubadir_hostpath, name)
assert not os.path.exists(dest)
shutil.copy2(source, dest)
return os.path.join(self.__scubadir_contpath, name) | [
"def",
"copy_scubadir_file",
"(",
"self",
",",
"name",
",",
"source",
")",
":",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"__scubadir_hostpath",
",",
"name",
")",
"assert",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")... | Copies source into the scubadir
Returns the container-path of the copied file | [
"Copies",
"source",
"into",
"the",
"scubadir"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/__main__.py#L347-L356 |
20,513 | JonathonReinhart/scuba | scuba/utils.py | format_cmdline | def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
line = ''
for a in (shell_quote(a) for a in args):
# If adding this argument will make the line too long,
# yield the current line, and start a new one.
if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
# Append this argument to the current line, separating
# it by a space from the existing arguments.
if line:
line += ' ' + a
else:
line = a
yield line
return ' \\\n'.join(lines()) | python | def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
line = ''
for a in (shell_quote(a) for a in args):
# If adding this argument will make the line too long,
# yield the current line, and start a new one.
if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
# Append this argument to the current line, separating
# it by a space from the existing arguments.
if line:
line += ' ' + a
else:
line = a
yield line
return ' \\\n'.join(lines()) | [
"def",
"format_cmdline",
"(",
"args",
",",
"maxwidth",
"=",
"80",
")",
":",
"# Leave room for the space and backslash at the end of each line",
"maxwidth",
"-=",
"2",
"def",
"lines",
"(",
")",
":",
"line",
"=",
"''",
"for",
"a",
"in",
"(",
"shell_quote",
"(",
... | Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument. | [
"Format",
"args",
"into",
"a",
"shell",
"-",
"quoted",
"command",
"line",
"."
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/utils.py#L13-L41 |
20,514 | JonathonReinhart/scuba | scuba/utils.py | parse_env_var | def parse_env_var(s):
"""Parse an environment variable string
Returns a key-value tuple
Apply the same logic as `docker run -e`:
"If the operator names an environment variable without specifying a value,
then the current value of the named variable is propagated into the
container's environment
"""
parts = s.split('=', 1)
if len(parts) == 2:
k, v = parts
return (k, v)
k = parts[0]
return (k, os.getenv(k, '')) | python | def parse_env_var(s):
parts = s.split('=', 1)
if len(parts) == 2:
k, v = parts
return (k, v)
k = parts[0]
return (k, os.getenv(k, '')) | [
"def",
"parse_env_var",
"(",
"s",
")",
":",
"parts",
"=",
"s",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"2",
":",
"k",
",",
"v",
"=",
"parts",
"return",
"(",
"k",
",",
"v",
")",
"k",
"=",
"parts",
"[",
... | Parse an environment variable string
Returns a key-value tuple
Apply the same logic as `docker run -e`:
"If the operator names an environment variable without specifying a value,
then the current value of the named variable is propagated into the
container's environment | [
"Parse",
"an",
"environment",
"variable",
"string"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/utils.py#L53-L69 |
20,515 | JonathonReinhart/scuba | scuba/dockerutil.py | __wrap_docker_exec | def __wrap_docker_exec(func):
'''Wrap a function to raise DockerExecuteError on ENOENT'''
def call(*args, **kwargs):
try:
return func(*args, **kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
raise DockerExecuteError('Failed to execute docker. Is it installed?')
raise
return call | python | def __wrap_docker_exec(func):
'''Wrap a function to raise DockerExecuteError on ENOENT'''
def call(*args, **kwargs):
try:
return func(*args, **kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
raise DockerExecuteError('Failed to execute docker. Is it installed?')
raise
return call | [
"def",
"__wrap_docker_exec",
"(",
"func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
... | Wrap a function to raise DockerExecuteError on ENOENT | [
"Wrap",
"a",
"function",
"to",
"raise",
"DockerExecuteError",
"on",
"ENOENT"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L19-L28 |
20,516 | JonathonReinhart/scuba | scuba/dockerutil.py | docker_inspect | def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if not p.returncode == 0:
if 'no such image' in stderr.lower():
raise NoSuchImageError(image)
raise DockerError('Failed to inspect image: {}'.format(stderr.strip()))
return json.loads(stdout)[0] | python | def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if not p.returncode == 0:
if 'no such image' in stderr.lower():
raise NoSuchImageError(image)
raise DockerError('Failed to inspect image: {}'.format(stderr.strip()))
return json.loads(stdout)[0] | [
"def",
"docker_inspect",
"(",
"image",
")",
":",
"args",
"=",
"[",
"'docker'",
",",
"'inspect'",
",",
"'--type'",
",",
"'image'",
",",
"image",
"]",
"p",
"=",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"s... | Inspects a docker image
Returns: Parsed JSON data | [
"Inspects",
"a",
"docker",
"image"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L34-L51 |
20,517 | JonathonReinhart/scuba | scuba/dockerutil.py | docker_pull | def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image)) | python | def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image)) | [
"def",
"docker_pull",
"(",
"image",
")",
":",
"args",
"=",
"[",
"'docker'",
",",
"'pull'",
",",
"image",
"]",
"# If this fails, the default docker stdout/stderr looks good to the user.",
"ret",
"=",
"call",
"(",
"args",
")",
"if",
"ret",
"!=",
"0",
":",
"raise",... | Pulls an image | [
"Pulls",
"an",
"image"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L53-L60 |
20,518 | JonathonReinhart/scuba | scuba/dockerutil.py | get_image_command | def get_image_command(image):
'''Gets the default command for an image'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Cmd']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke)) | python | def get_image_command(image):
'''Gets the default command for an image'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Cmd']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke)) | [
"def",
"get_image_command",
"(",
"image",
")",
":",
"info",
"=",
"docker_inspect_or_pull",
"(",
"image",
")",
"try",
":",
"return",
"info",
"[",
"'Config'",
"]",
"[",
"'Cmd'",
"]",
"except",
"KeyError",
"as",
"ke",
":",
"raise",
"DockerError",
"(",
"'Faile... | Gets the default command for an image | [
"Gets",
"the",
"default",
"command",
"for",
"an",
"image"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L71-L77 |
20,519 | JonathonReinhart/scuba | scuba/dockerutil.py | get_image_entrypoint | def get_image_entrypoint(image):
'''Gets the image entrypoint'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Entrypoint']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke)) | python | def get_image_entrypoint(image):
'''Gets the image entrypoint'''
info = docker_inspect_or_pull(image)
try:
return info['Config']['Entrypoint']
except KeyError as ke:
raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke)) | [
"def",
"get_image_entrypoint",
"(",
"image",
")",
":",
"info",
"=",
"docker_inspect_or_pull",
"(",
"image",
")",
"try",
":",
"return",
"info",
"[",
"'Config'",
"]",
"[",
"'Entrypoint'",
"]",
"except",
"KeyError",
"as",
"ke",
":",
"raise",
"DockerError",
"(",... | Gets the image entrypoint | [
"Gets",
"the",
"image",
"entrypoint"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L79-L85 |
20,520 | JonathonReinhart/scuba | scuba/dockerutil.py | make_vol_opt | def make_vol_opt(hostdir, contdir, options=None):
'''Generate a docker volume option'''
vol = '--volume={}:{}'.format(hostdir, contdir)
if options != None:
if isinstance(options, str):
options = (options,)
vol += ':' + ','.join(options)
return vol | python | def make_vol_opt(hostdir, contdir, options=None):
'''Generate a docker volume option'''
vol = '--volume={}:{}'.format(hostdir, contdir)
if options != None:
if isinstance(options, str):
options = (options,)
vol += ':' + ','.join(options)
return vol | [
"def",
"make_vol_opt",
"(",
"hostdir",
",",
"contdir",
",",
"options",
"=",
"None",
")",
":",
"vol",
"=",
"'--volume={}:{}'",
".",
"format",
"(",
"hostdir",
",",
"contdir",
")",
"if",
"options",
"!=",
"None",
":",
"if",
"isinstance",
"(",
"options",
",",... | Generate a docker volume option | [
"Generate",
"a",
"docker",
"volume",
"option"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/dockerutil.py#L88-L95 |
20,521 | JonathonReinhart/scuba | scuba/config.py | find_config | def find_config():
'''Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current directory
'''
cross_fs = 'SCUBA_DISCOVERY_ACROSS_FILESYSTEM' in os.environ
path = os.getcwd()
rel = ''
while True:
if os.path.exists(os.path.join(path, SCUBA_YML)):
return path, rel
if not cross_fs and os.path.ismount(path):
msg = '{} not found here or any parent up to mount point {}'.format(SCUBA_YML, path) \
+ '\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).'
raise ConfigNotFoundError(msg)
# Traverse up directory hierarchy
path, rest = os.path.split(path)
if not rest:
raise ConfigNotFoundError('{} not found here or any parent directories'.format(SCUBA_YML))
# Accumulate the relative path back to where we started
rel = os.path.join(rest, rel) | python | def find_config():
'''Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current directory
'''
cross_fs = 'SCUBA_DISCOVERY_ACROSS_FILESYSTEM' in os.environ
path = os.getcwd()
rel = ''
while True:
if os.path.exists(os.path.join(path, SCUBA_YML)):
return path, rel
if not cross_fs and os.path.ismount(path):
msg = '{} not found here or any parent up to mount point {}'.format(SCUBA_YML, path) \
+ '\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).'
raise ConfigNotFoundError(msg)
# Traverse up directory hierarchy
path, rest = os.path.split(path)
if not rest:
raise ConfigNotFoundError('{} not found here or any parent directories'.format(SCUBA_YML))
# Accumulate the relative path back to where we started
rel = os.path.join(rest, rel) | [
"def",
"find_config",
"(",
")",
":",
"cross_fs",
"=",
"'SCUBA_DISCOVERY_ACROSS_FILESYSTEM'",
"in",
"os",
".",
"environ",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"rel",
"=",
"''",
"while",
"True",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"o... | Search up the diretcory hierarchy for .scuba.yml
Returns: path, rel on success, or None if not found
path The absolute path of the directory where .scuba.yml was found
rel The relative path from the directory where .scuba.yml was found
to the current directory | [
"Search",
"up",
"the",
"diretcory",
"hierarchy",
"for",
".",
"scuba",
".",
"yml"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/config.py#L74-L101 |
20,522 | JonathonReinhart/scuba | scuba/config.py | _process_script_node | def _process_script_node(node, name):
'''Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md.
'''
if isinstance(node, basestring):
# The script is just the text itself
return [node]
if isinstance(node, dict):
# There must be a "script" key, which must be a list of strings
script = node.get('script')
if not script:
raise ConfigError("{}: must have a 'script' subkey".format(name))
if isinstance(script, list):
return script
if isinstance(script, basestring):
return [script]
raise ConfigError("{}.script: must be a string or list".format(name))
raise ConfigError("{}: must be string or dict".format(name)) | python | def _process_script_node(node, name):
'''Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md.
'''
if isinstance(node, basestring):
# The script is just the text itself
return [node]
if isinstance(node, dict):
# There must be a "script" key, which must be a list of strings
script = node.get('script')
if not script:
raise ConfigError("{}: must have a 'script' subkey".format(name))
if isinstance(script, list):
return script
if isinstance(script, basestring):
return [script]
raise ConfigError("{}.script: must be a string or list".format(name))
raise ConfigError("{}: must be string or dict".format(name)) | [
"def",
"_process_script_node",
"(",
"node",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"basestring",
")",
":",
"# The script is just the text itself",
"return",
"[",
"node",
"]",
"if",
"isinstance",
"(",
"node",
",",
"dict",
")",
":",
"# Th... | Process a script-type node
This handles nodes that follow the *Common script schema*,
as outlined in doc/yaml-reference.md. | [
"Process",
"a",
"script",
"-",
"type",
"node"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/config.py#L104-L129 |
20,523 | JonathonReinhart/scuba | scuba/config.py | ScubaConfig.process_command | def process_command(self, command):
'''Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image name to use
'''
result = ScubaContext()
result.script = None
result.image = self.image
result.entrypoint = self.entrypoint
result.environment = self.environment.copy()
if command:
alias = self.aliases.get(command[0])
if not alias:
# Command is not an alias; use it as-is.
result.script = [shell_quote_cmd(command)]
else:
# Using an alias
# Does this alias override the image and/or entrypoint?
if alias.image:
result.image = alias.image
if alias.entrypoint is not None:
result.entrypoint = alias.entrypoint
# Merge/override the environment
if alias.environment:
result.environment.update(alias.environment)
if len(alias.script) > 1:
# Alias is a multiline script; no additional
# arguments are allowed in the scuba invocation.
if len(command) > 1:
raise ConfigError('Additional arguments not allowed with multi-line aliases')
result.script = alias.script
else:
# Alias is a single-line script; perform substituion
# and add user arguments.
command.pop(0)
result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
result.script = flatten_list(result.script)
return result | python | def process_command(self, command):
'''Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image name to use
'''
result = ScubaContext()
result.script = None
result.image = self.image
result.entrypoint = self.entrypoint
result.environment = self.environment.copy()
if command:
alias = self.aliases.get(command[0])
if not alias:
# Command is not an alias; use it as-is.
result.script = [shell_quote_cmd(command)]
else:
# Using an alias
# Does this alias override the image and/or entrypoint?
if alias.image:
result.image = alias.image
if alias.entrypoint is not None:
result.entrypoint = alias.entrypoint
# Merge/override the environment
if alias.environment:
result.environment.update(alias.environment)
if len(alias.script) > 1:
# Alias is a multiline script; no additional
# arguments are allowed in the scuba invocation.
if len(command) > 1:
raise ConfigError('Additional arguments not allowed with multi-line aliases')
result.script = alias.script
else:
# Alias is a single-line script; perform substituion
# and add user arguments.
command.pop(0)
result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
result.script = flatten_list(result.script)
return result | [
"def",
"process_command",
"(",
"self",
",",
"command",
")",
":",
"result",
"=",
"ScubaContext",
"(",
")",
"result",
".",
"script",
"=",
"None",
"result",
".",
"image",
"=",
"self",
".",
"image",
"result",
".",
"entrypoint",
"=",
"self",
".",
"entrypoint"... | Processes a user command using aliases
Arguments:
command A user command list (e.g. argv)
Returns: A ScubaContext object with the following attributes:
script: a list of command line strings
image: the docker image name to use | [
"Processes",
"a",
"user",
"command",
"using",
"aliases"
] | 0244c81ec482d3c60202028bc075621447bc3ad1 | https://github.com/JonathonReinhart/scuba/blob/0244c81ec482d3c60202028bc075621447bc3ad1/scuba/config.py#L276-L324 |
20,524 | chrislim2888/IP2Location-Python | IP2Location.py | IP2Location.open | def open(self, filename):
''' Opens a database file '''
# Ensure old file is closed before opening a new one
self.close()
self._f = open(filename, 'rb')
self._dbtype = struct.unpack('B', self._f.read(1))[0]
self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
self._dbyear = struct.unpack('B', self._f.read(1))[0]
self._dbmonth = struct.unpack('B', self._f.read(1))[0]
self._dbday = struct.unpack('B', self._f.read(1))[0]
self._ipv4dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv4dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv4indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6indexbaseaddr = struct.unpack('<I', self._f.read(4))[0] | python | def open(self, filename):
''' Opens a database file '''
# Ensure old file is closed before opening a new one
self.close()
self._f = open(filename, 'rb')
self._dbtype = struct.unpack('B', self._f.read(1))[0]
self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
self._dbyear = struct.unpack('B', self._f.read(1))[0]
self._dbmonth = struct.unpack('B', self._f.read(1))[0]
self._dbday = struct.unpack('B', self._f.read(1))[0]
self._ipv4dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv4dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv4indexbaseaddr = struct.unpack('<I', self._f.read(4))[0]
self._ipv6indexbaseaddr = struct.unpack('<I', self._f.read(4))[0] | [
"def",
"open",
"(",
"self",
",",
"filename",
")",
":",
"# Ensure old file is closed before opening a new one",
"self",
".",
"close",
"(",
")",
"self",
".",
"_f",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"self",
".",
"_dbtype",
"=",
"struct",
".",
"u... | Opens a database file | [
"Opens",
"a",
"database",
"file"
] | 6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621 | https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L105-L121 |
20,525 | chrislim2888/IP2Location-Python | IP2Location.py | IP2Location._parse_addr | def _parse_addr(self, addr):
''' Parses address and returns IP version. Raises exception on invalid argument '''
ipv = 0
try:
socket.inet_pton(socket.AF_INET6, addr)
# Convert ::FFFF:x.y.z.y to IPv4
if addr.lower().startswith('::ffff:'):
try:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
except:
ipv = 6
else:
ipv = 6
except:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
return ipv | python | def _parse_addr(self, addr):
''' Parses address and returns IP version. Raises exception on invalid argument '''
ipv = 0
try:
socket.inet_pton(socket.AF_INET6, addr)
# Convert ::FFFF:x.y.z.y to IPv4
if addr.lower().startswith('::ffff:'):
try:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
except:
ipv = 6
else:
ipv = 6
except:
socket.inet_pton(socket.AF_INET, addr)
ipv = 4
return ipv | [
"def",
"_parse_addr",
"(",
"self",
",",
"addr",
")",
":",
"ipv",
"=",
"0",
"try",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"addr",
")",
"# Convert ::FFFF:x.y.z.y to IPv4",
"if",
"addr",
".",
"lower",
"(",
")",
".",
"startswit... | Parses address and returns IP version. Raises exception on invalid argument | [
"Parses",
"address",
"and",
"returns",
"IP",
"version",
".",
"Raises",
"exception",
"on",
"invalid",
"argument"
] | 6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621 | https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L342-L359 |
20,526 | taxjar/taxjar-python | taxjar/client.py | Client.rates_for_location | def rates_for_location(self, postal_code, location_deets=None):
"""Shows the sales tax rates for a given location."""
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request) | python | def rates_for_location(self, postal_code, location_deets=None):
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request) | [
"def",
"rates_for_location",
"(",
"self",
",",
"postal_code",
",",
"location_deets",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"\"rates/\"",
"+",
"postal_code",
",",
"location_deets",
")",
"return",
"self",
".",
"responder",
"(",
"requ... | Shows the sales tax rates for a given location. | [
"Shows",
"the",
"sales",
"tax",
"rates",
"for",
"a",
"given",
"location",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L31-L34 |
20,527 | taxjar/taxjar-python | taxjar/client.py | Client.tax_for_order | def tax_for_order(self, order_deets):
"""Shows the sales tax that should be collected for a given order."""
request = self._post('taxes', order_deets)
return self.responder(request) | python | def tax_for_order(self, order_deets):
request = self._post('taxes', order_deets)
return self.responder(request) | [
"def",
"tax_for_order",
"(",
"self",
",",
"order_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'taxes'",
",",
"order_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Shows the sales tax that should be collected for a given order. | [
"Shows",
"the",
"sales",
"tax",
"that",
"should",
"be",
"collected",
"for",
"a",
"given",
"order",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L36-L39 |
20,528 | taxjar/taxjar-python | taxjar/client.py | Client.list_orders | def list_orders(self, params=None):
"""Lists existing order transactions."""
request = self._get('transactions/orders', params)
return self.responder(request) | python | def list_orders(self, params=None):
request = self._get('transactions/orders', params)
return self.responder(request) | [
"def",
"list_orders",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/orders'",
",",
"params",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Lists existing order transactions. | [
"Lists",
"existing",
"order",
"transactions",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L41-L44 |
20,529 | taxjar/taxjar-python | taxjar/client.py | Client.show_order | def show_order(self, order_id):
"""Shows an existing order transaction."""
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request) | python | def show_order(self, order_id):
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request) | [
"def",
"show_order",
"(",
"self",
",",
"order_id",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/orders/'",
"+",
"str",
"(",
"order_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Shows an existing order transaction. | [
"Shows",
"an",
"existing",
"order",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L46-L49 |
20,530 | taxjar/taxjar-python | taxjar/client.py | Client.create_order | def create_order(self, order_deets):
"""Creates a new order transaction."""
request = self._post('transactions/orders', order_deets)
return self.responder(request) | python | def create_order(self, order_deets):
request = self._post('transactions/orders', order_deets)
return self.responder(request) | [
"def",
"create_order",
"(",
"self",
",",
"order_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'transactions/orders'",
",",
"order_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Creates a new order transaction. | [
"Creates",
"a",
"new",
"order",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L51-L54 |
20,531 | taxjar/taxjar-python | taxjar/client.py | Client.update_order | def update_order(self, order_id, order_deets):
"""Updates an existing order transaction."""
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request) | python | def update_order(self, order_id, order_deets):
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request) | [
"def",
"update_order",
"(",
"self",
",",
"order_id",
",",
"order_deets",
")",
":",
"request",
"=",
"self",
".",
"_put",
"(",
"\"transactions/orders/\"",
"+",
"str",
"(",
"order_id",
")",
",",
"order_deets",
")",
"return",
"self",
".",
"responder",
"(",
"re... | Updates an existing order transaction. | [
"Updates",
"an",
"existing",
"order",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L56-L59 |
20,532 | taxjar/taxjar-python | taxjar/client.py | Client.delete_order | def delete_order(self, order_id):
"""Deletes an existing order transaction."""
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request) | python | def delete_order(self, order_id):
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request) | [
"def",
"delete_order",
"(",
"self",
",",
"order_id",
")",
":",
"request",
"=",
"self",
".",
"_delete",
"(",
"\"transactions/orders/\"",
"+",
"str",
"(",
"order_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Deletes an existing order transaction. | [
"Deletes",
"an",
"existing",
"order",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L61-L64 |
20,533 | taxjar/taxjar-python | taxjar/client.py | Client.list_refunds | def list_refunds(self, params=None):
"""Lists existing refund transactions."""
request = self._get('transactions/refunds', params)
return self.responder(request) | python | def list_refunds(self, params=None):
request = self._get('transactions/refunds', params)
return self.responder(request) | [
"def",
"list_refunds",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/refunds'",
",",
"params",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Lists existing refund transactions. | [
"Lists",
"existing",
"refund",
"transactions",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L66-L69 |
20,534 | taxjar/taxjar-python | taxjar/client.py | Client.show_refund | def show_refund(self, refund_id):
"""Shows an existing refund transaction."""
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request) | python | def show_refund(self, refund_id):
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request) | [
"def",
"show_refund",
"(",
"self",
",",
"refund_id",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'transactions/refunds/'",
"+",
"str",
"(",
"refund_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Shows an existing refund transaction. | [
"Shows",
"an",
"existing",
"refund",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L71-L74 |
20,535 | taxjar/taxjar-python | taxjar/client.py | Client.create_refund | def create_refund(self, refund_deets):
"""Creates a new refund transaction."""
request = self._post('transactions/refunds', refund_deets)
return self.responder(request) | python | def create_refund(self, refund_deets):
request = self._post('transactions/refunds', refund_deets)
return self.responder(request) | [
"def",
"create_refund",
"(",
"self",
",",
"refund_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'transactions/refunds'",
",",
"refund_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Creates a new refund transaction. | [
"Creates",
"a",
"new",
"refund",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L76-L79 |
20,536 | taxjar/taxjar-python | taxjar/client.py | Client.update_refund | def update_refund(self, refund_id, refund_deets):
"""Updates an existing refund transaction."""
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request) | python | def update_refund(self, refund_id, refund_deets):
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request) | [
"def",
"update_refund",
"(",
"self",
",",
"refund_id",
",",
"refund_deets",
")",
":",
"request",
"=",
"self",
".",
"_put",
"(",
"'transactions/refunds/'",
"+",
"str",
"(",
"refund_id",
")",
",",
"refund_deets",
")",
"return",
"self",
".",
"responder",
"(",
... | Updates an existing refund transaction. | [
"Updates",
"an",
"existing",
"refund",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L81-L84 |
20,537 | taxjar/taxjar-python | taxjar/client.py | Client.delete_refund | def delete_refund(self, refund_id):
"""Deletes an existing refund transaction."""
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request) | python | def delete_refund(self, refund_id):
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request) | [
"def",
"delete_refund",
"(",
"self",
",",
"refund_id",
")",
":",
"request",
"=",
"self",
".",
"_delete",
"(",
"'transactions/refunds/'",
"+",
"str",
"(",
"refund_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Deletes an existing refund transaction. | [
"Deletes",
"an",
"existing",
"refund",
"transaction",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L86-L89 |
20,538 | taxjar/taxjar-python | taxjar/client.py | Client.list_customers | def list_customers(self, params=None):
"""Lists existing customers."""
request = self._get('customers', params)
return self.responder(request) | python | def list_customers(self, params=None):
request = self._get('customers', params)
return self.responder(request) | [
"def",
"list_customers",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'customers'",
",",
"params",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Lists existing customers. | [
"Lists",
"existing",
"customers",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L91-L94 |
20,539 | taxjar/taxjar-python | taxjar/client.py | Client.show_customer | def show_customer(self, customer_id):
"""Shows an existing customer."""
request = self._get('customers/' + str(customer_id))
return self.responder(request) | python | def show_customer(self, customer_id):
request = self._get('customers/' + str(customer_id))
return self.responder(request) | [
"def",
"show_customer",
"(",
"self",
",",
"customer_id",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'customers/'",
"+",
"str",
"(",
"customer_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Shows an existing customer. | [
"Shows",
"an",
"existing",
"customer",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L96-L99 |
20,540 | taxjar/taxjar-python | taxjar/client.py | Client.create_customer | def create_customer(self, customer_deets):
"""Creates a new customer."""
request = self._post('customers', customer_deets)
return self.responder(request) | python | def create_customer(self, customer_deets):
request = self._post('customers', customer_deets)
return self.responder(request) | [
"def",
"create_customer",
"(",
"self",
",",
"customer_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'customers'",
",",
"customer_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Creates a new customer. | [
"Creates",
"a",
"new",
"customer",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L101-L104 |
20,541 | taxjar/taxjar-python | taxjar/client.py | Client.update_customer | def update_customer(self, customer_id, customer_deets):
"""Updates an existing customer."""
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request) | python | def update_customer(self, customer_id, customer_deets):
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request) | [
"def",
"update_customer",
"(",
"self",
",",
"customer_id",
",",
"customer_deets",
")",
":",
"request",
"=",
"self",
".",
"_put",
"(",
"\"customers/\"",
"+",
"str",
"(",
"customer_id",
")",
",",
"customer_deets",
")",
"return",
"self",
".",
"responder",
"(",
... | Updates an existing customer. | [
"Updates",
"an",
"existing",
"customer",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L106-L109 |
20,542 | taxjar/taxjar-python | taxjar/client.py | Client.delete_customer | def delete_customer(self, customer_id):
"""Deletes an existing customer."""
request = self._delete("customers/" + str(customer_id))
return self.responder(request) | python | def delete_customer(self, customer_id):
request = self._delete("customers/" + str(customer_id))
return self.responder(request) | [
"def",
"delete_customer",
"(",
"self",
",",
"customer_id",
")",
":",
"request",
"=",
"self",
".",
"_delete",
"(",
"\"customers/\"",
"+",
"str",
"(",
"customer_id",
")",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Deletes an existing customer. | [
"Deletes",
"an",
"existing",
"customer",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L111-L114 |
20,543 | taxjar/taxjar-python | taxjar/client.py | Client.validate_address | def validate_address(self, address_deets):
"""Validates a customer address and returns back a collection of address matches."""
request = self._post('addresses/validate', address_deets)
return self.responder(request) | python | def validate_address(self, address_deets):
request = self._post('addresses/validate', address_deets)
return self.responder(request) | [
"def",
"validate_address",
"(",
"self",
",",
"address_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'addresses/validate'",
",",
"address_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Validates a customer address and returns back a collection of address matches. | [
"Validates",
"a",
"customer",
"address",
"and",
"returns",
"back",
"a",
"collection",
"of",
"address",
"matches",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L121-L124 |
20,544 | taxjar/taxjar-python | taxjar/client.py | Client.validate | def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request) | python | def validate(self, vat_deets):
request = self._get('validation', vat_deets)
return self.responder(request) | [
"def",
"validate",
"(",
"self",
",",
"vat_deets",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'validation'",
",",
"vat_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Validates an existing VAT identification number against VIES. | [
"Validates",
"an",
"existing",
"VAT",
"identification",
"number",
"against",
"VIES",
"."
] | be9b30d7dc968d24e066c7c133849fee180f8d95 | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L126-L129 |
20,545 | last-partizan/pytils | pytils/templatetags/pytils_numeral.py | choose_plural | def choose_plural(amount, variants):
"""
Choose proper form for plural.
Value is a amount, parameters are forms of noun.
Forms are variants for 1, 2, 5 nouns. It may be tuple
of elements, or string where variants separates each other
by comma.
Examples::
{{ some_int|choose_plural:"пример,примера,примеров" }}
"""
try:
if isinstance(variants, six.string_types):
uvariants = smart_text(variants, encoding)
else:
uvariants = [smart_text(v, encoding) for v in variants]
res = numeral.choose_plural(amount, uvariants)
except Exception as err:
# because filter must die silently
try:
default_variant = variants
except Exception:
default_variant = ""
res = default_value % {'error': err, 'value': default_variant}
return res | python | def choose_plural(amount, variants):
try:
if isinstance(variants, six.string_types):
uvariants = smart_text(variants, encoding)
else:
uvariants = [smart_text(v, encoding) for v in variants]
res = numeral.choose_plural(amount, uvariants)
except Exception as err:
# because filter must die silently
try:
default_variant = variants
except Exception:
default_variant = ""
res = default_value % {'error': err, 'value': default_variant}
return res | [
"def",
"choose_plural",
"(",
"amount",
",",
"variants",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"variants",
",",
"six",
".",
"string_types",
")",
":",
"uvariants",
"=",
"smart_text",
"(",
"variants",
",",
"encoding",
")",
"else",
":",
"uvariants",
... | Choose proper form for plural.
Value is a amount, parameters are forms of noun.
Forms are variants for 1, 2, 5 nouns. It may be tuple
of elements, or string where variants separates each other
by comma.
Examples::
{{ some_int|choose_plural:"пример,примера,примеров" }} | [
"Choose",
"proper",
"form",
"for",
"plural",
"."
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L29-L54 |
20,546 | last-partizan/pytils | pytils/templatetags/pytils_numeral.py | in_words | def in_words(amount, gender=None):
"""
In-words representation of amount.
Parameter is a gender: MALE, FEMALE or NEUTER
Examples::
{{ some_int|in_words }}
{{ some_other_int|in_words:FEMALE }}
"""
try:
res = numeral.in_words(amount, getattr(numeral, str(gender), None))
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res | python | def in_words(amount, gender=None):
try:
res = numeral.in_words(amount, getattr(numeral, str(gender), None))
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res | [
"def",
"in_words",
"(",
"amount",
",",
"gender",
"=",
"None",
")",
":",
"try",
":",
"res",
"=",
"numeral",
".",
"in_words",
"(",
"amount",
",",
"getattr",
"(",
"numeral",
",",
"str",
"(",
"gender",
")",
",",
"None",
")",
")",
"except",
"Exception",
... | In-words representation of amount.
Parameter is a gender: MALE, FEMALE or NEUTER
Examples::
{{ some_int|in_words }}
{{ some_other_int|in_words:FEMALE }} | [
"In",
"-",
"words",
"representation",
"of",
"amount",
"."
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L92-L107 |
20,547 | last-partizan/pytils | pytils/templatetags/pytils_numeral.py | sum_string | def sum_string(amount, gender, items):
"""
in_words and choose_plural in a one flask
Makes in-words representation of value with
choosing correct form of noun.
First parameter is an amount of objects. Second is a
gender (MALE, FEMALE, NEUTER). Third is a variants
of forms for object name.
Examples::
{% sum_string some_int MALE "пример,примера,примеров" %}
{% sum_string some_other_int FEMALE "задача,задачи,задач" %}
"""
try:
if isinstance(items, six.string_types):
uitems = smart_text(items, encoding, default_uvalue)
else:
uitems = [smart_text(i, encoding) for i in items]
res = numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems)
except Exception as err:
# because tag's renderer must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res | python | def sum_string(amount, gender, items):
try:
if isinstance(items, six.string_types):
uitems = smart_text(items, encoding, default_uvalue)
else:
uitems = [smart_text(i, encoding) for i in items]
res = numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems)
except Exception as err:
# because tag's renderer must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res | [
"def",
"sum_string",
"(",
"amount",
",",
"gender",
",",
"items",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"items",
",",
"six",
".",
"string_types",
")",
":",
"uitems",
"=",
"smart_text",
"(",
"items",
",",
"encoding",
",",
"default_uvalue",
")",
... | in_words and choose_plural in a one flask
Makes in-words representation of value with
choosing correct form of noun.
First parameter is an amount of objects. Second is a
gender (MALE, FEMALE, NEUTER). Third is a variants
of forms for object name.
Examples::
{% sum_string some_int MALE "пример,примера,примеров" %}
{% sum_string some_other_int FEMALE "задача,задачи,задач" %} | [
"in_words",
"and",
"choose_plural",
"in",
"a",
"one",
"flask",
"Makes",
"in",
"-",
"words",
"representation",
"of",
"value",
"with",
"choosing",
"correct",
"form",
"of",
"noun",
"."
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_numeral.py#L118-L141 |
20,548 | last-partizan/pytils | pytils/typo.py | rl_cleanspaces | def rl_cleanspaces(x):
"""
Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations
"""
patterns = (
# arguments for re.sub: pattern and repl
# удаляем пробел перед знаками препинания
(r' +([\.,?!\)]+)', r'\1'),
# добавляем пробел после знака препинания, если только за ним нет другого
(r'([\.,?!\)]+)([^\.!,?\)]+)', r'\1 \2'),
# убираем пробел после открывающей скобки
(r'(\S+)\s*(\()\s*(\S+)', r'\1 (\3'),
)
# удаляем двойные, начальные и конечные пробелы
return os.linesep.join(
' '.join(part for part in line.split(' ') if part)
for line in _sub_patterns(patterns, x).split(os.linesep)
) | python | def rl_cleanspaces(x):
patterns = (
# arguments for re.sub: pattern and repl
# удаляем пробел перед знаками препинания
(r' +([\.,?!\)]+)', r'\1'),
# добавляем пробел после знака препинания, если только за ним нет другого
(r'([\.,?!\)]+)([^\.!,?\)]+)', r'\1 \2'),
# убираем пробел после открывающей скобки
(r'(\S+)\s*(\()\s*(\S+)', r'\1 (\3'),
)
# удаляем двойные, начальные и конечные пробелы
return os.linesep.join(
' '.join(part for part in line.split(' ') if part)
for line in _sub_patterns(patterns, x).split(os.linesep)
) | [
"def",
"rl_cleanspaces",
"(",
"x",
")",
":",
"patterns",
"=",
"(",
"# arguments for re.sub: pattern and repl",
"# удаляем пробел перед знаками препинания",
"(",
"r' +([\\.,?!\\)]+)'",
",",
"r'\\1'",
")",
",",
"# добавляем пробел после знака препинания, если только за ним нет другог... | Clean double spaces, trailing spaces, heading spaces,
spaces before punctuations | [
"Clean",
"double",
"spaces",
"trailing",
"spaces",
"heading",
"spaces",
"spaces",
"before",
"punctuations"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L26-L44 |
20,549 | last-partizan/pytils | pytils/typo.py | rl_quotes | def rl_quotes(x):
"""
Replace quotes by typographic quotes
"""
patterns = (
# открывающие кавычки ставятся обычно вплотную к слову слева
# а закрывающие -- вплотную справа
# открывающие русские кавычки-ёлочки
(re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab\\3'),
# закрывающие русские кавычки-ёлочки
(re.compile(r'(\S)(")((?u))', re.UNICODE), u'\\1\xbb\\3'),
# открывающие кавычки-лапки, вместо одинарных кавычек
(re.compile(r'((?:^|\s))(\')((?u))', re.UNICODE), u'\\1\u201c\\3'),
# закрывающие кавычки-лапки
(re.compile(r'(\S)(\')((?u))', re.UNICODE), u'\\1\u201d\\3'),
)
return _sub_patterns(patterns, x) | python | def rl_quotes(x):
patterns = (
# открывающие кавычки ставятся обычно вплотную к слову слева
# а закрывающие -- вплотную справа
# открывающие русские кавычки-ёлочки
(re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab\\3'),
# закрывающие русские кавычки-ёлочки
(re.compile(r'(\S)(")((?u))', re.UNICODE), u'\\1\xbb\\3'),
# открывающие кавычки-лапки, вместо одинарных кавычек
(re.compile(r'((?:^|\s))(\')((?u))', re.UNICODE), u'\\1\u201c\\3'),
# закрывающие кавычки-лапки
(re.compile(r'(\S)(\')((?u))', re.UNICODE), u'\\1\u201d\\3'),
)
return _sub_patterns(patterns, x) | [
"def",
"rl_quotes",
"(",
"x",
")",
":",
"patterns",
"=",
"(",
"# открывающие кавычки ставятся обычно вплотную к слову слева",
"# а закрывающие -- вплотную справа",
"# открывающие русские кавычки-ёлочки",
"(",
"re",
".",
"compile",
"(",
"r'((?:^|\\s))(\")((?u))'",
",",
"re",
"... | Replace quotes by typographic quotes | [
"Replace",
"quotes",
"by",
"typographic",
"quotes"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/typo.py#L134-L151 |
20,550 | last-partizan/pytils | pytils/templatetags/pytils_dt.py | distance_of_time | def distance_of_time(from_time, accuracy=1):
"""
Display distance of time from current time.
Parameter is an accuracy level (deafult is 1).
Value must be numeral (i.e. time.time() result) or
datetime.datetime (i.e. datetime.datetime.now()
result).
Examples::
{{ some_time|distance_of_time }}
{{ some_dtime|distance_of_time:2 }}
"""
try:
to_time = None
if conf.settings.USE_TZ:
to_time=utils.timezone.now()
res = dt.distance_of_time_in_words(from_time, accuracy, to_time)
except Exception as err:
# because filter must die silently
try:
default_distance = "%s seconds" % str(int(time.time() - from_time))
except Exception:
default_distance = ""
res = default_value % {'error': err, 'value': default_distance}
return res | python | def distance_of_time(from_time, accuracy=1):
try:
to_time = None
if conf.settings.USE_TZ:
to_time=utils.timezone.now()
res = dt.distance_of_time_in_words(from_time, accuracy, to_time)
except Exception as err:
# because filter must die silently
try:
default_distance = "%s seconds" % str(int(time.time() - from_time))
except Exception:
default_distance = ""
res = default_value % {'error': err, 'value': default_distance}
return res | [
"def",
"distance_of_time",
"(",
"from_time",
",",
"accuracy",
"=",
"1",
")",
":",
"try",
":",
"to_time",
"=",
"None",
"if",
"conf",
".",
"settings",
".",
"USE_TZ",
":",
"to_time",
"=",
"utils",
".",
"timezone",
".",
"now",
"(",
")",
"res",
"=",
"dt",... | Display distance of time from current time.
Parameter is an accuracy level (deafult is 1).
Value must be numeral (i.e. time.time() result) or
datetime.datetime (i.e. datetime.datetime.now()
result).
Examples::
{{ some_time|distance_of_time }}
{{ some_dtime|distance_of_time:2 }} | [
"Display",
"distance",
"of",
"time",
"from",
"current",
"time",
"."
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_dt.py#L20-L45 |
20,551 | last-partizan/pytils | pytils/templatetags/pytils_dt.py | ru_strftime | def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False):
"""
Russian strftime, formats date with given format.
Value is a date (supports datetime.date and datetime.datetime),
parameter is a format (string). For explainings about format,
see documentation for original strftime:
http://docs.python.org/lib/module-time.html
Examples::
{{ some_date|ru_strftime:"%d %B %Y, %A" }}
"""
try:
res = dt.ru_strftime(format,
date,
inflected=True,
inflected_day=inflected_day,
preposition=preposition)
except Exception as err:
# because filter must die silently
try:
default_date = date.strftime(format)
except Exception:
default_date = str(date)
res = default_value % {'error': err, 'value': default_date}
return res | python | def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False):
try:
res = dt.ru_strftime(format,
date,
inflected=True,
inflected_day=inflected_day,
preposition=preposition)
except Exception as err:
# because filter must die silently
try:
default_date = date.strftime(format)
except Exception:
default_date = str(date)
res = default_value % {'error': err, 'value': default_date}
return res | [
"def",
"ru_strftime",
"(",
"date",
",",
"format",
"=",
"\"%d.%m.%Y\"",
",",
"inflected_day",
"=",
"False",
",",
"preposition",
"=",
"False",
")",
":",
"try",
":",
"res",
"=",
"dt",
".",
"ru_strftime",
"(",
"format",
",",
"date",
",",
"inflected",
"=",
... | Russian strftime, formats date with given format.
Value is a date (supports datetime.date and datetime.datetime),
parameter is a format (string). For explainings about format,
see documentation for original strftime:
http://docs.python.org/lib/module-time.html
Examples::
{{ some_date|ru_strftime:"%d %B %Y, %A" }} | [
"Russian",
"strftime",
"formats",
"date",
"with",
"given",
"format",
"."
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_dt.py#L47-L72 |
20,552 | last-partizan/pytils | pytils/dt.py | ru_strftime | def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False,
inflected_day=False, preposition=False):
"""
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{datetime.date} or C{datetime.datetime}
@param inflected: is month inflected, default False
@type inflected: C{bool}
@param inflected_day: is day inflected, default False
@type inflected: C{bool}
@param preposition: is preposition used, default False
preposition=True automatically implies inflected_day=True
@type preposition: C{bool}
@return: strftime string
@rtype: unicode
"""
if date is None:
date = datetime.datetime.today()
weekday = date.weekday()
prepos = preposition and DAY_NAMES[weekday][3] or u""
month_idx = inflected and 2 or 1
day_idx = (inflected_day or preposition) and 2 or 1
# for russian typography standard,
# 1 April 2007, but 01.04.2007
if u'%b' in format or u'%B' in format:
format = format.replace(u'%d', six.text_type(date.day))
format = format.replace(u'%a', prepos+DAY_NAMES[weekday][0])
format = format.replace(u'%A', prepos+DAY_NAMES[weekday][day_idx])
format = format.replace(u'%b', MONTH_NAMES[date.month-1][0])
format = format.replace(u'%B', MONTH_NAMES[date.month-1][month_idx])
# Python 2: strftime's argument must be str
# Python 3: strftime's argument str, not a bitestring
if six.PY2:
# strftime must be str, so encode it to utf8:
s_format = format.encode("utf-8")
s_res = date.strftime(s_format)
# and back to unicode
u_res = s_res.decode("utf-8")
else:
u_res = date.strftime(format)
return u_res | python | def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False,
inflected_day=False, preposition=False):
if date is None:
date = datetime.datetime.today()
weekday = date.weekday()
prepos = preposition and DAY_NAMES[weekday][3] or u""
month_idx = inflected and 2 or 1
day_idx = (inflected_day or preposition) and 2 or 1
# for russian typography standard,
# 1 April 2007, but 01.04.2007
if u'%b' in format or u'%B' in format:
format = format.replace(u'%d', six.text_type(date.day))
format = format.replace(u'%a', prepos+DAY_NAMES[weekday][0])
format = format.replace(u'%A', prepos+DAY_NAMES[weekday][day_idx])
format = format.replace(u'%b', MONTH_NAMES[date.month-1][0])
format = format.replace(u'%B', MONTH_NAMES[date.month-1][month_idx])
# Python 2: strftime's argument must be str
# Python 3: strftime's argument str, not a bitestring
if six.PY2:
# strftime must be str, so encode it to utf8:
s_format = format.encode("utf-8")
s_res = date.strftime(s_format)
# and back to unicode
u_res = s_res.decode("utf-8")
else:
u_res = date.strftime(format)
return u_res | [
"def",
"ru_strftime",
"(",
"format",
"=",
"u\"%d.%m.%Y\"",
",",
"date",
"=",
"None",
",",
"inflected",
"=",
"False",
",",
"inflected_day",
"=",
"False",
",",
"preposition",
"=",
"False",
")",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",... | Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{datetime.date} or C{datetime.datetime}
@param inflected: is month inflected, default False
@type inflected: C{bool}
@param inflected_day: is day inflected, default False
@type inflected: C{bool}
@param preposition: is preposition used, default False
preposition=True automatically implies inflected_day=True
@type preposition: C{bool}
@return: strftime string
@rtype: unicode | [
"Russian",
"strftime",
"without",
"locale"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/dt.py#L179-L233 |
20,553 | last-partizan/pytils | pytils/numeral.py | _get_float_remainder | def _get_float_remainder(fvalue, signs=9):
"""
Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ValueError: fvalue is negative
@raise ValueError: signs overflow
"""
check_positive(fvalue)
if isinstance(fvalue, six.integer_types):
return "0"
if isinstance(fvalue, Decimal) and fvalue.as_tuple()[2] == 0:
# Decimal.as_tuple() -> (sign, digit_tuple, exponent)
# если экспонента "0" -- значит дробной части нет
return "0"
signs = min(signs, len(FRACTIONS))
# нужно remainder в строке, потому что дробные X.0Y
# будут "ломаться" до X.Y
remainder = str(fvalue).split('.')[1]
iremainder = int(remainder)
orig_remainder = remainder
factor = len(str(remainder)) - signs
if factor > 0:
# после запятой цифр больше чем signs, округляем
iremainder = int(round(iremainder / (10.0**factor)))
format = "%%0%dd" % min(len(remainder), signs)
remainder = format % iremainder
if len(remainder) > signs:
# при округлении цифр вида 0.998 ругаться
raise ValueError("Signs overflow: I can't round only fractional part \
of %s to fit %s in %d signs" % \
(str(fvalue), orig_remainder, signs))
return remainder | python | def _get_float_remainder(fvalue, signs=9):
check_positive(fvalue)
if isinstance(fvalue, six.integer_types):
return "0"
if isinstance(fvalue, Decimal) and fvalue.as_tuple()[2] == 0:
# Decimal.as_tuple() -> (sign, digit_tuple, exponent)
# если экспонента "0" -- значит дробной части нет
return "0"
signs = min(signs, len(FRACTIONS))
# нужно remainder в строке, потому что дробные X.0Y
# будут "ломаться" до X.Y
remainder = str(fvalue).split('.')[1]
iremainder = int(remainder)
orig_remainder = remainder
factor = len(str(remainder)) - signs
if factor > 0:
# после запятой цифр больше чем signs, округляем
iremainder = int(round(iremainder / (10.0**factor)))
format = "%%0%dd" % min(len(remainder), signs)
remainder = format % iremainder
if len(remainder) > signs:
# при округлении цифр вида 0.998 ругаться
raise ValueError("Signs overflow: I can't round only fractional part \
of %s to fit %s in %d signs" % \
(str(fvalue), orig_remainder, signs))
return remainder | [
"def",
"_get_float_remainder",
"(",
"fvalue",
",",
"signs",
"=",
"9",
")",
":",
"check_positive",
"(",
"fvalue",
")",
"if",
"isinstance",
"(",
"fvalue",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"\"0\"",
"if",
"isinstance",
"(",
"fvalue",
",",
... | Get remainder of float, i.e. 2.05 -> '05'
@param fvalue: input value
@type fvalue: C{integer types}, C{float} or C{Decimal}
@param signs: maximum number of signs
@type signs: C{integer types}
@return: remainder
@rtype: C{str}
@raise ValueError: fvalue is negative
@raise ValueError: signs overflow | [
"Get",
"remainder",
"of",
"float",
"i",
".",
"e",
".",
"2",
".",
"05",
"-",
">",
"05"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L77-L123 |
20,554 | last-partizan/pytils | pytils/numeral.py | choose_plural | def choose_plural(amount, variants):
"""
Choose proper case depending on amount
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@return: proper variant
@rtype: C{unicode}
@raise ValueError: variants' length lesser than 3
"""
if isinstance(variants, six.text_type):
variants = split_values(variants)
check_length(variants, 3)
amount = abs(amount)
if amount % 10 == 1 and amount % 100 != 11:
variant = 0
elif amount % 10 >= 2 and amount % 10 <= 4 and \
(amount % 100 < 10 or amount % 100 >= 20):
variant = 1
else:
variant = 2
return variants[variant] | python | def choose_plural(amount, variants):
if isinstance(variants, six.text_type):
variants = split_values(variants)
check_length(variants, 3)
amount = abs(amount)
if amount % 10 == 1 and amount % 100 != 11:
variant = 0
elif amount % 10 >= 2 and amount % 10 <= 4 and \
(amount % 100 < 10 or amount % 100 >= 20):
variant = 1
else:
variant = 2
return variants[variant] | [
"def",
"choose_plural",
"(",
"amount",
",",
"variants",
")",
":",
"if",
"isinstance",
"(",
"variants",
",",
"six",
".",
"text_type",
")",
":",
"variants",
"=",
"split_values",
"(",
"variants",
")",
"check_length",
"(",
"variants",
",",
"3",
")",
"amount",
... | Choose proper case depending on amount
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@return: proper variant
@rtype: C{unicode}
@raise ValueError: variants' length lesser than 3 | [
"Choose",
"proper",
"case",
"depending",
"on",
"amount"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L126-L157 |
20,555 | last-partizan/pytils | pytils/numeral.py | get_plural | def get_plural(amount, variants, absence=None):
"""
Get proper case with value
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@param absence: if amount is zero will return it
@type absence: C{unicode}
@return: amount with proper variant
@rtype: C{unicode}
"""
if amount or absence is None:
return u"%d %s" % (amount, choose_plural(amount, variants))
else:
return absence | python | def get_plural(amount, variants, absence=None):
if amount or absence is None:
return u"%d %s" % (amount, choose_plural(amount, variants))
else:
return absence | [
"def",
"get_plural",
"(",
"amount",
",",
"variants",
",",
"absence",
"=",
"None",
")",
":",
"if",
"amount",
"or",
"absence",
"is",
"None",
":",
"return",
"u\"%d %s\"",
"%",
"(",
"amount",
",",
"choose_plural",
"(",
"amount",
",",
"variants",
")",
")",
... | Get proper case with value
@param amount: amount of objects
@type amount: C{integer types}
@param variants: variants (forms) of object in such form:
(1 object, 2 objects, 5 objects).
@type variants: 3-element C{sequence} of C{unicode}
or C{unicode} (three variants with delimeter ',')
@param absence: if amount is zero will return it
@type absence: C{unicode}
@return: amount with proper variant
@rtype: C{unicode} | [
"Get",
"proper",
"case",
"with",
"value"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L160-L181 |
20,556 | last-partizan/pytils | pytils/numeral.py | in_words | def in_words(amount, gender=None):
"""
Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError: when amount is negative
"""
check_positive(amount)
if isinstance(amount, Decimal) and amount.as_tuple()[2] == 0:
# если целое,
# т.е. Decimal.as_tuple -> (sign, digits tuple, exponent), exponent=0
# то как целое
amount = int(amount)
if gender is None:
args = (amount,)
else:
args = (amount, gender)
# если целое
if isinstance(amount, six.integer_types):
return in_words_int(*args)
# если дробное
elif isinstance(amount, (float, Decimal)):
return in_words_float(*args)
# ни float, ни int, ни Decimal
else:
# до сюда не должно дойти
raise TypeError(
"amount should be number type (int, long, float, Decimal), got %s"
% type(amount)) | python | def in_words(amount, gender=None):
check_positive(amount)
if isinstance(amount, Decimal) and amount.as_tuple()[2] == 0:
# если целое,
# т.е. Decimal.as_tuple -> (sign, digits tuple, exponent), exponent=0
# то как целое
amount = int(amount)
if gender is None:
args = (amount,)
else:
args = (amount, gender)
# если целое
if isinstance(amount, six.integer_types):
return in_words_int(*args)
# если дробное
elif isinstance(amount, (float, Decimal)):
return in_words_float(*args)
# ни float, ни int, ни Decimal
else:
# до сюда не должно дойти
raise TypeError(
"amount should be number type (int, long, float, Decimal), got %s"
% type(amount)) | [
"def",
"in_words",
"(",
"amount",
",",
"gender",
"=",
"None",
")",
":",
"check_positive",
"(",
"amount",
")",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
"and",
"amount",
".",
"as_tuple",
"(",
")",
"[",
"2",
"]",
"==",
"0",
":",
"# если ц... | Numeral in words
@param amount: numeral
@type amount: C{integer types}, C{float} or C{Decimal}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@return: in-words reprsentation of numeral
@rtype: C{unicode}
raise ValueError: when amount is negative | [
"Numeral",
"in",
"words"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L289-L325 |
20,557 | last-partizan/pytils | pytils/numeral.py | _sum_string_fn | def _sum_string_fn(into, tmp_val, gender, items=None):
"""
Make in-words representation of single order
@param into: in-words representation of lower orders
@type into: C{unicode}
@param tmp_val: temporary value without lower orders
@type tmp_val: C{integer types}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@param items: variants of objects
@type items: 3-element C{sequence} of C{unicode}
@return: new into and tmp_val
@rtype: C{tuple}
@raise ValueError: tmp_val is negative
"""
if items is None:
items = (u"", u"", u"")
one_item, two_items, five_items = items
check_positive(tmp_val)
if tmp_val == 0:
return into, tmp_val
words = []
rest = tmp_val % 1000
tmp_val = tmp_val // 1000
if rest == 0:
# последние три знака нулевые
if into == u"":
into = u"%s " % five_items
return into, tmp_val
# начинаем подсчет с rest
end_word = five_items
# сотни
words.append(HUNDREDS[rest // 100])
# десятки
rest = rest % 100
rest1 = rest // 10
# особый случай -- tens=1
tens = rest1 == 1 and TENS[rest] or TENS[rest1]
words.append(tens)
# единицы
if rest1 < 1 or rest1 > 1:
amount = rest % 10
end_word = choose_plural(amount, items)
words.append(ONES[amount][gender-1])
words.append(end_word)
# добавляем то, что уже было
words.append(into)
# убираем пустые подстроки
words = filter(lambda x: len(x) > 0, words)
# склеиваем и отдаем
return u" ".join(words).strip(), tmp_val | python | def _sum_string_fn(into, tmp_val, gender, items=None):
if items is None:
items = (u"", u"", u"")
one_item, two_items, five_items = items
check_positive(tmp_val)
if tmp_val == 0:
return into, tmp_val
words = []
rest = tmp_val % 1000
tmp_val = tmp_val // 1000
if rest == 0:
# последние три знака нулевые
if into == u"":
into = u"%s " % five_items
return into, tmp_val
# начинаем подсчет с rest
end_word = five_items
# сотни
words.append(HUNDREDS[rest // 100])
# десятки
rest = rest % 100
rest1 = rest // 10
# особый случай -- tens=1
tens = rest1 == 1 and TENS[rest] or TENS[rest1]
words.append(tens)
# единицы
if rest1 < 1 or rest1 > 1:
amount = rest % 10
end_word = choose_plural(amount, items)
words.append(ONES[amount][gender-1])
words.append(end_word)
# добавляем то, что уже было
words.append(into)
# убираем пустые подстроки
words = filter(lambda x: len(x) > 0, words)
# склеиваем и отдаем
return u" ".join(words).strip(), tmp_val | [
"def",
"_sum_string_fn",
"(",
"into",
",",
"tmp_val",
",",
"gender",
",",
"items",
"=",
"None",
")",
":",
"if",
"items",
"is",
"None",
":",
"items",
"=",
"(",
"u\"\"",
",",
"u\"\"",
",",
"u\"\"",
")",
"one_item",
",",
"two_items",
",",
"five_items",
... | Make in-words representation of single order
@param into: in-words representation of lower orders
@type into: C{unicode}
@param tmp_val: temporary value without lower orders
@type tmp_val: C{integer types}
@param gender: gender (MALE, FEMALE or NEUTER)
@type gender: C{int}
@param items: variants of objects
@type items: 3-element C{sequence} of C{unicode}
@return: new into and tmp_val
@rtype: C{tuple}
@raise ValueError: tmp_val is negative | [
"Make",
"in",
"-",
"words",
"representation",
"of",
"single",
"order"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/numeral.py#L388-L455 |
20,558 | last-partizan/pytils | pytils/utils.py | check_length | def check_length(value, length):
"""
Checks length of value
@param value: value to check
@type value: C{str}
@param length: length checking for
@type length: C{int}
@return: None when check successful
@raise ValueError: check failed
"""
_length = len(value)
if _length != length:
raise ValueError("length must be %d, not %d" % \
(length, _length)) | python | def check_length(value, length):
_length = len(value)
if _length != length:
raise ValueError("length must be %d, not %d" % \
(length, _length)) | [
"def",
"check_length",
"(",
"value",
",",
"length",
")",
":",
"_length",
"=",
"len",
"(",
"value",
")",
"if",
"_length",
"!=",
"length",
":",
"raise",
"ValueError",
"(",
"\"length must be %d, not %d\"",
"%",
"(",
"length",
",",
"_length",
")",
")"
] | Checks length of value
@param value: value to check
@type value: C{str}
@param length: length checking for
@type length: C{int}
@return: None when check successful
@raise ValueError: check failed | [
"Checks",
"length",
"of",
"value"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L10-L27 |
20,559 | last-partizan/pytils | pytils/utils.py | check_positive | def check_positive(value, strict=False):
"""
Checks if variable is positive
@param value: value to check
@type value: C{integer types}, C{float} or C{Decimal}
@return: None when check successful
@raise ValueError: check failed
"""
if not strict and value < 0:
raise ValueError("Value must be positive or zero, not %s" % str(value))
if strict and value <= 0:
raise ValueError("Value must be positive, not %s" % str(value)) | python | def check_positive(value, strict=False):
if not strict and value < 0:
raise ValueError("Value must be positive or zero, not %s" % str(value))
if strict and value <= 0:
raise ValueError("Value must be positive, not %s" % str(value)) | [
"def",
"check_positive",
"(",
"value",
",",
"strict",
"=",
"False",
")",
":",
"if",
"not",
"strict",
"and",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Value must be positive or zero, not %s\"",
"%",
"str",
"(",
"value",
")",
")",
"if",
"strict",
... | Checks if variable is positive
@param value: value to check
@type value: C{integer types}, C{float} or C{Decimal}
@return: None when check successful
@raise ValueError: check failed | [
"Checks",
"if",
"variable",
"is",
"positive"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/utils.py#L30-L44 |
20,560 | last-partizan/pytils | pytils/templatetags/pytils_translit.py | detranslify | def detranslify(text):
"""Detranslify russian text"""
try:
res = translit.detranslify(text)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
return res | python | def detranslify(text):
try:
res = translit.detranslify(text)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
return res | [
"def",
"detranslify",
"(",
"text",
")",
":",
"try",
":",
"res",
"=",
"translit",
".",
"detranslify",
"(",
"text",
")",
"except",
"Exception",
"as",
"err",
":",
"# because filter must die silently",
"res",
"=",
"default_value",
"%",
"{",
"'error'",
":",
"err"... | Detranslify russian text | [
"Detranslify",
"russian",
"text"
] | 1c570a32b15e564bc68587b8207e32d464e61d08 | https://github.com/last-partizan/pytils/blob/1c570a32b15e564bc68587b8207e32d464e61d08/pytils/templatetags/pytils_translit.py#L36-L43 |
20,561 | larsyencken/csvdiff | csvdiff/patch.py | apply | def apply(diff, recs, strict=True):
"""
Transform the records with the patch. May fail if the records do not
match those expected in the patch.
"""
index_columns = diff['_index']
indexed = records.index(copy.deepcopy(list(recs)), index_columns)
_add_records(indexed, diff['added'], index_columns, strict=strict)
_remove_records(indexed, diff['removed'], index_columns, strict=strict)
_update_records(indexed, diff['changed'], strict=strict)
return records.sort(indexed.values()) | python | def apply(diff, recs, strict=True):
index_columns = diff['_index']
indexed = records.index(copy.deepcopy(list(recs)), index_columns)
_add_records(indexed, diff['added'], index_columns, strict=strict)
_remove_records(indexed, diff['removed'], index_columns, strict=strict)
_update_records(indexed, diff['changed'], strict=strict)
return records.sort(indexed.values()) | [
"def",
"apply",
"(",
"diff",
",",
"recs",
",",
"strict",
"=",
"True",
")",
":",
"index_columns",
"=",
"diff",
"[",
"'_index'",
"]",
"indexed",
"=",
"records",
".",
"index",
"(",
"copy",
".",
"deepcopy",
"(",
"list",
"(",
"recs",
")",
")",
",",
"ind... | Transform the records with the patch. May fail if the records do not
match those expected in the patch. | [
"Transform",
"the",
"records",
"with",
"the",
"patch",
".",
"May",
"fail",
"if",
"the",
"records",
"do",
"not",
"match",
"those",
"expected",
"in",
"the",
"patch",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L106-L116 |
20,562 | larsyencken/csvdiff | csvdiff/patch.py | load | def load(istream, strict=True):
"Deserialize a patch object."
try:
diff = json.load(istream)
if strict:
jsonschema.validate(diff, SCHEMA)
except ValueError:
raise InvalidPatchError('patch is not valid JSON')
except jsonschema.exceptions.ValidationError as e:
raise InvalidPatchError(e.message)
return diff | python | def load(istream, strict=True):
"Deserialize a patch object."
try:
diff = json.load(istream)
if strict:
jsonschema.validate(diff, SCHEMA)
except ValueError:
raise InvalidPatchError('patch is not valid JSON')
except jsonschema.exceptions.ValidationError as e:
raise InvalidPatchError(e.message)
return diff | [
"def",
"load",
"(",
"istream",
",",
"strict",
"=",
"True",
")",
":",
"try",
":",
"diff",
"=",
"json",
".",
"load",
"(",
"istream",
")",
"if",
"strict",
":",
"jsonschema",
".",
"validate",
"(",
"diff",
",",
"SCHEMA",
")",
"except",
"ValueError",
":",
... | Deserialize a patch object. | [
"Deserialize",
"a",
"patch",
"object",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L175-L187 |
20,563 | larsyencken/csvdiff | csvdiff/patch.py | save | def save(diff, stream=sys.stdout, compact=False):
"Serialize a patch object."
flags = {'sort_keys': True}
if not compact:
flags['indent'] = 2
json.dump(diff, stream, **flags) | python | def save(diff, stream=sys.stdout, compact=False):
"Serialize a patch object."
flags = {'sort_keys': True}
if not compact:
flags['indent'] = 2
json.dump(diff, stream, **flags) | [
"def",
"save",
"(",
"diff",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"compact",
"=",
"False",
")",
":",
"flags",
"=",
"{",
"'sort_keys'",
":",
"True",
"}",
"if",
"not",
"compact",
":",
"flags",
"[",
"'indent'",
"]",
"=",
"2",
"json",
".",
"... | Serialize a patch object. | [
"Serialize",
"a",
"patch",
"object",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L190-L196 |
20,564 | larsyencken/csvdiff | csvdiff/patch.py | create | def create(from_records, to_records, index_columns, ignore_columns=None):
"""
Diff two sets of records, using the index columns as the primary key for
both datasets.
"""
from_indexed = records.index(from_records, index_columns)
to_indexed = records.index(to_records, index_columns)
if ignore_columns is not None:
from_indexed = records.filter_ignored(from_indexed, ignore_columns)
to_indexed = records.filter_ignored(to_indexed, ignore_columns)
return create_indexed(from_indexed, to_indexed, index_columns) | python | def create(from_records, to_records, index_columns, ignore_columns=None):
from_indexed = records.index(from_records, index_columns)
to_indexed = records.index(to_records, index_columns)
if ignore_columns is not None:
from_indexed = records.filter_ignored(from_indexed, ignore_columns)
to_indexed = records.filter_ignored(to_indexed, ignore_columns)
return create_indexed(from_indexed, to_indexed, index_columns) | [
"def",
"create",
"(",
"from_records",
",",
"to_records",
",",
"index_columns",
",",
"ignore_columns",
"=",
"None",
")",
":",
"from_indexed",
"=",
"records",
".",
"index",
"(",
"from_records",
",",
"index_columns",
")",
"to_indexed",
"=",
"records",
".",
"index... | Diff two sets of records, using the index columns as the primary key for
both datasets. | [
"Diff",
"two",
"sets",
"of",
"records",
"using",
"the",
"index",
"columns",
"as",
"the",
"primary",
"key",
"for",
"both",
"datasets",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L199-L211 |
20,565 | larsyencken/csvdiff | csvdiff/patch.py | _compare_rows | def _compare_rows(from_recs, to_recs, keys):
"Return the set of keys which have changed."
return set(
k for k in keys
if sorted(from_recs[k].items()) != sorted(to_recs[k].items())
) | python | def _compare_rows(from_recs, to_recs, keys):
"Return the set of keys which have changed."
return set(
k for k in keys
if sorted(from_recs[k].items()) != sorted(to_recs[k].items())
) | [
"def",
"_compare_rows",
"(",
"from_recs",
",",
"to_recs",
",",
"keys",
")",
":",
"return",
"set",
"(",
"k",
"for",
"k",
"in",
"keys",
"if",
"sorted",
"(",
"from_recs",
"[",
"k",
"]",
".",
"items",
"(",
")",
")",
"!=",
"sorted",
"(",
"to_recs",
"[",... | Return the set of keys which have changed. | [
"Return",
"the",
"set",
"of",
"keys",
"which",
"have",
"changed",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L236-L241 |
20,566 | larsyencken/csvdiff | csvdiff/patch.py | record_diff | def record_diff(lhs, rhs):
"Diff an individual row."
delta = {}
for k in set(lhs).union(rhs):
from_ = lhs[k]
to_ = rhs[k]
if from_ != to_:
delta[k] = {'from': from_, 'to': to_}
return delta | python | def record_diff(lhs, rhs):
"Diff an individual row."
delta = {}
for k in set(lhs).union(rhs):
from_ = lhs[k]
to_ = rhs[k]
if from_ != to_:
delta[k] = {'from': from_, 'to': to_}
return delta | [
"def",
"record_diff",
"(",
"lhs",
",",
"rhs",
")",
":",
"delta",
"=",
"{",
"}",
"for",
"k",
"in",
"set",
"(",
"lhs",
")",
".",
"union",
"(",
"rhs",
")",
":",
"from_",
"=",
"lhs",
"[",
"k",
"]",
"to_",
"=",
"rhs",
"[",
"k",
"]",
"if",
"from_... | Diff an individual row. | [
"Diff",
"an",
"individual",
"row",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L260-L269 |
20,567 | larsyencken/csvdiff | csvdiff/patch.py | filter_significance | def filter_significance(diff, significance):
"""
Prune any changes in the patch which are due to numeric changes less than this level of
significance.
"""
changed = diff['changed']
# remove individual field changes that are significant
reduced = [{'key': delta['key'],
'fields': {k: v
for k, v in delta['fields'].items()
if _is_significant(v, significance)}}
for delta in changed]
# call a key changed only if it still has significant changes
filtered = [delta for delta in reduced if delta['fields']]
diff = diff.copy()
diff['changed'] = filtered
return diff | python | def filter_significance(diff, significance):
changed = diff['changed']
# remove individual field changes that are significant
reduced = [{'key': delta['key'],
'fields': {k: v
for k, v in delta['fields'].items()
if _is_significant(v, significance)}}
for delta in changed]
# call a key changed only if it still has significant changes
filtered = [delta for delta in reduced if delta['fields']]
diff = diff.copy()
diff['changed'] = filtered
return diff | [
"def",
"filter_significance",
"(",
"diff",
",",
"significance",
")",
":",
"changed",
"=",
"diff",
"[",
"'changed'",
"]",
"# remove individual field changes that are significant",
"reduced",
"=",
"[",
"{",
"'key'",
":",
"delta",
"[",
"'key'",
"]",
",",
"'fields'",
... | Prune any changes in the patch which are due to numeric changes less than this level of
significance. | [
"Prune",
"any",
"changes",
"in",
"the",
"patch",
"which",
"are",
"due",
"to",
"numeric",
"changes",
"less",
"than",
"this",
"level",
"of",
"significance",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L304-L323 |
20,568 | larsyencken/csvdiff | csvdiff/patch.py | _is_significant | def _is_significant(change, significance):
"""
Return True if a change is genuinely significant given our tolerance.
"""
try:
a = float(change['from'])
b = float(change['to'])
except ValueError:
return True
return abs(a - b) > 10 ** (-significance) | python | def _is_significant(change, significance):
try:
a = float(change['from'])
b = float(change['to'])
except ValueError:
return True
return abs(a - b) > 10 ** (-significance) | [
"def",
"_is_significant",
"(",
"change",
",",
"significance",
")",
":",
"try",
":",
"a",
"=",
"float",
"(",
"change",
"[",
"'from'",
"]",
")",
"b",
"=",
"float",
"(",
"change",
"[",
"'to'",
"]",
")",
"except",
"ValueError",
":",
"return",
"True",
"re... | Return True if a change is genuinely significant given our tolerance. | [
"Return",
"True",
"if",
"a",
"change",
"is",
"genuinely",
"significant",
"given",
"our",
"tolerance",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L326-L337 |
20,569 | larsyencken/csvdiff | csvdiff/__init__.py | diff_files | def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None):
"""
Diff two CSV files, returning the patch which transforms one into the
other.
"""
with open(from_file) as from_stream:
with open(to_file) as to_stream:
from_records = records.load(from_stream, sep=sep)
to_records = records.load(to_stream, sep=sep)
return patch.create(from_records, to_records, index_columns,
ignore_columns=ignored_columns) | python | def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None):
with open(from_file) as from_stream:
with open(to_file) as to_stream:
from_records = records.load(from_stream, sep=sep)
to_records = records.load(to_stream, sep=sep)
return patch.create(from_records, to_records, index_columns,
ignore_columns=ignored_columns) | [
"def",
"diff_files",
"(",
"from_file",
",",
"to_file",
",",
"index_columns",
",",
"sep",
"=",
"','",
",",
"ignored_columns",
"=",
"None",
")",
":",
"with",
"open",
"(",
"from_file",
")",
"as",
"from_stream",
":",
"with",
"open",
"(",
"to_file",
")",
"as"... | Diff two CSV files, returning the patch which transforms one into the
other. | [
"Diff",
"two",
"CSV",
"files",
"returning",
"the",
"patch",
"which",
"transforms",
"one",
"into",
"the",
"other",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L28-L38 |
20,570 | larsyencken/csvdiff | csvdiff/__init__.py | patch_file | def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO,
strict: bool = True, sep: str = ','):
"""
Apply the patch to the source CSV file, and save the result to the target
file.
"""
diff = patch.load(patch_stream)
from_records = records.load(fromcsv_stream, sep=sep)
to_records = patch.apply(diff, from_records, strict=strict)
# what order should the columns be in?
if to_records:
# have data, use a nice ordering
all_columns = to_records[0].keys()
index_columns = diff['_index']
fieldnames = _nice_fieldnames(all_columns, index_columns)
else:
# no data, use the original order
fieldnames = from_records.fieldnames
records.save(to_records, fieldnames, tocsv_stream) | python | def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO,
strict: bool = True, sep: str = ','):
diff = patch.load(patch_stream)
from_records = records.load(fromcsv_stream, sep=sep)
to_records = patch.apply(diff, from_records, strict=strict)
# what order should the columns be in?
if to_records:
# have data, use a nice ordering
all_columns = to_records[0].keys()
index_columns = diff['_index']
fieldnames = _nice_fieldnames(all_columns, index_columns)
else:
# no data, use the original order
fieldnames = from_records.fieldnames
records.save(to_records, fieldnames, tocsv_stream) | [
"def",
"patch_file",
"(",
"patch_stream",
":",
"TextIO",
",",
"fromcsv_stream",
":",
"TextIO",
",",
"tocsv_stream",
":",
"TextIO",
",",
"strict",
":",
"bool",
"=",
"True",
",",
"sep",
":",
"str",
"=",
"','",
")",
":",
"diff",
"=",
"patch",
".",
"load",... | Apply the patch to the source CSV file, and save the result to the target
file. | [
"Apply",
"the",
"patch",
"to",
"the",
"source",
"CSV",
"file",
"and",
"save",
"the",
"result",
"to",
"the",
"target",
"file",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L49-L70 |
20,571 | larsyencken/csvdiff | csvdiff/__init__.py | patch_records | def patch_records(diff, from_records, strict=True):
"""
Apply the patch to the sequence of records, returning the transformed
records.
"""
return patch.apply(diff, from_records, strict=strict) | python | def patch_records(diff, from_records, strict=True):
return patch.apply(diff, from_records, strict=strict) | [
"def",
"patch_records",
"(",
"diff",
",",
"from_records",
",",
"strict",
"=",
"True",
")",
":",
"return",
"patch",
".",
"apply",
"(",
"diff",
",",
"from_records",
",",
"strict",
"=",
"strict",
")"
] | Apply the patch to the sequence of records, returning the transformed
records. | [
"Apply",
"the",
"patch",
"to",
"the",
"sequence",
"of",
"records",
"returning",
"the",
"transformed",
"records",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L73-L78 |
20,572 | larsyencken/csvdiff | csvdiff/__init__.py | _nice_fieldnames | def _nice_fieldnames(all_columns, index_columns):
"Indexes on the left, other fields in alphabetical order on the right."
non_index_columns = set(all_columns).difference(index_columns)
return index_columns + sorted(non_index_columns) | python | def _nice_fieldnames(all_columns, index_columns):
"Indexes on the left, other fields in alphabetical order on the right."
non_index_columns = set(all_columns).difference(index_columns)
return index_columns + sorted(non_index_columns) | [
"def",
"_nice_fieldnames",
"(",
"all_columns",
",",
"index_columns",
")",
":",
"non_index_columns",
"=",
"set",
"(",
"all_columns",
")",
".",
"difference",
"(",
"index_columns",
")",
"return",
"index_columns",
"+",
"sorted",
"(",
"non_index_columns",
")"
] | Indexes on the left, other fields in alphabetical order on the right. | [
"Indexes",
"on",
"the",
"left",
"other",
"fields",
"in",
"alphabetical",
"order",
"on",
"the",
"right",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L81-L84 |
20,573 | larsyencken/csvdiff | csvdiff/__init__.py | csvdiff_cmd | def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None,
sep=',', quiet=False, ignore_columns=None, significance=None):
"""
Compare two csv files to see what rows differ between them. The files
are each expected to have a header row, and for each row to be uniquely
identified by one or more indexing columns.
"""
if ignore_columns is not None:
for i in ignore_columns:
if i in index_columns:
error.abort("You can't ignore an index column")
ostream = (open(output, 'w') if output
else io.StringIO() if quiet
else sys.stdout)
try:
if style == 'summary':
_diff_and_summarize(from_csv, to_csv, index_columns, ostream,
sep=sep, ignored_columns=ignore_columns,
significance=significance)
else:
compact = (style == 'compact')
_diff_files_to_stream(from_csv, to_csv, index_columns, ostream,
compact=compact, sep=sep, ignored_columns=ignore_columns,
significance=significance)
except records.InvalidKeyError as e:
error.abort(e.args[0])
finally:
ostream.close() | python | def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None,
sep=',', quiet=False, ignore_columns=None, significance=None):
if ignore_columns is not None:
for i in ignore_columns:
if i in index_columns:
error.abort("You can't ignore an index column")
ostream = (open(output, 'w') if output
else io.StringIO() if quiet
else sys.stdout)
try:
if style == 'summary':
_diff_and_summarize(from_csv, to_csv, index_columns, ostream,
sep=sep, ignored_columns=ignore_columns,
significance=significance)
else:
compact = (style == 'compact')
_diff_files_to_stream(from_csv, to_csv, index_columns, ostream,
compact=compact, sep=sep, ignored_columns=ignore_columns,
significance=significance)
except records.InvalidKeyError as e:
error.abort(e.args[0])
finally:
ostream.close() | [
"def",
"csvdiff_cmd",
"(",
"index_columns",
",",
"from_csv",
",",
"to_csv",
",",
"style",
"=",
"None",
",",
"output",
"=",
"None",
",",
"sep",
"=",
"','",
",",
"quiet",
"=",
"False",
",",
"ignore_columns",
"=",
"None",
",",
"significance",
"=",
"None",
... | Compare two csv files to see what rows differ between them. The files
are each expected to have a header row, and for each row to be uniquely
identified by one or more indexing columns. | [
"Compare",
"two",
"csv",
"files",
"to",
"see",
"what",
"rows",
"differ",
"between",
"them",
".",
"The",
"files",
"are",
"each",
"expected",
"to",
"have",
"a",
"header",
"row",
"and",
"for",
"each",
"row",
"to",
"be",
"uniquely",
"identified",
"by",
"one"... | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L128-L160 |
20,574 | larsyencken/csvdiff | csvdiff/__init__.py | _diff_and_summarize | def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,
sep=',', ignored_columns=None, significance=None):
"""
Print a summary of the difference between the two files.
"""
from_records = list(records.load(from_csv, sep=sep))
to_records = records.load(to_csv, sep=sep)
diff = patch.create(from_records, to_records, index_columns, ignored_columns)
if significance is not None:
diff = patch.filter_significance(diff, significance)
_summarize_diff(diff, len(from_records), stream=stream)
exit_code = (EXIT_SAME
if patch.is_empty(diff)
else EXIT_DIFFERENT)
sys.exit(exit_code) | python | def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,
sep=',', ignored_columns=None, significance=None):
from_records = list(records.load(from_csv, sep=sep))
to_records = records.load(to_csv, sep=sep)
diff = patch.create(from_records, to_records, index_columns, ignored_columns)
if significance is not None:
diff = patch.filter_significance(diff, significance)
_summarize_diff(diff, len(from_records), stream=stream)
exit_code = (EXIT_SAME
if patch.is_empty(diff)
else EXIT_DIFFERENT)
sys.exit(exit_code) | [
"def",
"_diff_and_summarize",
"(",
"from_csv",
",",
"to_csv",
",",
"index_columns",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"sep",
"=",
"','",
",",
"ignored_columns",
"=",
"None",
",",
"significance",
"=",
"None",
")",
":",
"from_records",
"=",
"lis... | Print a summary of the difference between the two files. | [
"Print",
"a",
"summary",
"of",
"the",
"difference",
"between",
"the",
"two",
"files",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L178-L194 |
20,575 | larsyencken/csvdiff | csvdiff/__init__.py | csvpatch_cmd | def csvpatch_cmd(input_csv, input=None, output=None, strict=True):
"""
Apply the changes from a csvdiff patch to an existing CSV file.
"""
patch_stream = (sys.stdin
if input is None
else open(input))
tocsv_stream = (sys.stdout
if output is None
else open(output, 'w'))
fromcsv_stream = open(input_csv)
try:
patch_file(patch_stream, fromcsv_stream, tocsv_stream, strict=strict)
except patch.InvalidPatchError as e:
error.abort('reading patch, {0}'.format(e.args[0]))
finally:
patch_stream.close()
fromcsv_stream.close()
tocsv_stream.close() | python | def csvpatch_cmd(input_csv, input=None, output=None, strict=True):
patch_stream = (sys.stdin
if input is None
else open(input))
tocsv_stream = (sys.stdout
if output is None
else open(output, 'w'))
fromcsv_stream = open(input_csv)
try:
patch_file(patch_stream, fromcsv_stream, tocsv_stream, strict=strict)
except patch.InvalidPatchError as e:
error.abort('reading patch, {0}'.format(e.args[0]))
finally:
patch_stream.close()
fromcsv_stream.close()
tocsv_stream.close() | [
"def",
"csvpatch_cmd",
"(",
"input_csv",
",",
"input",
"=",
"None",
",",
"output",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"patch_stream",
"=",
"(",
"sys",
".",
"stdin",
"if",
"input",
"is",
"None",
"else",
"open",
"(",
"input",
")",
")",
... | Apply the changes from a csvdiff patch to an existing CSV file. | [
"Apply",
"the",
"changes",
"from",
"a",
"csvdiff",
"patch",
"to",
"an",
"existing",
"CSV",
"file",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L229-L250 |
20,576 | larsyencken/csvdiff | csvdiff/records.py | sort | def sort(records: Sequence[Record]) -> List[Record]:
"Sort records into a canonical order, suitable for comparison."
return sorted(records, key=_record_key) | python | def sort(records: Sequence[Record]) -> List[Record]:
"Sort records into a canonical order, suitable for comparison."
return sorted(records, key=_record_key) | [
"def",
"sort",
"(",
"records",
":",
"Sequence",
"[",
"Record",
"]",
")",
"->",
"List",
"[",
"Record",
"]",
":",
"return",
"sorted",
"(",
"records",
",",
"key",
"=",
"_record_key",
")"
] | Sort records into a canonical order, suitable for comparison. | [
"Sort",
"records",
"into",
"a",
"canonical",
"order",
"suitable",
"for",
"comparison",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L86-L88 |
20,577 | larsyencken/csvdiff | csvdiff/records.py | _record_key | def _record_key(record: Record) -> List[Tuple[Column, str]]:
"An orderable representation of this record."
return sorted(record.items()) | python | def _record_key(record: Record) -> List[Tuple[Column, str]]:
"An orderable representation of this record."
return sorted(record.items()) | [
"def",
"_record_key",
"(",
"record",
":",
"Record",
")",
"->",
"List",
"[",
"Tuple",
"[",
"Column",
",",
"str",
"]",
"]",
":",
"return",
"sorted",
"(",
"record",
".",
"items",
"(",
")",
")"
] | An orderable representation of this record. | [
"An",
"orderable",
"representation",
"of",
"this",
"record",
"."
] | 163dd9da676a8e5f926a935803726340261f03ae | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L91-L93 |
20,578 | Stewori/pytypes | pytypes/util.py | getargspecs | def getargspecs(func):
"""Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators.
"""
if func is None:
raise TypeError('None is not a Python function')
if hasattr(func, 'ch_func'):
return getargspecs(func.ch_func)
elif hasattr(func, 'ov_func'):
return getargspecs(func.ov_func)
if hasattr(inspect, 'getfullargspec'):
return inspect.getfullargspec(func) # Python 3
else:
return inspect.getargspec(func) | python | def getargspecs(func):
if func is None:
raise TypeError('None is not a Python function')
if hasattr(func, 'ch_func'):
return getargspecs(func.ch_func)
elif hasattr(func, 'ov_func'):
return getargspecs(func.ov_func)
if hasattr(inspect, 'getfullargspec'):
return inspect.getfullargspec(func) # Python 3
else:
return inspect.getargspec(func) | [
"def",
"getargspecs",
"(",
"func",
")",
":",
"if",
"func",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'None is not a Python function'",
")",
"if",
"hasattr",
"(",
"func",
",",
"'ch_func'",
")",
":",
"return",
"getargspecs",
"(",
"func",
".",
"ch_func",
... | Bridges inspect.getargspec and inspect.getfullargspec.
Automatically selects the proper one depending of current Python version.
Automatically bypasses wrappers from typechecked- and override-decorators. | [
"Bridges",
"inspect",
".",
"getargspec",
"and",
"inspect",
".",
"getfullargspec",
".",
"Automatically",
"selects",
"the",
"proper",
"one",
"depending",
"of",
"current",
"Python",
"version",
".",
"Automatically",
"bypasses",
"wrappers",
"from",
"typechecked",
"-",
... | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L94-L108 |
20,579 | Stewori/pytypes | pytypes/util.py | get_required_kwonly_args | def get_required_kwonly_args(argspecs):
"""Determines whether given argspecs implies required keywords-only args
and returns them as a list. Returns empty list if no such args exist.
"""
try:
kwonly = argspecs.kwonlyargs
if argspecs.kwonlydefaults is None:
return kwonly
res = []
for name in kwonly:
if not name in argspecs.kwonlydefaults:
res.append(name)
return res
except AttributeError:
return [] | python | def get_required_kwonly_args(argspecs):
try:
kwonly = argspecs.kwonlyargs
if argspecs.kwonlydefaults is None:
return kwonly
res = []
for name in kwonly:
if not name in argspecs.kwonlydefaults:
res.append(name)
return res
except AttributeError:
return [] | [
"def",
"get_required_kwonly_args",
"(",
"argspecs",
")",
":",
"try",
":",
"kwonly",
"=",
"argspecs",
".",
"kwonlyargs",
"if",
"argspecs",
".",
"kwonlydefaults",
"is",
"None",
":",
"return",
"kwonly",
"res",
"=",
"[",
"]",
"for",
"name",
"in",
"kwonly",
":"... | Determines whether given argspecs implies required keywords-only args
and returns them as a list. Returns empty list if no such args exist. | [
"Determines",
"whether",
"given",
"argspecs",
"implies",
"required",
"keywords",
"-",
"only",
"args",
"and",
"returns",
"them",
"as",
"a",
"list",
".",
"Returns",
"empty",
"list",
"if",
"no",
"such",
"args",
"exist",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L111-L125 |
20,580 | Stewori/pytypes | pytypes/util.py | getargnames | def getargnames(argspecs, with_unbox=False):
"""Resembles list of arg-names as would be seen in a function signature, including
var-args, var-keywords and keyword-only args.
"""
# todo: We can maybe make use of inspect.formatargspec
args = argspecs.args
vargs = argspecs.varargs
try:
kw = argspecs.keywords
except AttributeError:
kw = argspecs.varkw
try:
kwonly = argspecs.kwonlyargs
except AttributeError:
kwonly = None
res = []
if not args is None:
res.extend(args)
if not vargs is None:
res.append('*'+vargs if with_unbox else vargs)
if not kwonly is None:
res.extend(kwonly)
if not kw is None:
res.append('**'+kw if with_unbox else kw)
return res | python | def getargnames(argspecs, with_unbox=False):
# todo: We can maybe make use of inspect.formatargspec
args = argspecs.args
vargs = argspecs.varargs
try:
kw = argspecs.keywords
except AttributeError:
kw = argspecs.varkw
try:
kwonly = argspecs.kwonlyargs
except AttributeError:
kwonly = None
res = []
if not args is None:
res.extend(args)
if not vargs is None:
res.append('*'+vargs if with_unbox else vargs)
if not kwonly is None:
res.extend(kwonly)
if not kw is None:
res.append('**'+kw if with_unbox else kw)
return res | [
"def",
"getargnames",
"(",
"argspecs",
",",
"with_unbox",
"=",
"False",
")",
":",
"# todo: We can maybe make use of inspect.formatargspec",
"args",
"=",
"argspecs",
".",
"args",
"vargs",
"=",
"argspecs",
".",
"varargs",
"try",
":",
"kw",
"=",
"argspecs",
".",
"k... | Resembles list of arg-names as would be seen in a function signature, including
var-args, var-keywords and keyword-only args. | [
"Resembles",
"list",
"of",
"arg",
"-",
"names",
"as",
"would",
"be",
"seen",
"in",
"a",
"function",
"signature",
"including",
"var",
"-",
"args",
"var",
"-",
"keywords",
"and",
"keyword",
"-",
"only",
"args",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L128-L152 |
20,581 | Stewori/pytypes | pytypes/util.py | get_class_that_defined_method | def get_class_that_defined_method(meth):
"""Determines the class owning the given method.
"""
if is_classmethod(meth):
return meth.__self__
if hasattr(meth, 'im_class'):
return meth.im_class
elif hasattr(meth, '__qualname__'):
# Python 3
try:
cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')
cls = inspect.getmodule(meth)
for cls_name in cls_names:
cls = getattr(cls, cls_name)
if isinstance(cls, type):
return cls
except AttributeError:
# If this was called from a decorator and meth is not a method, this
# can result in AttributeError, because at decorator-time meth has not
# yet been added to module. If it's really a method, its class would be
# already in, so no problem in that case.
pass
raise ValueError(str(meth)+' is not a method.') | python | def get_class_that_defined_method(meth):
if is_classmethod(meth):
return meth.__self__
if hasattr(meth, 'im_class'):
return meth.im_class
elif hasattr(meth, '__qualname__'):
# Python 3
try:
cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')
cls = inspect.getmodule(meth)
for cls_name in cls_names:
cls = getattr(cls, cls_name)
if isinstance(cls, type):
return cls
except AttributeError:
# If this was called from a decorator and meth is not a method, this
# can result in AttributeError, because at decorator-time meth has not
# yet been added to module. If it's really a method, its class would be
# already in, so no problem in that case.
pass
raise ValueError(str(meth)+' is not a method.') | [
"def",
"get_class_that_defined_method",
"(",
"meth",
")",
":",
"if",
"is_classmethod",
"(",
"meth",
")",
":",
"return",
"meth",
".",
"__self__",
"if",
"hasattr",
"(",
"meth",
",",
"'im_class'",
")",
":",
"return",
"meth",
".",
"im_class",
"elif",
"hasattr",
... | Determines the class owning the given method. | [
"Determines",
"the",
"class",
"owning",
"the",
"given",
"method",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L415-L437 |
20,582 | Stewori/pytypes | pytypes/util.py | is_classmethod | def is_classmethod(meth):
"""Detects if the given callable is a classmethod.
"""
if inspect.ismethoddescriptor(meth):
return isinstance(meth, classmethod)
if not inspect.ismethod(meth):
return False
if not inspect.isclass(meth.__self__):
return False
if not hasattr(meth.__self__, meth.__name__):
return False
return meth == getattr(meth.__self__, meth.__name__) | python | def is_classmethod(meth):
if inspect.ismethoddescriptor(meth):
return isinstance(meth, classmethod)
if not inspect.ismethod(meth):
return False
if not inspect.isclass(meth.__self__):
return False
if not hasattr(meth.__self__, meth.__name__):
return False
return meth == getattr(meth.__self__, meth.__name__) | [
"def",
"is_classmethod",
"(",
"meth",
")",
":",
"if",
"inspect",
".",
"ismethoddescriptor",
"(",
"meth",
")",
":",
"return",
"isinstance",
"(",
"meth",
",",
"classmethod",
")",
"if",
"not",
"inspect",
".",
"ismethod",
"(",
"meth",
")",
":",
"return",
"Fa... | Detects if the given callable is a classmethod. | [
"Detects",
"if",
"the",
"given",
"callable",
"is",
"a",
"classmethod",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L463-L474 |
20,583 | Stewori/pytypes | pytypes/util.py | get_current_args | def get_current_args(caller_level = 0, func = None, argNames = None):
"""Determines the args of current function call.
Use caller_level > 0 to get args of even earlier function calls in current stack.
"""
if argNames is None:
argNames = getargnames(getargspecs(func))
if func is None:
func = get_current_function(caller_level+1)
if isinstance(func, property):
func = func.fget if func.fset is None else func.fset
stck = inspect.stack()
lcs = stck[1+caller_level][0].f_locals
return tuple([lcs[t] for t in argNames]) | python | def get_current_args(caller_level = 0, func = None, argNames = None):
if argNames is None:
argNames = getargnames(getargspecs(func))
if func is None:
func = get_current_function(caller_level+1)
if isinstance(func, property):
func = func.fget if func.fset is None else func.fset
stck = inspect.stack()
lcs = stck[1+caller_level][0].f_locals
return tuple([lcs[t] for t in argNames]) | [
"def",
"get_current_args",
"(",
"caller_level",
"=",
"0",
",",
"func",
"=",
"None",
",",
"argNames",
"=",
"None",
")",
":",
"if",
"argNames",
"is",
"None",
":",
"argNames",
"=",
"getargnames",
"(",
"getargspecs",
"(",
"func",
")",
")",
"if",
"func",
"i... | Determines the args of current function call.
Use caller_level > 0 to get args of even earlier function calls in current stack. | [
"Determines",
"the",
"args",
"of",
"current",
"function",
"call",
".",
"Use",
"caller_level",
">",
"0",
"to",
"get",
"args",
"of",
"even",
"earlier",
"function",
"calls",
"in",
"current",
"stack",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L531-L543 |
20,584 | Stewori/pytypes | pytypes/util.py | getmodule | def getmodule(code):
"""More robust variant of inspect.getmodule.
E.g. has less issues on Jython.
"""
try:
md = inspect.getmodule(code, code.co_filename)
except AttributeError:
return inspect.getmodule(code)
if md is None:
# Jython-specific:
# This is currently just a crutch; todo: resolve __pyclasspath__ properly!
cfname = code.co_filename.replace('__pyclasspath__',
os.path.realpath('')+os.sep+'__pyclasspath__')
cfname = cfname.replace('$py.class', '.py')
md = inspect.getmodule(code, cfname)
if md is None:
md = inspect.getmodule(code)
return md | python | def getmodule(code):
try:
md = inspect.getmodule(code, code.co_filename)
except AttributeError:
return inspect.getmodule(code)
if md is None:
# Jython-specific:
# This is currently just a crutch; todo: resolve __pyclasspath__ properly!
cfname = code.co_filename.replace('__pyclasspath__',
os.path.realpath('')+os.sep+'__pyclasspath__')
cfname = cfname.replace('$py.class', '.py')
md = inspect.getmodule(code, cfname)
if md is None:
md = inspect.getmodule(code)
return md | [
"def",
"getmodule",
"(",
"code",
")",
":",
"try",
":",
"md",
"=",
"inspect",
".",
"getmodule",
"(",
"code",
",",
"code",
".",
"co_filename",
")",
"except",
"AttributeError",
":",
"return",
"inspect",
".",
"getmodule",
"(",
"code",
")",
"if",
"md",
"is"... | More robust variant of inspect.getmodule.
E.g. has less issues on Jython. | [
"More",
"robust",
"variant",
"of",
"inspect",
".",
"getmodule",
".",
"E",
".",
"g",
".",
"has",
"less",
"issues",
"on",
"Jython",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L551-L568 |
20,585 | Stewori/pytypes | pytypes/util.py | _calc_traceback_limit | def _calc_traceback_limit(tb):
"""Calculates limit-parameter to strip away pytypes' internals when used
with API from traceback module.
"""
limit = 1
tb2 = tb
while not tb2.tb_next is None:
try:
maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2]
except IndexError:
maybe_pytypes = None
if maybe_pytypes == 'pytypes' and not \
tb2.tb_next.tb_frame.f_code == pytypes.typechecker._pytypes___import__.__code__:
break
else:
limit += 1
tb2 = tb2.tb_next
return limit | python | def _calc_traceback_limit(tb):
limit = 1
tb2 = tb
while not tb2.tb_next is None:
try:
maybe_pytypes = tb2.tb_next.tb_frame.f_code.co_filename.split(os.sep)[-2]
except IndexError:
maybe_pytypes = None
if maybe_pytypes == 'pytypes' and not \
tb2.tb_next.tb_frame.f_code == pytypes.typechecker._pytypes___import__.__code__:
break
else:
limit += 1
tb2 = tb2.tb_next
return limit | [
"def",
"_calc_traceback_limit",
"(",
"tb",
")",
":",
"limit",
"=",
"1",
"tb2",
"=",
"tb",
"while",
"not",
"tb2",
".",
"tb_next",
"is",
"None",
":",
"try",
":",
"maybe_pytypes",
"=",
"tb2",
".",
"tb_next",
".",
"tb_frame",
".",
"f_code",
".",
"co_filena... | Calculates limit-parameter to strip away pytypes' internals when used
with API from traceback module. | [
"Calculates",
"limit",
"-",
"parameter",
"to",
"strip",
"away",
"pytypes",
"internals",
"when",
"used",
"with",
"API",
"from",
"traceback",
"module",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L758-L775 |
20,586 | Stewori/pytypes | pytypes/util.py | _pytypes_excepthook | def _pytypes_excepthook(exctype, value, tb):
""""An excepthook suitable for use as sys.excepthook, that strips away
the part of the traceback belonging to pytypes' internals.
Can be switched on and off via pytypes.clean_traceback
or pytypes.set_clean_traceback.
The latter automatically installs this hook in sys.excepthook.
"""
if pytypes.clean_traceback and issubclass(exctype, TypeError):
traceback.print_exception(exctype, value, tb, _calc_traceback_limit(tb))
else:
if _sys_excepthook is None:
sys.__excepthook__(exctype, value, tb)
else:
_sys_excepthook(exctype, value, tb) | python | def _pytypes_excepthook(exctype, value, tb):
"if pytypes.clean_traceback and issubclass(exctype, TypeError):
traceback.print_exception(exctype, value, tb, _calc_traceback_limit(tb))
else:
if _sys_excepthook is None:
sys.__excepthook__(exctype, value, tb)
else:
_sys_excepthook(exctype, value, tb) | [
"def",
"_pytypes_excepthook",
"(",
"exctype",
",",
"value",
",",
"tb",
")",
":",
"if",
"pytypes",
".",
"clean_traceback",
"and",
"issubclass",
"(",
"exctype",
",",
"TypeError",
")",
":",
"traceback",
".",
"print_exception",
"(",
"exctype",
",",
"value",
",",... | An excepthook suitable for use as sys.excepthook, that strips away
the part of the traceback belonging to pytypes' internals.
Can be switched on and off via pytypes.clean_traceback
or pytypes.set_clean_traceback.
The latter automatically installs this hook in sys.excepthook. | [
"An",
"excepthook",
"suitable",
"for",
"use",
"as",
"sys",
".",
"excepthook",
"that",
"strips",
"away",
"the",
"part",
"of",
"the",
"traceback",
"belonging",
"to",
"pytypes",
"internals",
".",
"Can",
"be",
"switched",
"on",
"and",
"off",
"via",
"pytypes",
... | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L817-L830 |
20,587 | Stewori/pytypes | pytypes/type_util.py | get_generator_type | def get_generator_type(genr):
"""Obtains PEP 484 style type of a generator object, i.e. returns a
typing.Generator object.
"""
if genr in _checked_generator_types:
return _checked_generator_types[genr]
if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals:
return genr.gi_frame.f_locals['gen_type']
else:
cllble, nesting, slf = util.get_callable_fq_for_code(genr.gi_code)
if cllble is None:
return Generator
return _funcsigtypes(cllble, slf, nesting[-1] if slf else None,
genr.gi_frame.f_globals if not genr.gi_frame is None else None)[1] | python | def get_generator_type(genr):
if genr in _checked_generator_types:
return _checked_generator_types[genr]
if not genr.gi_frame is None and 'gen_type' in genr.gi_frame.f_locals:
return genr.gi_frame.f_locals['gen_type']
else:
cllble, nesting, slf = util.get_callable_fq_for_code(genr.gi_code)
if cllble is None:
return Generator
return _funcsigtypes(cllble, slf, nesting[-1] if slf else None,
genr.gi_frame.f_globals if not genr.gi_frame is None else None)[1] | [
"def",
"get_generator_type",
"(",
"genr",
")",
":",
"if",
"genr",
"in",
"_checked_generator_types",
":",
"return",
"_checked_generator_types",
"[",
"genr",
"]",
"if",
"not",
"genr",
".",
"gi_frame",
"is",
"None",
"and",
"'gen_type'",
"in",
"genr",
".",
"gi_fra... | Obtains PEP 484 style type of a generator object, i.e. returns a
typing.Generator object. | [
"Obtains",
"PEP",
"484",
"style",
"type",
"of",
"a",
"generator",
"object",
"i",
".",
"e",
".",
"returns",
"a",
"typing",
".",
"Generator",
"object",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L109-L122 |
20,588 | Stewori/pytypes | pytypes/type_util.py | get_Generic_parameters | def get_Generic_parameters(tp, generic_supertype):
"""tp must be a subclass of generic_supertype.
Retrieves the type values from tp that correspond to parameters
defined by generic_supertype.
E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent
to get_Mapping_key_value(tp) except for the error message.
Note that get_Generic_itemtype(tp) is not exactly equal to
get_Generic_parameters(tp, typing.Container), as that method
additionally contains treatment for typing.Tuple and typing.Iterable.
"""
try:
res = _select_Generic_superclass_parameters(tp, generic_supertype)
except TypeError:
res = None
if res is None:
raise TypeError("%s has no proper parameters defined by %s."%
(type_str(tp), type_str(generic_supertype)))
else:
return tuple(res) | python | def get_Generic_parameters(tp, generic_supertype):
try:
res = _select_Generic_superclass_parameters(tp, generic_supertype)
except TypeError:
res = None
if res is None:
raise TypeError("%s has no proper parameters defined by %s."%
(type_str(tp), type_str(generic_supertype)))
else:
return tuple(res) | [
"def",
"get_Generic_parameters",
"(",
"tp",
",",
"generic_supertype",
")",
":",
"try",
":",
"res",
"=",
"_select_Generic_superclass_parameters",
"(",
"tp",
",",
"generic_supertype",
")",
"except",
"TypeError",
":",
"res",
"=",
"None",
"if",
"res",
"is",
"None",
... | tp must be a subclass of generic_supertype.
Retrieves the type values from tp that correspond to parameters
defined by generic_supertype.
E.g. get_Generic_parameters(tp, typing.Mapping) is equivalent
to get_Mapping_key_value(tp) except for the error message.
Note that get_Generic_itemtype(tp) is not exactly equal to
get_Generic_parameters(tp, typing.Container), as that method
additionally contains treatment for typing.Tuple and typing.Iterable. | [
"tp",
"must",
"be",
"a",
"subclass",
"of",
"generic_supertype",
".",
"Retrieves",
"the",
"type",
"values",
"from",
"tp",
"that",
"correspond",
"to",
"parameters",
"defined",
"by",
"generic_supertype",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L218-L238 |
20,589 | Stewori/pytypes | pytypes/type_util.py | get_Tuple_params | def get_Tuple_params(tpl):
"""Python version independent function to obtain the parameters
of a typing.Tuple object.
Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
try:
return tpl.__tuple_params__
except AttributeError:
try:
if tpl.__args__ is None:
return None
# Python 3.6
if tpl.__args__[0] == ():
return ()
else:
if tpl.__args__[-1] is Ellipsis:
return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None
else:
return tpl.__args__
except AttributeError:
return None | python | def get_Tuple_params(tpl):
try:
return tpl.__tuple_params__
except AttributeError:
try:
if tpl.__args__ is None:
return None
# Python 3.6
if tpl.__args__[0] == ():
return ()
else:
if tpl.__args__[-1] is Ellipsis:
return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None
else:
return tpl.__args__
except AttributeError:
return None | [
"def",
"get_Tuple_params",
"(",
"tpl",
")",
":",
"try",
":",
"return",
"tpl",
".",
"__tuple_params__",
"except",
"AttributeError",
":",
"try",
":",
"if",
"tpl",
".",
"__args__",
"is",
"None",
":",
"return",
"None",
"# Python 3.6",
"if",
"tpl",
".",
"__args... | Python version independent function to obtain the parameters
of a typing.Tuple object.
Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. | [
"Python",
"version",
"independent",
"function",
"to",
"obtain",
"the",
"parameters",
"of",
"a",
"typing",
".",
"Tuple",
"object",
".",
"Omits",
"the",
"ellipsis",
"argument",
"if",
"present",
".",
"Use",
"is_Tuple_ellipsis",
"for",
"that",
".",
"Tested",
"with... | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L241-L262 |
20,590 | Stewori/pytypes | pytypes/type_util.py | is_Tuple_ellipsis | def is_Tuple_ellipsis(tpl):
"""Python version independent function to check if a typing.Tuple object
contains an ellipsis."""
try:
return tpl.__tuple_use_ellipsis__
except AttributeError:
try:
if tpl.__args__ is None:
return False
# Python 3.6
if tpl.__args__[-1] is Ellipsis:
return True
except AttributeError:
pass
return False | python | def is_Tuple_ellipsis(tpl):
try:
return tpl.__tuple_use_ellipsis__
except AttributeError:
try:
if tpl.__args__ is None:
return False
# Python 3.6
if tpl.__args__[-1] is Ellipsis:
return True
except AttributeError:
pass
return False | [
"def",
"is_Tuple_ellipsis",
"(",
"tpl",
")",
":",
"try",
":",
"return",
"tpl",
".",
"__tuple_use_ellipsis__",
"except",
"AttributeError",
":",
"try",
":",
"if",
"tpl",
".",
"__args__",
"is",
"None",
":",
"return",
"False",
"# Python 3.6",
"if",
"tpl",
".",
... | Python version independent function to check if a typing.Tuple object
contains an ellipsis. | [
"Python",
"version",
"independent",
"function",
"to",
"check",
"if",
"a",
"typing",
".",
"Tuple",
"object",
"contains",
"an",
"ellipsis",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L265-L279 |
20,591 | Stewori/pytypes | pytypes/type_util.py | is_Union | def is_Union(tp):
"""Python version independent check if a type is typing.Union.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
"""
if tp is Union:
return True
try:
# Python 3.6
return tp.__origin__ is Union
except AttributeError:
try:
return isinstance(tp, typing.UnionMeta)
except AttributeError:
return False | python | def is_Union(tp):
if tp is Union:
return True
try:
# Python 3.6
return tp.__origin__ is Union
except AttributeError:
try:
return isinstance(tp, typing.UnionMeta)
except AttributeError:
return False | [
"def",
"is_Union",
"(",
"tp",
")",
":",
"if",
"tp",
"is",
"Union",
":",
"return",
"True",
"try",
":",
"# Python 3.6",
"return",
"tp",
".",
"__origin__",
"is",
"Union",
"except",
"AttributeError",
":",
"try",
":",
"return",
"isinstance",
"(",
"tp",
",",
... | Python version independent check if a type is typing.Union.
Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1. | [
"Python",
"version",
"independent",
"check",
"if",
"a",
"type",
"is",
"typing",
".",
"Union",
".",
"Tested",
"with",
"CPython",
"2",
".",
"7",
"3",
".",
"5",
"3",
".",
"6",
"and",
"Jython",
"2",
".",
"7",
".",
"1",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L336-L349 |
20,592 | Stewori/pytypes | pytypes/type_util.py | is_builtin_type | def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | python | def is_builtin_type(tp):
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | [
"def",
"is_builtin_type",
"(",
"tp",
")",
":",
"return",
"hasattr",
"(",
"__builtins__",
",",
"tp",
".",
"__name__",
")",
"and",
"tp",
"is",
"getattr",
"(",
"__builtins__",
",",
"tp",
".",
"__name__",
")"
] | Checks if the given type is a builtin one. | [
"Checks",
"if",
"the",
"given",
"type",
"is",
"a",
"builtin",
"one",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L533-L536 |
20,593 | Stewori/pytypes | pytypes/type_util.py | get_types | def get_types(func):
"""Works like get_type_hints, but returns types as a sequence rather than a
dictionary. Types are returned in declaration order of the corresponding arguments.
"""
return _get_types(func, util.is_classmethod(func), util.is_method(func)) | python | def get_types(func):
return _get_types(func, util.is_classmethod(func), util.is_method(func)) | [
"def",
"get_types",
"(",
"func",
")",
":",
"return",
"_get_types",
"(",
"func",
",",
"util",
".",
"is_classmethod",
"(",
"func",
")",
",",
"util",
".",
"is_method",
"(",
"func",
")",
")"
] | Works like get_type_hints, but returns types as a sequence rather than a
dictionary. Types are returned in declaration order of the corresponding arguments. | [
"Works",
"like",
"get_type_hints",
"but",
"returns",
"types",
"as",
"a",
"sequence",
"rather",
"than",
"a",
"dictionary",
".",
"Types",
"are",
"returned",
"in",
"declaration",
"order",
"of",
"the",
"corresponding",
"arguments",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L780-L784 |
20,594 | Stewori/pytypes | pytypes/type_util.py | get_member_types | def get_member_types(obj, member_name, prop_getter = False):
"""Still experimental, incomplete and hardly tested.
Works like get_types, but is also applicable to descriptors.
"""
cls = obj.__class__
member = getattr(cls, member_name)
slf = not (isinstance(member, staticmethod) or isinstance(member, classmethod))
clsm = isinstance(member, classmethod)
return _get_types(member, clsm, slf, cls, prop_getter) | python | def get_member_types(obj, member_name, prop_getter = False):
cls = obj.__class__
member = getattr(cls, member_name)
slf = not (isinstance(member, staticmethod) or isinstance(member, classmethod))
clsm = isinstance(member, classmethod)
return _get_types(member, clsm, slf, cls, prop_getter) | [
"def",
"get_member_types",
"(",
"obj",
",",
"member_name",
",",
"prop_getter",
"=",
"False",
")",
":",
"cls",
"=",
"obj",
".",
"__class__",
"member",
"=",
"getattr",
"(",
"cls",
",",
"member_name",
")",
"slf",
"=",
"not",
"(",
"isinstance",
"(",
"member"... | Still experimental, incomplete and hardly tested.
Works like get_types, but is also applicable to descriptors. | [
"Still",
"experimental",
"incomplete",
"and",
"hardly",
"tested",
".",
"Works",
"like",
"get_types",
"but",
"is",
"also",
"applicable",
"to",
"descriptors",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L787-L795 |
20,595 | Stewori/pytypes | pytypes/type_util.py | _get_types | def _get_types(func, clsm, slf, clss = None, prop_getter = False,
unspecified_type = Any, infer_defaults = None):
"""Helper for get_types and get_member_types.
"""
func0 = util._actualfunc(func, prop_getter)
# check consistency regarding special case with 'self'-keyword
if not slf:
argNames = util.getargnames(util.getargspecs(func0))
if len(argNames) > 0:
if clsm:
if argNames[0] != 'cls':
util._warn_argname('classmethod using non-idiomatic cls argname',
func0, slf, clsm, clss)
if clss is None and (slf or clsm):
if slf:
assert util.is_method(func) or isinstance(func, property)
if clsm:
assert util.is_classmethod(func)
clss = util.get_class_that_defined_method(func)
assert hasattr(clss, func.__name__)
args, res = _funcsigtypes(func, slf or clsm, clss, None, prop_getter,
unspecified_type = unspecified_type, infer_defaults = infer_defaults)
return _match_stub_type(args), _match_stub_type(res) | python | def _get_types(func, clsm, slf, clss = None, prop_getter = False,
unspecified_type = Any, infer_defaults = None):
func0 = util._actualfunc(func, prop_getter)
# check consistency regarding special case with 'self'-keyword
if not slf:
argNames = util.getargnames(util.getargspecs(func0))
if len(argNames) > 0:
if clsm:
if argNames[0] != 'cls':
util._warn_argname('classmethod using non-idiomatic cls argname',
func0, slf, clsm, clss)
if clss is None and (slf or clsm):
if slf:
assert util.is_method(func) or isinstance(func, property)
if clsm:
assert util.is_classmethod(func)
clss = util.get_class_that_defined_method(func)
assert hasattr(clss, func.__name__)
args, res = _funcsigtypes(func, slf or clsm, clss, None, prop_getter,
unspecified_type = unspecified_type, infer_defaults = infer_defaults)
return _match_stub_type(args), _match_stub_type(res) | [
"def",
"_get_types",
"(",
"func",
",",
"clsm",
",",
"slf",
",",
"clss",
"=",
"None",
",",
"prop_getter",
"=",
"False",
",",
"unspecified_type",
"=",
"Any",
",",
"infer_defaults",
"=",
"None",
")",
":",
"func0",
"=",
"util",
".",
"_actualfunc",
"(",
"fu... | Helper for get_types and get_member_types. | [
"Helper",
"for",
"get_types",
"and",
"get_member_types",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L798-L820 |
20,596 | Stewori/pytypes | pytypes/type_util.py | _get_type_hints | def _get_type_hints(func, args = None, res = None, infer_defaults = None):
"""Helper for get_type_hints.
"""
if args is None or res is None:
args2, res2 = _get_types(func, util.is_classmethod(func),
util.is_method(func), unspecified_type = type(NotImplemented),
infer_defaults = infer_defaults)
if args is None:
args = args2
if res is None:
res = res2
slf = 1 if util.is_method(func) else 0
argNames = util.getargnames(util.getargspecs(util._actualfunc(func)))
result = {}
if not args is Any:
prms = get_Tuple_params(args)
for i in range(slf, len(argNames)):
if not prms[i-slf] is type(NotImplemented):
result[argNames[i]] = prms[i-slf]
result['return'] = res
return result | python | def _get_type_hints(func, args = None, res = None, infer_defaults = None):
if args is None or res is None:
args2, res2 = _get_types(func, util.is_classmethod(func),
util.is_method(func), unspecified_type = type(NotImplemented),
infer_defaults = infer_defaults)
if args is None:
args = args2
if res is None:
res = res2
slf = 1 if util.is_method(func) else 0
argNames = util.getargnames(util.getargspecs(util._actualfunc(func)))
result = {}
if not args is Any:
prms = get_Tuple_params(args)
for i in range(slf, len(argNames)):
if not prms[i-slf] is type(NotImplemented):
result[argNames[i]] = prms[i-slf]
result['return'] = res
return result | [
"def",
"_get_type_hints",
"(",
"func",
",",
"args",
"=",
"None",
",",
"res",
"=",
"None",
",",
"infer_defaults",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
"or",
"res",
"is",
"None",
":",
"args2",
",",
"res2",
"=",
"_get_types",
"(",
"func",
... | Helper for get_type_hints. | [
"Helper",
"for",
"get_type_hints",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L836-L856 |
20,597 | Stewori/pytypes | pytypes/type_util.py | _issubclass_Mapping_covariant | def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
This subclass-check treats Mapping-values as covariant.
"""
if is_Generic(subclass):
if subclass.__origin__ is None or not issubclass(subclass.__origin__, Mapping):
return _issubclass_Generic(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
if superclass.__args__ is None:
if not pytypes.check_unbound_types:
raise TypeError("Attempted to check unbound mapping type(superclass): "+
str(superclass))
if pytypes.strict_unknown_check:
# Nothing is subtype of unknown type
return False
super_args = (Any, Any)
else:
super_args = superclass.__args__
if subclass.__args__ is None:
if not pytypes.check_unbound_types:
raise TypeError("Attempted to check unbound mapping type(subclass): "+
str(subclass))
if pytypes.strict_unknown_check:
# Nothing can subclass unknown type
# For value type it would be okay if superclass had Any as value type,
# as unknown type is subtype of Any. However, since key type is invariant
# and also unknown, it cannot pass.
return False
sub_args = (Any, Any)
else:
sub_args = subclass.__args__
if not _issubclass(sub_args[0], super_args[0],
bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
return False
if not _issubclass(sub_args[1], super_args[1],
bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
return False
return True
return issubclass(subclass, superclass) | python | def _issubclass_Mapping_covariant(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
if is_Generic(subclass):
if subclass.__origin__ is None or not issubclass(subclass.__origin__, Mapping):
return _issubclass_Generic(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
if superclass.__args__ is None:
if not pytypes.check_unbound_types:
raise TypeError("Attempted to check unbound mapping type(superclass): "+
str(superclass))
if pytypes.strict_unknown_check:
# Nothing is subtype of unknown type
return False
super_args = (Any, Any)
else:
super_args = superclass.__args__
if subclass.__args__ is None:
if not pytypes.check_unbound_types:
raise TypeError("Attempted to check unbound mapping type(subclass): "+
str(subclass))
if pytypes.strict_unknown_check:
# Nothing can subclass unknown type
# For value type it would be okay if superclass had Any as value type,
# as unknown type is subtype of Any. However, since key type is invariant
# and also unknown, it cannot pass.
return False
sub_args = (Any, Any)
else:
sub_args = subclass.__args__
if not _issubclass(sub_args[0], super_args[0],
bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
return False
if not _issubclass(sub_args[1], super_args[1],
bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
return False
return True
return issubclass(subclass, superclass) | [
"def",
"_issubclass_Mapping_covariant",
"(",
"subclass",
",",
"superclass",
",",
"bound_Generic",
",",
"bound_typevars",
",",
"bound_typevars_readonly",
",",
"follow_fwd_refs",
",",
"_recursion_check",
")",
":",
"if",
"is_Generic",
"(",
"subclass",
")",
":",
"if",
"... | Helper for _issubclass, a.k.a pytypes.issubtype.
This subclass-check treats Mapping-values as covariant. | [
"Helper",
"for",
"_issubclass",
"a",
".",
"k",
".",
"a",
"pytypes",
".",
"issubtype",
".",
"This",
"subclass",
"-",
"check",
"treats",
"Mapping",
"-",
"values",
"as",
"covariant",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1104-L1145 |
20,598 | Stewori/pytypes | pytypes/type_util.py | _issubclass_Union_rec | def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass_Union.
"""
# this function is partly based on code from typing module 3.5.2.2
super_args = get_Union_params(superclass)
if super_args is None:
return is_Union(subclass)
elif is_Union(subclass):
sub_args = get_Union_params(subclass)
if sub_args is None:
return False
return all(_issubclass(c, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check) \
for c in (sub_args))
elif isinstance(subclass, TypeVar):
if subclass in super_args:
return True
if subclass.__constraints__:
return _issubclass(Union[subclass.__constraints__],
superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
return False
else:
return any(_issubclass(subclass, t, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check) \
for t in super_args) | python | def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
# this function is partly based on code from typing module 3.5.2.2
super_args = get_Union_params(superclass)
if super_args is None:
return is_Union(subclass)
elif is_Union(subclass):
sub_args = get_Union_params(subclass)
if sub_args is None:
return False
return all(_issubclass(c, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check) \
for c in (sub_args))
elif isinstance(subclass, TypeVar):
if subclass in super_args:
return True
if subclass.__constraints__:
return _issubclass(Union[subclass.__constraints__],
superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
return False
else:
return any(_issubclass(subclass, t, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check) \
for t in super_args) | [
"def",
"_issubclass_Union_rec",
"(",
"subclass",
",",
"superclass",
",",
"bound_Generic",
",",
"bound_typevars",
",",
"bound_typevars_readonly",
",",
"follow_fwd_refs",
",",
"_recursion_check",
")",
":",
"# this function is partly based on code from typing module 3.5.2.2",
"sup... | Helper for _issubclass_Union. | [
"Helper",
"for",
"_issubclass_Union",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1532-L1558 |
20,599 | Stewori/pytypes | pytypes/type_util.py | _isinstance | def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None,
bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None):
"""Access this via ``pytypes.is_of_type``.
Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module.
obj : Any
The object to check for being an instance of ``cls``.
cls : type
The type to check for ``obj`` being an instance of.
bound_Generic : Optional[Generic]
A type object holding values for unbound typevars occurring in ``cls``.
Default: None
If ``cls`` contains unbound ``TypeVar``s and ``bound_Generic`` is provided, this function
attempts to retrieve corresponding values for the unbound ``TypeVar``s from ``bound_Generic``.
In collision case with ``bound_typevars`` the value from ``bound_Generic`` if preferred.
bound_typevars : Optional[Dict[typing.TypeVar, type]]
A dictionary holding values for unbound typevars occurring in ``cls``.
Default: {}
Depending on ``bound_typevars_readonly`` pytypes can also bind values to typevars as needed.
This is done by inserting according mappings into this dictionary. This can e.g. be useful to
infer values for ``TypeVar``s or to consistently check a set of ``TypeVar``s across multiple
calls, e.g. when checking all arguments of a function call.
In collision case with ``bound_Generic`` the value from ``bound_Generic`` if preferred.
bound_typevars_readonly : bool
Defines if pytypes is allowed to write into the ``bound_typevars`` dictionary.
Default: True
If set to False, pytypes cannot assign values to ``TypeVar``s, but only checks regarding
values already present in ``bound_typevars`` or ``bound_Generic``.
follow_fwd_refs : bool
Defines if ``ForwardRef``s should be explored.
Default: True
If this is set to ``False`` and a ``ForwardRef`` is encountered, pytypes aborts the check
raising a ForwardRefError.
_recursion_check : Optional[Dict[type, Set[type]]]
Internally used for recursion checks.
Default: None
If ``Union``s and ``ForwardRef``s occur in the same type, recursions can occur. As soon as
a ``ForwardRef`` is encountered, pytypes automatically creates this dictionary and
continues in recursion-proof manner.
"""
if bound_typevars is None:
bound_typevars = {}
# Special treatment if cls is Iterable[...]
if is_Generic(cls) and cls.__origin__ is typing.Iterable:
if not is_iterable(obj):
return False
itp = get_iterable_itemtype(obj)
if itp is None:
return not pytypes.check_iterables
else:
return _issubclass(itp, cls.__args__[0], bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
if is_Callable(cls):
return _isinstance_Callable(obj, cls, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
return _issubclass(deep_type(obj), cls, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check) | python | def _isinstance(obj, cls, bound_Generic=None, bound_typevars=None,
bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None):
if bound_typevars is None:
bound_typevars = {}
# Special treatment if cls is Iterable[...]
if is_Generic(cls) and cls.__origin__ is typing.Iterable:
if not is_iterable(obj):
return False
itp = get_iterable_itemtype(obj)
if itp is None:
return not pytypes.check_iterables
else:
return _issubclass(itp, cls.__args__[0], bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
if is_Callable(cls):
return _isinstance_Callable(obj, cls, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check)
return _issubclass(deep_type(obj), cls, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check) | [
"def",
"_isinstance",
"(",
"obj",
",",
"cls",
",",
"bound_Generic",
"=",
"None",
",",
"bound_typevars",
"=",
"None",
",",
"bound_typevars_readonly",
"=",
"False",
",",
"follow_fwd_refs",
"=",
"True",
",",
"_recursion_check",
"=",
"None",
")",
":",
"if",
"bou... | Access this via ``pytypes.is_of_type``.
Works like ``isinstance``, but supports PEP 484 style types from ``typing`` module.
obj : Any
The object to check for being an instance of ``cls``.
cls : type
The type to check for ``obj`` being an instance of.
bound_Generic : Optional[Generic]
A type object holding values for unbound typevars occurring in ``cls``.
Default: None
If ``cls`` contains unbound ``TypeVar``s and ``bound_Generic`` is provided, this function
attempts to retrieve corresponding values for the unbound ``TypeVar``s from ``bound_Generic``.
In collision case with ``bound_typevars`` the value from ``bound_Generic`` if preferred.
bound_typevars : Optional[Dict[typing.TypeVar, type]]
A dictionary holding values for unbound typevars occurring in ``cls``.
Default: {}
Depending on ``bound_typevars_readonly`` pytypes can also bind values to typevars as needed.
This is done by inserting according mappings into this dictionary. This can e.g. be useful to
infer values for ``TypeVar``s or to consistently check a set of ``TypeVar``s across multiple
calls, e.g. when checking all arguments of a function call.
In collision case with ``bound_Generic`` the value from ``bound_Generic`` if preferred.
bound_typevars_readonly : bool
Defines if pytypes is allowed to write into the ``bound_typevars`` dictionary.
Default: True
If set to False, pytypes cannot assign values to ``TypeVar``s, but only checks regarding
values already present in ``bound_typevars`` or ``bound_Generic``.
follow_fwd_refs : bool
Defines if ``ForwardRef``s should be explored.
Default: True
If this is set to ``False`` and a ``ForwardRef`` is encountered, pytypes aborts the check
raising a ForwardRefError.
_recursion_check : Optional[Dict[type, Set[type]]]
Internally used for recursion checks.
Default: None
If ``Union``s and ``ForwardRef``s occur in the same type, recursions can occur. As soon as
a ``ForwardRef`` is encountered, pytypes automatically creates this dictionary and
continues in recursion-proof manner. | [
"Access",
"this",
"via",
"pytypes",
".",
"is_of_type",
".",
"Works",
"like",
"isinstance",
"but",
"supports",
"PEP",
"484",
"style",
"types",
"from",
"typing",
"module",
"."
] | b814d38709e84c0e0825caf8b721c20eb5a8ab3b | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1847-L1909 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.