Code
stringlengths 103
85.9k
| Summary
sequencelengths 0
94
|
---|---|
Please provide a description of the function: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') | [
"Get current app from Flast stack to use.\n\n This will allow to ensure which Redis connection to be used when\n accessing Redis connection public methods via plugin.\n "
] |
Please provide a description of the function: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) | [
"\n Actual method to read redis settings from app configuration, initialize\n Redis connection and copy all public connection methods to current\n instance.\n\n :param app: :class:`flask.Flask` application instance.\n :param config_prefix: Config prefix to use. By default: ``REDIS``\n "
] |
Please provide a description of the function: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 | [
"Read connection args spec, exclude self from list of possible\n\n :param klass: Redis connection class.\n "
] |
Please provide a description of the function: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) | [
"Include public methods from Redis connection to current instance.\n\n :param connection: Redis connection instance.\n "
] |
Please provide a description of the function:def _wrap_public_method(self, attr):
def wrapper(*args, **kwargs):
return getattr(self.connection, attr)(*args, **kwargs)
return wrapper | [
"\n Ensure that plugin will call current connection method when accessing\n as ``plugin.<public_method>(*args, **kwargs)``.\n "
] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function:def add_volume(self, hostpath, contpath, options=None):
'''Add a volume (bind-mount) to the docker run invocation
'''
if options is None:
options = []
self.volumes.append((hostpath, contpath, options)) | [] |
Please provide a description of the function: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)) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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()) | [] |
Please provide a description of the function: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, '')) | [
"Parse an environment variable string\n\n Returns a key-value tuple\n\n Apply the same logic as `docker run -e`:\n \"If the operator names an environment variable without specifying a value,\n then the current value of the named variable is propagated into the\n container's environment\n "
] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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] | [] |
Please provide a description of the function: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)) | [] |
Please provide a description of the function: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)) | [] |
Please provide a description of the function: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)) | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def from_yaml(self, node):
'''
Implementes a !from_yaml constructor with the following syntax:
!from_yaml filename key
Arguments:
filename: Filename of external YAML document from which to load,
relative to the current YAML file.
key: Key from external YAML document to return,
using a dot-separated syntax for nested keys.
Examples:
!from_yaml external.yml pop
!from_yaml external.yml foo.bar.pop
!from_yaml "another file.yml" "foo bar.snap crackle.pop"
'''
# Load the content from the node, as a scalar
content = self.construct_scalar(node)
# Split on unquoted spaces
try:
parts = shlex.split(content)
except UnicodeEncodeError:
raise yaml.YAMLError('Non-ASCII arguments to !from_yaml are unsupported')
if len(parts) != 2:
raise yaml.YAMLError('Two arguments expected to !from_yaml')
filename, key = parts
# path is relative to the current YAML document
path = os.path.join(self._root, filename)
# Load the other YAML document
with open(path, 'r') as f:
doc = yaml.load(f, self.__class__)
# Retrieve the key
try:
cur = doc
for k in key.split('.'):
cur = cur[k]
except KeyError:
raise yaml.YAMLError('Key "{}" not found in {}'.format(key, filename))
return cur | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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] | [] |
Please provide a description of the function:def get_country_short(self, ip):
''' Get country_short '''
rec = self.get_all(ip)
return rec and rec.country_short | [] |
Please provide a description of the function:def get_country_long(self, ip):
''' Get country_long '''
rec = self.get_all(ip)
return rec and rec.country_long | [] |
Please provide a description of the function:def get_region(self, ip):
''' Get region '''
rec = self.get_all(ip)
return rec and rec.region | [] |
Please provide a description of the function:def get_city(self, ip):
''' Get city '''
rec = self.get_all(ip)
return rec and rec.city | [] |
Please provide a description of the function:def get_isp(self, ip):
''' Get isp '''
rec = self.get_all(ip)
return rec and rec.isp | [] |
Please provide a description of the function:def get_latitude(self, ip):
''' Get latitude '''
rec = self.get_all(ip)
return rec and rec.latitude | [] |
Please provide a description of the function:def get_longitude(self, ip):
''' Get longitude '''
rec = self.get_all(ip)
return rec and rec.longitude | [] |
Please provide a description of the function:def get_domain(self, ip):
''' Get domain '''
rec = self.get_all(ip)
return rec and rec.domain | [] |
Please provide a description of the function:def get_zipcode(self, ip):
''' Get zipcode '''
rec = self.get_all(ip)
return rec and rec.zipcode | [] |
Please provide a description of the function:def get_timezone(self, ip):
''' Get timezone '''
rec = self.get_all(ip)
return rec and rec.timezone | [] |
Please provide a description of the function:def get_netspeed(self, ip):
''' Get netspeed '''
rec = self.get_all(ip)
return rec and rec.netspeed | [] |
Please provide a description of the function:def get_idd_code(self, ip):
''' Get idd_code '''
rec = self.get_all(ip)
return rec and rec.idd_code | [] |
Please provide a description of the function:def get_area_code(self, ip):
''' Get area_code '''
rec = self.get_all(ip)
return rec and rec.area_code | [] |
Please provide a description of the function:def get_weather_code(self, ip):
''' Get weather_code '''
rec = self.get_all(ip)
return rec and rec.weather_code | [] |
Please provide a description of the function:def get_weather_name(self, ip):
''' Get weather_name '''
rec = self.get_all(ip)
return rec and rec.weather_name | [] |
Please provide a description of the function:def get_mcc(self, ip):
''' Get mcc '''
rec = self.get_all(ip)
return rec and rec.mcc | [] |
Please provide a description of the function:def get_mnc(self, ip):
''' Get mnc '''
rec = self.get_all(ip)
return rec and rec.mnc | [] |
Please provide a description of the function:def get_mobile_brand(self, ip):
''' Get mobile_brand '''
rec = self.get_all(ip)
return rec and rec.mobile_brand | [] |
Please provide a description of the function:def get_elevation(self, ip):
''' Get elevation '''
rec = self.get_all(ip)
return rec and rec.elevation | [] |
Please provide a description of the function:def get_usage_type(self, ip):
''' Get usage_type '''
rec = self.get_all(ip)
return rec and rec.usage_type | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function:def rates_for_location(self, postal_code, location_deets=None):
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request) | [
"Shows the sales tax rates for a given location."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def list_orders(self, params=None):
request = self._get('transactions/orders', params)
return self.responder(request) | [
"Lists existing order transactions."
] |
Please provide a description of the function:def show_order(self, order_id):
request = self._get('transactions/orders/' + str(order_id))
return self.responder(request) | [
"Shows an existing order transaction."
] |
Please provide a description of the function:def create_order(self, order_deets):
request = self._post('transactions/orders', order_deets)
return self.responder(request) | [
"Creates a new order transaction."
] |
Please provide a description of the function:def update_order(self, order_id, order_deets):
request = self._put("transactions/orders/" + str(order_id), order_deets)
return self.responder(request) | [
"Updates an existing order transaction."
] |
Please provide a description of the function:def delete_order(self, order_id):
request = self._delete("transactions/orders/" + str(order_id))
return self.responder(request) | [
"Deletes an existing order transaction."
] |
Please provide a description of the function:def list_refunds(self, params=None):
request = self._get('transactions/refunds', params)
return self.responder(request) | [
"Lists existing refund transactions."
] |
Please provide a description of the function:def show_refund(self, refund_id):
request = self._get('transactions/refunds/' + str(refund_id))
return self.responder(request) | [
"Shows an existing refund transaction."
] |
Please provide a description of the function:def create_refund(self, refund_deets):
request = self._post('transactions/refunds', refund_deets)
return self.responder(request) | [
"Creates a new refund transaction."
] |
Please provide a description of the function:def update_refund(self, refund_id, refund_deets):
request = self._put('transactions/refunds/' + str(refund_id), refund_deets)
return self.responder(request) | [
"Updates an existing refund transaction."
] |
Please provide a description of the function:def delete_refund(self, refund_id):
request = self._delete('transactions/refunds/' + str(refund_id))
return self.responder(request) | [
"Deletes an existing refund transaction."
] |
Please provide a description of the function:def list_customers(self, params=None):
request = self._get('customers', params)
return self.responder(request) | [
"Lists existing customers."
] |
Please provide a description of the function:def show_customer(self, customer_id):
request = self._get('customers/' + str(customer_id))
return self.responder(request) | [
"Shows an existing customer."
] |
Please provide a description of the function:def create_customer(self, customer_deets):
request = self._post('customers', customer_deets)
return self.responder(request) | [
"Creates a new customer."
] |
Please provide a description of the function:def update_customer(self, customer_id, customer_deets):
request = self._put("customers/" + str(customer_id), customer_deets)
return self.responder(request) | [
"Updates an existing customer."
] |
Please provide a description of the function:def delete_customer(self, customer_id):
request = self._delete("customers/" + str(customer_id))
return self.responder(request) | [
"Deletes an existing customer."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def validate(self, vat_deets):
request = self._get('validation', vat_deets)
return self.responder(request) | [
"Validates an existing VAT identification number against VIES."
] |
Please provide a description of the function:def get_score(self, terms):
assert isinstance(terms, list) or isinstance(terms, tuple)
score_li = np.asarray([self._get_score(t) for t in terms])
s_pos = np.sum(score_li[score_li > 0])
s_neg = -np.sum(score_li[score_li < 0])
s_pol = (s_pos-s_neg) * 1.0 / ((s_pos+s_neg)+self.EPSILON)
s_sub = (s_pos+s_neg) * 1.0 / (len(score_li)+self.EPSILON)
return {self.TAG_POS: s_pos,
self.TAG_NEG: s_neg,
self.TAG_POL: s_pol,
self.TAG_SUB: s_sub} | [
"Get score for a list of terms.\n \n :type terms: list\n :param terms: A list of terms to be analyzed.\n \n :returns: dict\n "
] |
Please provide a description of the function: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 | [
"\n Choose proper form for plural.\n\n Value is a amount, parameters are forms of noun.\n Forms are variants for 1, 2, 5 nouns. It may be tuple\n of elements, or string where variants separates each other\n by comma.\n\n Examples::\n {{ some_int|choose_plural:\"пример,примера,примеров\" }}\n "
] |
Please provide a description of the function:def rubles(amount, zero_for_kopeck=False):
try:
res = numeral.rubles(amount, zero_for_kopeck)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': str(amount)}
return res | [
"Converts float value to in-words representation (for money)"
] |
Please provide a description of the function: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 | [
"\n In-words representation of amount.\n\n Parameter is a gender: MALE, FEMALE or NEUTER\n\n Examples::\n {{ some_int|in_words }}\n {{ some_other_int|in_words:FEMALE }}\n "
] |
Please provide a description of the function: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 | [
"\n in_words and choose_plural in a one flask\n Makes in-words representation of value with\n choosing correct form of noun.\n\n First parameter is an amount of objects. Second is a\n gender (MALE, FEMALE, NEUTER). Third is a variants\n of forms for object name.\n\n Examples::\n {% sum_string some_int MALE \"пример,примера,примеров\" %}\n {% sum_string some_other_int FEMALE \"задача,задачи,задач\" %}\n "
] |
Please provide a description of the function:def _sub_patterns(patterns, text):
for pattern, repl in patterns:
text = re.sub(pattern, repl, text)
return text | [
"\n Apply re.sub to bunch of (pattern, repl)\n "
] |
Please provide a description of the function: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)
) | [
"\n Clean double spaces, trailing spaces, heading spaces,\n spaces before punctuations\n "
] |
Please provide a description of the function:def rl_ellipsis(x):
patterns = (
# если больше трех точек, то не заменяем на троеточие
# чтобы не было глупых .....->…..
(r'([^\.]|^)\.\.\.([^\.]|$)', u'\\1\u2026\\2'),
# если троеточие в начале строки или возле кавычки --
# это цитата, пробел между троеточием и первым
# словом нужно убрать
(re.compile(u'(^|\\"|\u201c|\xab)\\s*\u2026\\s*([А-Яа-яA-Za-z])', re.UNICODE), u'\\1\u2026\\2'),
)
return _sub_patterns(patterns, x) | [
"\n Replace three dots to ellipsis\n "
] |
Please provide a description of the function:def rl_initials(x):
return re.sub(
re.compile(u'([А-Я])\\.\\s*([А-Я])\\.\\s*([А-Я][а-я]+)', re.UNICODE),
u'\\1.\\2.\u2009\\3',
x
) | [
"\n Replace space between initials and surname by thin space\n "
] |
Please provide a description of the function:def rl_dashes(x):
patterns = (
# тире
(re.compile(u'(^|(.\\s))\\-\\-?(([\\s\u202f].)|$)', re.MULTILINE|re.UNICODE), u'\\1\u2014\\3'),
# диапазоны между цифрами - en dash
(re.compile(u'(\\d[\\s\u2009]*)\\-([\\s\u2009]*\d)', re.MULTILINE|re.UNICODE), u'\\1\u2013\\2'),
# TODO: а что с минусом?
)
return _sub_patterns(patterns, x) | [
"\n Replace dash to long/medium dashes\n "
] |
Please provide a description of the function:def rl_wordglue(x):
patterns = (
# частицы склеиваем с предыдущим словом
(re.compile(u'(\\s+)(же|ли|ль|бы|б|ж|ка)([\\.,!\\?:;]?\\s+)', re.UNICODE), u'\u202f\\2\\3'),
# склеиваем короткие слова со следующим словом
(re.compile(u'\\b([a-zA-ZА-Яа-я]{1,3})(\\s+)', re.UNICODE), u'\\1\u202f'),
# склеиваем тире с предыдущим словом
(re.compile(u'(\\s+)([\u2014\\-]+)(\\s+)', re.UNICODE), u'\u202f\\2\\3'),
# склеиваем два последних слова в абзаце между собой
# полагается, что абзацы будут передаваться отдельной строкой
(re.compile(u'([^\\s]+)\\s+([^\\s]+)$', re.UNICODE), u'\\1\u202f\\2'),
)
return _sub_patterns(patterns, x) | [
"\n Glue (set nonbreakable space) short words with word before/after\n "
] |
Please provide a description of the function:def rl_marks(x):
# простые замены, можно без регулярок
replacements = (
(u'(r)', u'\u00ae'), # ®
(u'(R)', u'\u00ae'), # ®
(u'(p)', u'\u00a7'), # §
(u'(P)', u'\u00a7'), # §
(u'(tm)', u'\u2122'), # ™
(u'(TM)', u'\u2122'), # ™
)
patterns = (
# копирайт ставится до года: © 2008 Юрий Юревич
(re.compile(u'\\([cCсС]\\)\\s*(\\d+)', re.UNICODE), u'\u00a9\u202f\\1'),
(r'([^+])(\+\-|\-\+)', u'\\1\u00b1'), # ±
# градусы с минусом
(u'\\-(\\d+)[\\s]*([FCС][^\\w])', u'\u2212\\1\202f\u00b0\\2'), # −12 °C, −53 °F
# градусы без минуса
(u'(\\d+)[\\s]*([FCС][^\\w])', u'\\1\u202f\u00b0\\2'), # 12 °C, 53 °F
# ® и ™ приклеиваются к предыдущему слову, без пробела
(re.compile(u'([A-Za-zА-Яа-я\\!\\?])\\s*(\xae|\u2122)', re.UNICODE), u'\\1\\2'),
# No5 -> № 5
(re.compile(u'(\\s)(No|no|NO|\u2116)[\\s\u2009]*(\\d+)', re.UNICODE), u'\\1\u2116\u2009\\3'),
)
for what, to in replacements:
x = x.replace(what, to)
return _sub_patterns(patterns, x) | [
"\n Replace +-, (c), (tm), (r), (p), etc by its typographic eqivalents\n "
] |
Please provide a description of the function: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) | [
"\n Replace quotes by typographic quotes\n "
] |
Please provide a description of the function: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 | [
"\n Display distance of time from current time.\n\n Parameter is an accuracy level (deafult is 1).\n Value must be numeral (i.e. time.time() result) or\n datetime.datetime (i.e. datetime.datetime.now()\n result).\n\n Examples::\n {{ some_time|distance_of_time }}\n {{ some_dtime|distance_of_time:2 }}\n "
] |
Please provide a description of the function: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 | [
"\n Russian strftime, formats date with given format.\n\n Value is a date (supports datetime.date and datetime.datetime),\n parameter is a format (string). For explainings about format,\n see documentation for original strftime:\n http://docs.python.org/lib/module-time.html\n\n Examples::\n {{ some_date|ru_strftime:\"%d %B %Y, %A\" }}\n "
] |
Please provide a description of the function:def distance_of_time_in_words(from_time, accuracy=1, to_time=None):
current = False
if to_time is None:
current = True
to_time = datetime.datetime.now()
check_positive(accuracy, strict=True)
if not isinstance(from_time, datetime.datetime):
from_time = datetime.datetime.fromtimestamp(from_time)
if not isinstance(to_time, datetime.datetime):
to_time = datetime.datetime.fromtimestamp(to_time)
if from_time.tzinfo and not to_time.tzinfo:
to_time = to_time.replace(tzinfo=from_time.tzinfo)
dt_delta = to_time - from_time
difference = dt_delta.days*86400 + dt_delta.seconds
minutes_orig = int(abs(difference)/60.0)
hours_orig = int(abs(difference)/3600.0)
days_orig = int(abs(difference)/86400.0)
in_future = from_time > to_time
words = []
values = []
alternatives = []
days = days_orig
hours = hours_orig - days_orig*24
words.append(u"%d %s" % (days, numeral.choose_plural(days, DAY_VARIANTS)))
values.append(days)
words.append(u"%d %s" %
(hours, numeral.choose_plural(hours, HOUR_VARIANTS)))
values.append(hours)
days == 0 and hours == 1 and current and alternatives.append(u"час")
minutes = minutes_orig - hours_orig*60
words.append(u"%d %s" % (minutes,
numeral.choose_plural(minutes, MINUTE_VARIANTS)))
values.append(minutes)
days == 0 and hours == 0 and minutes == 1 and current and \
alternatives.append(u"минуту")
# убираем из values и words конечные нули
while values and not values[-1]:
values.pop()
words.pop()
# убираем из values и words начальные нули
while values and not values[0]:
values.pop(0)
words.pop(0)
limit = min(accuracy, len(words))
real_words = words[:limit]
real_values = values[:limit]
# снова убираем конечные нули
while real_values and not real_values[-1]:
real_values.pop()
real_words.pop()
limit -= 1
real_str = u" ".join(real_words)
# альтернативные варианты нужны только если в real_words одно значение
# и, вдобавок, если используется текущее время
alter_str = limit == 1 and current and alternatives and \
alternatives[0]
_result_str = alter_str or real_str
result_str = in_future and u"%s %s" % (PREFIX_IN, _result_str) \
or u"%s %s" % (_result_str, SUFFIX_AGO)
# если же прошло менее минуты, то real_words -- пустой, и поэтому
# нужно брать alternatives[0], а не result_str
zero_str = minutes == 0 and not real_words and \
(in_future and u"менее чем через минуту"
or u"менее минуты назад")
# нужно использовать вчера/позавчера/завтра/послезавтра
# если days 1..2 и в real_words одно значение
day_alternatives = DAY_ALTERNATIVES.get(days, False)
alternate_day = day_alternatives and current and limit == 1 and \
((in_future and day_alternatives[1])
or day_alternatives[0])
final_str = not real_words and zero_str or alternate_day or result_str
return final_str | [
"\n Represents distance of time in words\n\n @param from_time: source time (in seconds from epoch)\n @type from_time: C{int}, C{float} or C{datetime.datetime}\n\n @param accuracy: level of accuracy (1..3), default=1\n @type accuracy: C{int}\n\n @param to_time: target time (in seconds from epoch),\n default=None translates to current time\n @type to_time: C{int}, C{float} or C{datetime.datetime}\n\n @return: distance of time in words\n @rtype: unicode\n\n @raise ValueError: accuracy is lesser or equal zero\n "
] |
Please provide a description of the function: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 | [
"\n Russian strftime without locale\n\n @param format: strftime format, default=u'%d.%m.%Y'\n @type format: C{unicode}\n\n @param date: date value, default=None translates to today\n @type date: C{datetime.date} or C{datetime.datetime}\n\n @param inflected: is month inflected, default False\n @type inflected: C{bool}\n\n @param inflected_day: is day inflected, default False\n @type inflected: C{bool}\n\n @param preposition: is preposition used, default False\n preposition=True automatically implies inflected_day=True\n @type preposition: C{bool}\n\n @return: strftime string\n @rtype: unicode\n "
] |
Please provide a description of the function: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 | [
"\n Get remainder of float, i.e. 2.05 -> '05'\n\n @param fvalue: input value\n @type fvalue: C{integer types}, C{float} or C{Decimal}\n\n @param signs: maximum number of signs\n @type signs: C{integer types}\n\n @return: remainder\n @rtype: C{str}\n\n @raise ValueError: fvalue is negative\n @raise ValueError: signs overflow\n "
] |
Please provide a description of the function: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] | [
"\n Choose proper case depending on amount\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param variants: variants (forms) of object in such form:\n (1 object, 2 objects, 5 objects).\n @type variants: 3-element C{sequence} of C{unicode}\n or C{unicode} (three variants with delimeter ',')\n\n @return: proper variant\n @rtype: C{unicode}\n\n @raise ValueError: variants' length lesser than 3\n "
] |
Please provide a description of the function: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 | [
"\n Get proper case with value\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param variants: variants (forms) of object in such form:\n (1 object, 2 objects, 5 objects).\n @type variants: 3-element C{sequence} of C{unicode}\n or C{unicode} (three variants with delimeter ',')\n\n @param absence: if amount is zero will return it\n @type absence: C{unicode}\n\n @return: amount with proper variant\n @rtype: C{unicode}\n "
] |
Please provide a description of the function:def _get_plural_legacy(amount, extra_variants):
absence = None
if isinstance(extra_variants, six.text_type):
extra_variants = split_values(extra_variants)
if len(extra_variants) == 4:
variants = extra_variants[:3]
absence = extra_variants[3]
else:
variants = extra_variants
return get_plural(amount, variants, absence) | [
"\n Get proper case with value (legacy variant, without absence)\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param variants: variants (forms) of object in such form:\n (1 object, 2 objects, 5 objects, 0-object variant).\n 0-object variant is similar to C{absence} in C{get_plural}\n @type variants: 3-element C{sequence} of C{unicode}\n or C{unicode} (three variants with delimeter ',')\n\n @return: amount with proper variant\n @rtype: C{unicode}\n "
] |
Please provide a description of the function:def rubles(amount, zero_for_kopeck=False):
check_positive(amount)
pts = []
amount = round(amount, 2)
pts.append(sum_string(int(amount), 1, (u"рубль", u"рубля", u"рублей")))
remainder = _get_float_remainder(amount, 2)
iremainder = int(remainder)
if iremainder != 0 or zero_for_kopeck:
# если 3.1, то это 10 копеек, а не одна
if iremainder < 10 and len(remainder) == 1:
iremainder *= 10
pts.append(sum_string(iremainder, 2,
(u"копейка", u"копейки", u"копеек")))
return u" ".join(pts) | [
"\n Get string for money\n\n @param amount: amount of money\n @type amount: C{integer types}, C{float} or C{Decimal}\n\n @param zero_for_kopeck: If false, then zero kopecks ignored\n @type zero_for_kopeck: C{bool}\n\n @return: in-words representation of money's amount\n @rtype: C{unicode}\n\n @raise ValueError: amount is negative\n "
] |
Please provide a description of the function:def in_words_float(amount, _gender=FEMALE):
check_positive(amount)
pts = []
# преобразуем целую часть
pts.append(sum_string(int(amount), 2,
(u"целая", u"целых", u"целых")))
# теперь то, что после запятой
remainder = _get_float_remainder(amount)
signs = len(str(remainder)) - 1
pts.append(sum_string(int(remainder), 2, FRACTIONS[signs]))
return u" ".join(pts) | [
"\n Float in words\n\n @param amount: float numeral\n @type amount: C{float} or C{Decimal}\n\n @return: in-words reprsentation of float numeral\n @rtype: C{unicode}\n\n @raise ValueError: when ammount is negative\n "
] |
Please provide a description of the function: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)) | [
"\n Numeral in words\n\n @param amount: numeral\n @type amount: C{integer types}, C{float} or C{Decimal}\n\n @param gender: gender (MALE, FEMALE or NEUTER)\n @type gender: C{int}\n\n @return: in-words reprsentation of numeral\n @rtype: C{unicode}\n\n raise ValueError: when amount is negative\n "
] |
Please provide a description of the function:def sum_string(amount, gender, items=None):
if isinstance(items, six.text_type):
items = split_values(items)
if items is None:
items = (u"", u"", u"")
try:
one_item, two_items, five_items = items
except ValueError:
raise ValueError("Items must be 3-element sequence")
check_positive(amount)
if amount == 0:
if five_items:
return u"ноль %s" % five_items
else:
return u"ноль"
into = u''
tmp_val = amount
# единицы
into, tmp_val = _sum_string_fn(into, tmp_val, gender, items)
# тысячи
into, tmp_val = _sum_string_fn(into, tmp_val, FEMALE,
(u"тысяча", u"тысячи", u"тысяч"))
# миллионы
into, tmp_val = _sum_string_fn(into, tmp_val, MALE,
(u"миллион", u"миллиона", u"миллионов"))
# миллиарды
into, tmp_val = _sum_string_fn(into, tmp_val, MALE,
(u"миллиард", u"миллиарда", u"миллиардов"))
if tmp_val == 0:
return into
else:
raise ValueError("Cannot operand with numbers bigger than 10**11") | [
"\n Get sum in words\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param gender: gender of object (MALE, FEMALE or NEUTER)\n @type gender: C{int}\n\n @param items: variants of object in three forms:\n for one object, for two objects and for five objects\n @type items: 3-element C{sequence} of C{unicode} or\n just C{unicode} (three variants with delimeter ',')\n\n @return: in-words representation objects' amount\n @rtype: C{unicode}\n\n @raise ValueError: items isn't 3-element C{sequence} or C{unicode}\n @raise ValueError: amount bigger than 10**11\n @raise ValueError: amount is negative\n "
] |
Please provide a description of the function: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 | [
"\n Make in-words representation of single order\n\n @param into: in-words representation of lower orders\n @type into: C{unicode}\n\n @param tmp_val: temporary value without lower orders\n @type tmp_val: C{integer types}\n\n @param gender: gender (MALE, FEMALE or NEUTER)\n @type gender: C{int}\n\n @param items: variants of objects\n @type items: 3-element C{sequence} of C{unicode}\n\n @return: new into and tmp_val\n @rtype: C{tuple}\n\n @raise ValueError: tmp_val is negative\n "
] |
Please provide a description of the function:def detranslify(in_string):
try:
russian = six.text_type(in_string)
except UnicodeDecodeError:
raise ValueError("We expects if in_string is 8-bit string," + \
"then it consists only ASCII chars, but now it doesn't. " + \
"Use unicode in this case.")
for symb_out, symb_in in TRANSTABLE:
russian = russian.replace(symb_in, symb_out)
# TODO: выбрать правильный регистр для ь и ъ
# твердый и мягкий знак в dentranslify всегда будут в верхнем регистре
# потому что ` и ' не несут информацию о регистре
return russian | [
"\n Detranslify\n\n @param in_string: input string\n @type in_string: C{basestring}\n\n @return: detransliterated string\n @rtype: C{unicode}\n\n @raise ValueError: if in_string is C{str}, but it isn't ascii\n "
] |
Please provide a description of the function:def slugify(in_string):
try:
u_in_string = six.text_type(in_string).lower()
except UnicodeDecodeError:
raise ValueError("We expects when in_string is str type," + \
"it is an ascii, but now it isn't. Use unicode " + \
"in this case.")
# convert & to "and"
u_in_string = re.sub('\&\;|\&', ' and ', u_in_string)
# replace spaces by hyphen
u_in_string = re.sub('[-\s]+', '-', u_in_string)
# remove symbols that not in alphabet
u_in_string = u''.join([symb for symb in u_in_string if symb in ALPHABET])
# translify it
out_string = translify(u_in_string)
# remove non-alpha
return re.sub('[^\w\s-]', '', out_string).strip().lower() | [
"\n Prepare string for slug (i.e. URL or file/dir name)\n\n @param in_string: input string\n @type in_string: C{basestring}\n\n @return: slug-string\n @rtype: C{str}\n\n @raise ValueError: if in_string is C{str}, but it isn't ascii\n "
] |
Please provide a description of the function:def check_length(value, length):
_length = len(value)
if _length != length:
raise ValueError("length must be %d, not %d" % \
(length, _length)) | [
"\n Checks length of value\n\n @param value: value to check\n @type value: C{str}\n\n @param length: length checking for\n @type length: C{int}\n\n @return: None when check successful\n\n @raise ValueError: check failed\n "
] |
Please provide a description of the function: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)) | [
"\n Checks if variable is positive\n\n @param value: value to check\n @type value: C{integer types}, C{float} or C{Decimal}\n\n @return: None when check successful\n\n @raise ValueError: check failed\n "
] |
Please provide a description of the function:def split_values(ustring, sep=u','):
assert isinstance(ustring, six.text_type), "uvalue must be unicode, not %s" % type(ustring)
# unicode have special mark symbol 0xffff which cannot be used in a regular text,
# so we use it to mark a place where escaped column was
ustring_marked = ustring.replace(u'\,', u'\uffff')
items = tuple([i.strip().replace(u'\uffff', u',') for i in ustring_marked.split(sep)])
return items | [
"\n Splits unicode string with separator C{sep},\n but skips escaped separator.\n \n @param ustring: string to split\n @type ustring: C{unicode}\n \n @param sep: separator (default to u',')\n @type sep: C{unicode}\n \n @return: tuple of splitted elements\n "
] |
Please provide a description of the function:def translify(text):
try:
res = translit.translify(smart_text(text, encoding))
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
return res | [
"Translify russian text"
] |
Please provide a description of the function: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 | [
"Detranslify russian text"
] |
Please provide a description of the function: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()) | [
"\n Transform the records with the patch. May fail if the records do not\n match those expected in the patch.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.