code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if enable_json:
nested_dir = os.path.join(root_dir, 'plain')
if os.path.exists(root_dir) and not os.path.exists(nested_dir):
os.mkdir(nested_dir)
root_dir = nested_dir
return os.path.join(root_dir, '{}.log'.format(base_name)) | def get_plain_logname(base_name, root_dir, enable_json) | we nest all plain logs to prevent double log shipping | 2.175297 | 1.978691 | 1.099362 |
if not root_dir:
root_dir = os.environ.get('LOG_DIR')
assert root_dir, 'You should pass root_dir parameter or set env LOG_DIR'
JSON_FORMATTER = {
'()': json_formatter,
'env_vars': ['HOST_TYPE', 'TIPSI_CONFIG', 'TIPSI_BRANCH', 'CONTAINER_TYPE'],
}
default_loggers = {
... | def setup_logger(
base_name,
root_dir=None,
enable_json=True,
json_formatter='tipsi_tools.tipsi_logging.JSFormatter',
loggers={},
) | json_formatter:
'fan.contrib.django.span_formatter.SpanFormatter' - add INSTALLATION_ID, SPAN and etc | 2.477222 | 2.473353 | 1.001564 |
'''
Run command in shell, accepts command construction from list
Return (return_code, stdout, stderr)
stdout and stderr - as list of strings
'''
if isinstance(command, list):
command = ' '.join(command)
out = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subproce... | def run(command) | Run command in shell, accepts command construction from list
Return (return_code, stdout, stderr)
stdout and stderr - as list of strings | 4.227843 | 2.116412 | 1.997647 |
'''
Alias to run with check return code and stderr
'''
code, out, err = run(cmd)
# Because we're raising error, sometimes we want to process stdout/stderr after catching error
# so we're copying these outputs if required
if stdout is not None:
stdout[:] = out
if stderr is not No... | def succ(cmd, check_stderr=True, stdout=None, stderr=None) | Alias to run with check return code and stderr | 5.645957 | 4.867622 | 1.1599 |
'''
Wait for socket opened on remote side. Return False after timeout
'''
return wait_result(lambda: check_socket(host, port), True, timeout) | def wait_socket(host, port, timeout=120) | Wait for socket opened on remote side. Return False after timeout | 11.864413 | 4.574269 | 2.593729 |
'''
Format line system environment variables + defaults
'''
map = ChainMap(os.environ, defaults)
return line.format(**map) | def interpolate_sysenv(line, defaults={}) | Format line system environment variables + defaults | 13.933051 | 5.622132 | 2.478251 |
'''
Acts similar to bash 'source' or '.' commands.
'''
rex = re.compile('(?:export |declare -x )?(.*?)="(.*?)"')
out = call_out('source {} && export'.format(fname))
out = [x for x in out if 'export' in x or 'declare' in x]
out = {k: v for k, v in [rex.match(x).groups() for x in out if rex.ma... | def source(fname) | Acts similar to bash 'source' or '.' commands. | 4.715734 | 3.492059 | 1.350416 |
old_path = os.path.abspath('.')
os.chdir(dir_name)
try:
yield
os.chdir(old_path)
except Exception:
os.chdir(old_path)
raise | def cd(dir_name) | do something in other directory and return back after block ended | 2.239802 | 2.20061 | 1.017809 |
if identifier in self.tracker:
return False
else:
self.tracker.append(identifier)
self.tracker.pop(0)
return True | def _is_new(self, identifier) | Returns True if identifier hasn't been seen before. | 3.682947 | 2.810168 | 1.310579 |
response.body = "{}"
if self.handler(room_alias):
response.status = falcon.HTTP_200
self.api.create_room(alias=room_alias)
else:
response.status = falcon.HTTP_404 | def on_get(self, request, response, room_alias=None) | Called when a GET request is sent to /rooms/{room_alias} | 4.041831 | 3.771974 | 1.071543 |
response.body = "{}"
# Check whether repeat txn_id
if not self._is_new(txn_id):
response.status = falcon.HTTP_200
return
request.context["body"] = request.stream.read()
try:
events = json.loads(request.context["body"].decode("utf-8")... | def on_put(self, request, response, txn_id=None) | Responds to PUT request containing events. | 3.526846 | 3.363621 | 1.048527 |
response.body = "{}"
if self.handler(user_id):
response.status = falcon.HTTP_200
self.api.register(utils.mxid2localpart(user_id))
else:
response.status = falcon.HTTP_404 | def on_get(self, request, response, user_id=None) | Responds to GET request for users. | 4.841453 | 4.732378 | 1.023049 |
self.frame_parameters_changed_event.fire(profile_index, frame_parameters) | def set_frame_parameters(self, profile_index: int, frame_parameters) -> None | Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters. | 7.054879 | 3.855141 | 1.829993 |
'''Euler method integration. This function wraps the Euler class.
:param dfun:
derivative function of the system.
The differential system arranged as a series of first-order
equations: \\dot{X} = dfun(t, x)
:param xzero:
the initial condition of the s... | def euler(dfun, xzero, timerange, timestep) | Euler method integration. This function wraps the Euler class.
:param dfun:
derivative function of the system.
The differential system arranged as a series of first-order
equations: \\dot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
... | 6.454332 | 1.815398 | 3.555327 |
'''Verlet method integration. This function wraps the Verlet class.
:param dfun:
second derivative function of the system.
The differential system arranged as a series of second-order
equations: \ddot{X} = dfun(t, x)
:param xzero:
the initial conditio... | def verlet(dfun, xzero, vzero, timerange, timestep) | Verlet method integration. This function wraps the Verlet class.
:param dfun:
second derivative function of the system.
The differential system arranged as a series of second-order
equations: \ddot{X} = dfun(t, x)
:param xzero:
the initial condition of th... | 5.920912 | 1.59573 | 3.710472 |
'''Backward Euler method integration. This function wraps BackwardEuler.
:param dfun:
Derivative function of the system.
The differential system arranged as a series of first-order
equations: \dot{X} = dfun(t, x)
:param xzero:
The initial condition of... | def backwardeuler(dfun, xzero, timerange, timestep) | Backward Euler method integration. This function wraps BackwardEuler.
:param dfun:
Derivative function of the system.
The differential system arranged as a series of first-order
equations: \dot{X} = dfun(t, x)
:param xzero:
The initial condition of the sy... | 6.696428 | 1.431185 | 4.678941 |
# Duplicate request name?
if request.name in self.requests:
raise ValueError('redefinition of request "{0}"'.format(request.name))
self.requests[request.name] = request
# Add the request URLs
for method, url in request.urls:
# URL with argument... | def add_request(self, request) | Add a request object | 3.091459 | 3.094886 | 0.998893 |
assert isinstance(key, str), 'header key must be of type str'
assert isinstance(value, str), 'header value must be of type str'
self.headers[key] = value | def add_header(self, key, value) | Add a response header | 2.622419 | 2.477611 | 1.058447 |
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes'
response_headers = [('Content-Type', content_type)]
if headers:
response_headers.extend(headers)
self.start_response(status, response_headers)
return content | def response(self, status, content_type, content, headers=None) | Send an HTTP response | 2.848023 | 2.878876 | 0.989283 |
if text is None:
if isinstance(status, str):
text = status
else:
text = status.phrase
return self.response(status, content_type, [text.encode(encoding)], headers=headers) | def response_text(self, status, text=None, content_type='text/plain', encoding='utf-8', headers=None) | Send a plain-text response | 3.045052 | 3.219289 | 0.945877 |
encoder = JSONEncoder(
check_circular=self.app.validate_output,
allow_nan=False,
sort_keys=True,
indent=2 if self.app.pretty_output else None,
separators=(',', ': ') if self.app.pretty_output else (',', ':')
)
content = encode... | def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None) | Send a JSON response | 3.006555 | 3.0554 | 0.984014 |
environ = self.environ
if relative:
url = ''
else:
url = environ['wsgi.url_scheme'] + '://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
if ... | def reconstruct_url(self, path_info=None, query_string=None, relative=False) | Reconstructs the request URL using the algorithm provided by PEP3333 | 1.603381 | 1.621122 | 0.989057 |
# find optional value of ${XDG_CONFIG_DIRS}
config_dirs = environ.get('XDG_CONFIG_DIRS')
if config_dirs:
# PATH-like env vars operate in decreasing precedence, reverse this path set to mimic the end result
config_dirs = reversed(config_dirs.split(path.pathsep))
else:
# XDG s... | def read_xdg_config_dirs(name, extension) | Read from files found in XDG-specified system-wide configuration paths,
defaulting to ``/etc/xdg``. Depends on ``XDG_CONFIG_DIRS`` environment
variable.
:param name: application or configuration set name
:param extension: file extension to look for
:return: a `.Configuration` instance with values r... | 5.890924 | 6.186125 | 0.95228 |
# find optional value of ${XDG_CONFIG_HOME}
config_home = environ.get('XDG_CONFIG_HOME')
if not config_home:
# XDG spec: "If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used."
# see https://specifications.freedesktop.org/basedir-spec/latest/ar... | def read_xdg_config_home(name, extension) | Read from file found in XDG-specified configuration home directory,
expanding to ``${HOME}/.config/name.extension`` by default. Depends on
``XDG_CONFIG_HOME`` or ``HOME`` environment variables.
:param name: application or configuration set name
:param extension: file extension to look for
:return: ... | 4.367113 | 3.947121 | 1.106405 |
prefix = '{}_'.format(name)
prefix_len = len(prefix)
envvar_file = '{}_config_file'.format(name)
# create a new mapping from environment values starting with the prefix (but stripped of that prefix)
values = {var.lower()[prefix_len:]: value
for var, value in environ.items()
... | def read_envvars(name, extension) | Read environment variables starting with ``NAME_``, where subsequent
underscores are interpreted as namespaces. Underscores can be retained as
namespaces by doubling them up, e.g. ``NAME_SPA__CE_KEY`` would be
accessible in the resulting `.Configuration` as
``c.spa_ce.key``, where ``c`` is the `.Configu... | 5.102901 | 4.844666 | 1.053303 |
envvar_file = environ.get('{}_config_file'.format(name).upper())
if envvar_file:
# envvar set, load value as file
return loadf(envvar_file)
else:
# envvar not set, return an empty source
return NotConfigured | def read_envvar_file(name, extension) | Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigured` | 6.252763 | 5.963 | 1.048593 |
config_dir = environ.get(envvar)
if not config_dir:
return NotConfigured
# envvar is set, construct full file path, expanding user to allow the envvar containing a value like ~/config
config_path = path.join(path.expanduser(config_dir), '{name}.{extension}'.format(name=name, extension=exte... | def read_envvar_dir(envvar, name, extension) | Read values from a file located in a directory specified by a particular
environment file. ``read_envvar_dir('HOME', 'example', 'yaml')`` would
look for a file at ``/home/user/example.yaml``. When the environment
variable isn't set or the file does not exist, `NotConfigured` will be
returned.
:para... | 6.208852 | 6.005502 | 1.033861 |
for specifier in specifiers:
if isinstance(specifier, Locality):
# localities can carry multiple loaders, flatten this
yield from _LOADERS[specifier]
else:
# something not a locality, pass along verbatim
yield specifier | def loaders(*specifiers) | Generates loaders in the specified order.
Arguments can be `.Locality` instances, producing the loader(s) available
for that locality, `str` instances (used as file path templates) or
`callable`s. These can be mixed:
.. code-block:: python
# define a load order using predefined user-local loc... | 9.882464 | 10.972549 | 0.900653 |
return Configuration(*(yaml.safe_load(fp.read()) for fp in fps), missing=missing) | def load(*fps, missing=Missing.silent) | Read a `.Configuration` instance from file-like objects.
:param fps: file-like objects (supporting ``.read()``)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fps*
... | 6.817646 | 8.710391 | 0.782703 |
def readf(fname):
if default is _NoDefault or path.exists(fname):
# (attempt to) open fname if it exists OR if we're expected to raise an error on a missing file
with open(fname, 'r') as fp:
# default to empty dict, yaml.safe_load will return None for an empty do... | def loadf(*fnames, default=_NoDefault, missing=Missing.silent) | Read a `.Configuration` instance from named files.
:param fnames: name of the files to ``open()``
:param default: `dict` or `.Configuration` to use when a file does not
exist (default is to raise a `FileNotFoundError`)
:param missing: policy to be used when a configured key is missing, either
... | 5.18871 | 5.638822 | 0.920176 |
return Configuration(*(yaml.safe_load(string) for string in strings), missing=missing) | def loads(*strings, missing=Missing.silent) | Read a `.Configuration` instance from strings.
:param strings: configuration contents
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *strings*
:rtype: `.Configurati... | 6.156702 | 9.463601 | 0.650567 |
def generate_sources():
# argument order for product matters, for names "foo" and "bar":
# /etc/foo.yaml before /etc/bar.yaml, but both of them before ~/.foo.yaml and ~/.bar.yaml
for source, name in product(load_order, names):
if callable(source):
yield sourc... | def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension='yaml', missing=Missing.silent) | Read a `.Configuration` instance by name, trying to read from files in
increasing significance. The default load order is `.system`, `.user`,
`.application`, `.environment`.
Multiple names are combined with multiple loaders using names as the 'inner
loop / selector', loading ``/etc/name1.yaml`` and ``/... | 7.391185 | 6.875125 | 1.075062 |
while True:
# Try to set the lock
if self.redis.set(self.name, self.value, px=self.timeout, nx=True):
# It's ours until the timeout now
return True
# Lock is taken
if not block:
return False
# If... | def acquire(self, block=True) | Acquire lock. Blocks until acquired if `block` is `True`, otherwise returns `False` if the lock could not be acquired. | 5.93172 | 5.682924 | 1.043779 |
keys = [self.name]
args = [self.value, self.timeout]
# Redis docs claim EVALs are atomic, and I'm inclined to believe it.
if hasattr(self, '_refresh_script'):
return self._refresh_script(keys=keys, args=args) == 1
else:
keys_and_args = keys + args... | def refresh(self) | Refresh an existing lock to prevent it from expiring.
Uses a LUA (EVAL) script to ensure only a lock which we own is being overwritten.
Returns True if refresh succeeded, False if not. | 6.19613 | 4.870815 | 1.272093 |
log.info("Waiting for lock, currently held by %s", self.lock.who())
if self.lock.acquire():
log.info("Lock '%s' acquired", self.lockname)
# We got the lock, so we make sure the process is running and keep refreshing the lock - if we ever stop for any reason, for example... | def run(self) | Run process if nobody else is, otherwise wait until we're needed. Never returns. | 4.295542 | 4.118032 | 1.043105 |
if self.shell:
args = command
else:
args = shlex.split(command)
return subprocess.Popen(args, shell=self.shell) | def spawn(self, command) | Spawn process. | 3.214248 | 3.088295 | 1.040784 |
if self.process is None: # Process wasn't running yet, so nothing to worry about
return
if self.process.poll() is None:
log.info("Sending TERM to %d", self.process.pid)
self.process.terminate()
# Give process a second to terminate, if it didn't, ... | def cleanup(self) | Clean up, making sure the process is stopped before we pack up and go home. | 2.763571 | 2.55092 | 1.083362 |
if sig in [signal.SIGINT]:
log.warning("Ctrl-C pressed, shutting down...")
if sig in [signal.SIGTERM]:
log.warning("SIGTERM received, shutting down...")
self.cleanup()
sys.exit(-sig) | def handle_signal(self, sig, frame) | Handles signals, surprisingly. | 3.552024 | 3.47603 | 1.021863 |
if isinstance(data, dict):
validator = Validator(data, schema, defined_keys=defined_keys)
validator.validate()
else:
raise TypeError('expected data to be of type dict, but got: %s' % type(data)) | def validate(data, schema, defined_keys=False) | Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against | 2.975636 | 4.353984 | 0.683428 |
if hasattr(schema, '__validator_leaf__'):
return schema(data, tree)
if hasattr(schema, 'must_validate'): # cherry picking?
if not len(schema.must_validate):
reason = "must_validate attribute must not be empty"
raise SchemaError(data, tre... | def traverser(self, data, schema, tree) | Traverses the dictionary, recursing onto itself if
it sees appropriate key/value pairs that indicate that
there is a need for more validation in a branch below us. | 4.347873 | 4.315766 | 1.007439 |
key, value = data
schema_key, schema_value = schema
enforce(key, schema_key, tree, 'key') | def key_leaf(self, data, schema, tree) | The deepest validation we can make in any given circumstance for a key.
Does not recurse, it will just receive both values and the tree,
passing them on to the :fun:`enforce` function. | 7.232881 | 4.5055 | 1.605345 |
key, value = data
schema_key, schema_value = schema
if hasattr(schema_value, '__validator_leaf__'):
return schema_value(value, tree)
enforce(value, schema_value, tree, 'value') | def value_leaf(self, data, schema, tree) | The deepest validation we can make in any given circumstance for
a value. Does not recurse, it will just receive both values and the
tree, passing them on to the :fun:`enforce` function. | 6.487979 | 5.189141 | 1.250299 |
substitutes = dict()
hours, rem = divmod(tdelta.total_seconds(), 3600)
minutes, seconds = divmod(rem, 60)
substitutes["H"] = '{:02d}'.format(int(hours))
substitutes["M"] = '{:02d}'.format(int(minutes))
substitutes["S"] = '{:02d}'.format(int(seconds))
return DeltaTemplate(fmt).substitut... | def strfdelta(tdelta, fmt) | Used to format `datetime.timedelta` objects. Works just like `strftime`
>>> strfdelta(duration, '%H:%M:%S')
param tdelta: Time duration which is an instance of datetime.timedelta
param fmt: The pattern to format the timedelta with
rtype: str | 2.049349 | 2.396975 | 0.854973 |
try:
import pwd
_username = pwd.getpwuid(os.getuid())[0]
_userid = os.getuid()
_uname = os.uname()[1]
except ImportError:
import getpass
_username = getpass.getuser()
_userid = 0
import platform
_uname = platform.node()
return _us... | def get_user_information() | Returns the user's information
:rtype: (str, int, str) | 2.784456 | 2.757424 | 1.009804 |
client_id = os.getenv('AZURE_CLIENT_ID') if not client_id else client_id
client_secret = os.getenv('AZURE_CLIENT_SECRET') if not client_secret else client_secret
tenant_id = os.getenv('AZURE_TENANT_ID') if not tenant_id else tenant_id
credentials = ServicePrincipalCredentials(
... | def _login_azure_app_token(client_id=None, client_secret=None, tenant_id=None) | Authenticate APP using token credentials:
https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
:return: ~ServicePrincipalCredentials credentials | 1.497607 | 1.437853 | 1.041558 |
try:
container_group_name = 'compute' + str(int(time.time()))
result_file = self._create_container_group(resource_group_name=resource_group_name,
name=container_group_name,
... | def exec_container(self,
asset_url,
algorithm_url,
resource_group_name,
account_name,
account_key,
location,
share_name_input='compute',
... | Prepare a docker image that will run in the cloud, mounting the asset and executing the algorithm.
:param asset_url
:param algorithm_url
:param resource_group_name:
:param account_name:
:param account_key:
:param share_name_input:
:param share_name_output:
... | 2.619109 | 2.715833 | 0.964385 |
print("Listing container groups in resource group '{0}'...".format(resource_group_name))
container_groups = self.client.container_groups.list_by_resource_group(resource_group_name)
for container_group in container_groups:
print(" {0}".format(container_group.name)) | def list_container_groups(self, resource_group_name) | Lists the container groups in the specified resource group.
Arguments:
aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
-- An authenticated container instance management client.
resource_group {azure.mgmt.resource.resources.models.Resource... | 1.965054 | 2.021087 | 0.972276 |
Seq = namedtuple('Seq', ['id', 'description', 'seq'])
header, seq = '', []
for line in handle:
if line.startswith('>'):
if header:
yield Seq(header.split()[0], header, ''.join(seq))
header, seq = line[1:].strip(), []
else:
seq.append... | def fastalite(handle) | Return a sequence of namedtuple objects from a fasta file with
attributes (id, description, seq) given open file-like object
``handle`` | 2.144612 | 2.043362 | 1.049551 |
Seq = namedtuple('Seq', ['id', 'description', 'seq', 'qual'])
for i, chunk in enumerate(grouper(handle, 4, '')):
description, seq, plus, qual = chunk
seq, qual = seq.strip(), qual.strip()
checks = [description.startswith('@'), seq,
plus.startswith('+'), qual, len... | def fastqlite(handle) | Return a sequence of namedtuple objects from a fastq file with
attributes (id, description, seq, qual) given open file-like
object ``handle``. This parser assumes that lines corresponding to
sequences and quality scores are not wrapped. Raises
``ValueError`` for malformed records.
See https://doi.o... | 4.241227 | 3.322436 | 1.276541 |
for extra in super(Dimension, self).cauldron_extras:
yield extra
if self.formatters:
prop = self.id + '_raw'
else:
prop = self.id_prop
yield self.id + '_id', lambda row: getattr(row, prop) | def cauldron_extras(self) | Yield extra tuples containing a field name and a callable that takes
a row | 9.084946 | 7.916476 | 1.1476 |
if self.column_suffixes:
return self.column_suffixes
if len(self.columns) == 0:
return ()
elif len(self.columns) == 1:
if self.formatters:
return '_raw',
else:
return '',
elif len(self.columns) ==... | def make_column_suffixes(self) | Make sure we have the right column suffixes. These will be appended
to `id` when generating the query. | 3.383646 | 3.326314 | 1.017236 |
if cond is None:
return None
else:
if 'and' in cond:
conditions = [
parse_condition(
c, selectable, aggregated, default_aggregation
) for c in cond['and']
]
return and_(*conditions)
elif 'or' in... | def parse_condition(
cond, selectable, aggregated=False, default_aggregation='sum'
) | Create a SQLAlchemy clause from a condition. | 1.501192 | 1.48477 | 1.01106 |
# Crude tokenization
s = s.replace('+', ' PLUS ').replace('-', ' MINUS ') \
.replace('/', ' DIVIDE ').replace('*', ' MULTIPLY ')
words = [w for w in s.split(' ') if w]
return words | def tokenize(s) | Tokenize a string by splitting it by + and -
>>> tokenize('this + that')
['this', 'PLUS', 'that']
>>> tokenize('this+that')
['this', 'PLUS', 'that']
>>> tokenize('this+that-other')
['this', 'PLUS', 'that', 'MINUS', 'other'] | 3.893945 | 3.532859 | 1.102208 |
for col in columns:
if col.name == name or getattr(col, '_label', None) == name:
return col
return None | def _find_in_columncollection(columns, name) | Find a column in a column collection by name or _label | 3.557921 | 2.439815 | 1.458275 |
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
# Selectable is a table
if isinstance(selectable, DeclarativeMeta):
col = getattr(selectable, name, None)
if col is not None:
return col
col = _find_in_colu... | def find_column(selectable, name) | Find a column named `name` in selectable
:param selectable:
:param name:
:return: A column object | 3.022041 | 3.08479 | 0.979659 |
# An aggregation is a callable that takes a single field expression
# None will perform no aggregation
aggregation_lookup = {
'sum': func.sum,
'min': func.min,
'max': func.max,
'avg': func.avg,
'count': func.count,
'count_distinct': lambda fld: func.count... | def parse_field(fld, selectable, aggregated=True, default_aggregation='sum') | Parse a field object from yaml into a sqlalchemy expression | 2.449756 | 2.414704 | 1.014516 |
# TODO: This is deprecated in favor of
# ingredient_from_validated_dict
# Describe the required params for each kind of ingredient
# The key is the parameter name, the value is one of
# field: A parse_field with aggregation=False
# aggregated_field: A parse_field with aggregation=True
... | def ingredient_from_dict(ingr_dict, selectable) | Create an ingredient from an dictionary.
This object will be deserialized from yaml | 3.253293 | 3.238032 | 1.004713 |
aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']]
field = find_column(selectable, fld['value'])
for operator in fld.get('operators', []):
op = operator['operator']
other_field = parse_validated_field(operator['field'], selectable)
field = IngredientValidator... | def parse_validated_field(fld, selectable) | Converts a validated field to sqlalchemy. Field references are
looked up in selectable | 4.399554 | 4.500574 | 0.977554 |
validator = IngredientValidator(schema=ingr_dict['kind'])
if not validator.validate(ingr_dict):
raise Exception(validator.errors)
ingr_dict = validator.document
kind = ingr_dict.pop('kind', 'Metric')
IngredientClass = ingredient_class_for_name(kind)
if IngredientClass is None:
... | def ingredient_from_validated_dict(ingr_dict, selectable) | Create an ingredient from an dictionary.
This object will be deserialized from yaml | 3.607312 | 3.569806 | 1.010507 |
if hasattr(table, '__table__'):
table = table.__table__
config = introspect_table(table)
return Shelf.from_config(config, table) | def AutomaticShelf(table) | Given a SQLAlchemy Table, automatically generate a Shelf with metrics
and dimensions based on its schema. | 5.203131 | 5.053073 | 1.029696 |
d = {}
for c in table.columns:
if isinstance(c.type, String):
d[c.name] = {'kind': 'Dimension', 'field': c.name}
if isinstance(c.type, (Integer, Float)):
d[c.name] = {'kind': 'Metric', 'field': c.name}
return d | def introspect_table(table) | Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config. | 2.441985 | 2.355571 | 1.036685 |
if d is _POP_DEFAULT:
return self._ingredients.pop(k)
else:
return self._ingredients.pop(k, d) | def pop(self, k, d=_POP_DEFAULT) | Pop an ingredient off of this shelf. | 3.151748 | 2.121565 | 1.485577 |
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Dimension)
]) | def dimension_ids(self) | Return the Dimensions on this shelf in the order in which
they were used. | 12.585547 | 9.427392 | 1.334998 |
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Metric)
]) | def metric_ids(self) | Return the Metrics on this shelf in the order in which
they were used. | 13.459606 | 10.868804 | 1.23837 |
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Filter)
]) | def filter_ids(self) | Return the Metrics on this shelf in the order in which
they were used. | 15.862677 | 13.117059 | 1.209317 |
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
elif isinstance(selectable, basestring):
if '.' in selectable:
schema, tablename = selectable.split('.')
else:
schema, tabl... | def from_config(
cls,
obj,
selectable,
ingredient_constructor=ingredient_from_validated_dict,
metadata=None
) | Create a shelf using a dict shelf definition.
:param obj: A Python dictionary describing a Shelf.
:param selectable: A SQLAlchemy Table, a Recipe, a table name, or a
SQLAlchemy join to select from.
:param metadata: If `selectable` is passed as a table name, then in
order... | 3.189073 | 2.732819 | 1.166954 |
obj = safe_load(yaml_str)
return cls.from_config(
obj,
selectable,
ingredient_constructor=ingredient_from_dict,
**kwargs
) | def from_yaml(cls, yaml_str, selectable, **kwargs) | Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
:return: A shelf that contains the ingredients defined in yaml_str. | 6.015777 | 5.938958 | 1.012935 |
obj = safe_load(yaml_str)
return cls.from_config(obj, selectable, **kwargs) | def from_validated_yaml(cls, yaml_str, selectable, **kwargs) | Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
:return: A shelf that contains the ingredients defined in yaml_str. | 4.210105 | 6.056238 | 0.695168 |
if callable(constructor):
obj = constructor(obj, shelf=self)
if isinstance(obj, basestring):
set_descending = obj.startswith('-')
if set_descending:
obj = obj[1:]
if obj not in self:
raise BadRecipe("{} doesn't ex... | def find(self, obj, filter_to_class=Ingredient, constructor=None) | Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building Ingredients
from obj
:return: An Ingredient of subcl... | 2.620238 | 2.606583 | 1.005239 |
columns, group_bys, filters, havings = [], [], set(), set()
for ingredient in self.ingredients():
if ingredient.query_columns:
columns.extend(ingredient.query_columns)
if ingredient.group_by:
group_bys.extend(ingredient.group_by)
... | def brew_query_parts(self) | Make columns, group_bys, filters, havings | 2.06657 | 1.679316 | 1.230602 |
enchantedlist = []
if list:
sample_item = list[0]
# Extra fields to add to each row
# With extra callables
extra_fields, extra_callables = [], []
for ingredient in self.values():
if not isinstance(ingredient, (Dimensi... | def enchant(self, list, cache_context=None) | Add any calculated values to each row of a resultset generating a
new namedtuple
:param list: a list of row results
:param cache_context: optional extra context for caching
:return: a list with ingredient.cauldron_extras added for all
ingredients | 5.36429 | 4.407332 | 1.217129 |
if self.apply != value:
self.dirty = True
self.apply = value
return self.recipe | def apply_automatic_filters(self, value) | Toggles whether automatic filters are applied to a recipe. The
following will disable automatic filters for this recipe::
recipe.apply_automatic_filters(False) | 9.415154 | 10.924518 | 0.861837 |
assert isinstance(value, dict)
self._automatic_filters = value
self.dirty = True
return self.recipe | def automatic_filters(self, value) | Sets a dictionary of automatic filters to apply to this recipe.
If your recipe uses a shelf that has dimensions 'state' and 'gender'
you could filter the data to Men in California and New Hampshire with::
shelf = Shelf({
'state': Dimension(Census.state),
'gen... | 6.592283 | 13.748759 | 0.479482 |
if self._summarize_over is None:
return postquery_parts
assert self._summarize_over in self.recipe.dimension_ids
# Start with a subquery
subq = postquery_parts['query'].subquery(name='summarize')
summarize_over_dim = set((
self._summarize_over, ... | def modify_postquery_parts(self, postquery_parts) | Take a recipe that has dimensions
Resummarize it over one of the dimensions returning averages of the
metrics. | 3.008074 | 2.909866 | 1.03375 |
assert isinstance(value, bool)
if self._anonymize != value:
self.dirty = True
self._anonymize = value
# Builder pattern must return the recipe
return self.recipe | def anonymize(self, value) | Should this recipe be anonymized | 9.97548 | 7.358328 | 1.355672 |
for ingredient in self.recipe._cauldron.values():
if hasattr(ingredient.meta, 'anonymizer'):
anonymizer = ingredient.meta.anonymizer
# Build a FakerAnonymizer if we have a string
if isinstance(anonymizer, basestring):
# C... | def add_ingredients(self) | Put the anonymizers in the last position of formatters | 2.709042 | 2.445479 | 1.107776 |
assert isinstance(blend_recipe, Recipe)
self.blend_recipes.append(blend_recipe)
self.blend_types.append('inner')
self.blend_criteria.append((join_base, join_blend))
self.dirty = True
return self.recipe | def blend(self, blend_recipe, join_base, join_blend) | Blend a recipe into the base recipe.
This performs an inner join of the blend_recipe to the
base recipe's SQL. | 4.184544 | 3.915251 | 1.06878 |
if not self.blend_recipes:
return postquery_parts
for blend_recipe, blend_type, blend_criteria in \
zip(self.blend_recipes,
self.blend_types,
self.blend_criteria):
join_base, join_blend = blend_criteria
blend_subq... | def modify_postquery_parts(self, postquery_parts) | Make the comparison recipe a subquery that is left joined to the
base recipe using dimensions that are shared between the recipes.
Hoist the metric from the comparison recipe up to the base query
while adding the suffix. | 2.50181 | 2.393349 | 1.045318 |
assert isinstance(compare_recipe, Recipe)
assert isinstance(suffix, basestring)
self.compare_recipe.append(compare_recipe)
self.suffix.append(suffix)
self.dirty = True
return self.recipe | def compare(self, compare_recipe, suffix='_compare') | Adds a comparison recipe to a base recipe. | 3.158619 | 3.178998 | 0.99359 |
if not self.compare_recipe:
return postquery_parts
for compare_recipe, compare_suffix in zip(
self.compare_recipe, self.suffix
):
comparison_subq = compare_recipe.subquery()
# For all metrics in the comparison recipe
# Use th... | def modify_postquery_parts(self, postquery_parts) | Make the comparison recipe a subquery that is left joined to the
base recipe using dimensions that are shared between the recipes.
Hoist the metric from the comparison recipe up to the base query
while adding the suffix. | 4.287469 | 4.051871 | 1.058146 |
key = self.storage_client.storage_accounts.list_keys(self.resource_group_name, account).keys[0].value
if container:
bs = BlockBlobService(account_name=account, account_key=key)
container_list = []
for i in bs.list_blobs(container_or_share_name).items:
... | def list(self, container_or_share_name, container=None, account=None) | List the blobs/files inside a container/share_name.
Args:
container_or_share_name(str): Name of the container/share_name where we want to list the blobs/files.
container(bool): flag to know it you are listing files or blobs.
account(str): The name of the storage account. | 2.129939 | 2.023354 | 1.052678 |
parse_url = _parse_url(remote_file)
key = self.storage_client.storage_accounts.list_keys(self.resource_group_name, parse_url.account).keys[0].value
if parse_url.file_type == 'blob':
bs = BlockBlobService(account_name=parse_url.account, account_key=key)
sas_token... | def generate_url(self, remote_file) | Sign a remote file to distribute. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
remote_file(str): The blob that we want to sign. | 1.829513 | 1.792745 | 1.02051 |
if 'core.windows.net' not in remote_file:
self.logger.error("Source or destination must be a azure storage url (format "
"https://myaccount.blob.core.windows.net/mycontainer/myblob")
raise OsmosisError
parse_url = _parse_url(remote_file)
... | def delete(self, remote_file) | Delete file from the cloud. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
remote_file(str): The path of the file to be deleted.
Raises:
:exc:`~..OsmosisError`: if the file is not uploaded correctly. | 3.000781 | 2.67339 | 1.122463 |
if 'core.windows.net' not in source_path and 'core.windows.net' not in dest_path:
self.logger.error("Source or destination must be a azure storage url (format "
"https://myaccount.blob.core.windows.net/mycontainer/myblob")
raise OsmosisError
... | def copy(self, source_path, dest_path, account=None, group_name=None) | Copy file from a path to another path. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
source_path(str): The path of the file to be copied.
dest_path(str): The destination path where the file is going to be allocated.
Raises:
... | 1.904325 | 1.798157 | 1.059043 |
if isinstance(statement, sqlalchemy.orm.Query):
if dialect is None:
dialect = statement.session.get_bind().dialect
statement = statement.statement
# Generate a class that can handle encoding
if dialect:
DialectKlass = dialect.__class__
else:
DialectKlass... | def prettyprintable_sql(statement, dialect=None, reindent=True) | Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement. The function can also receive a
`sqlalchemy.orm.Query` object instead of statement.
WARNING: Should only be used for debugging. Inlining parameters is not
safe when handling user created... | 5.365372 | 5.172394 | 1.037309 |
try:
return self.format_lookup.get(v, v)
except TypeError:
# v is something we can't lookup (like a list)
return v | def _normalize_coerce_to_format_with_lookup(self, v) | Replace a format with a default | 5.560577 | 5.177032 | 1.074086 |
def tokenize(s):
# Crude tokenization
s = s.replace('+', ' + ').replace('-', ' - ') \
.replace('/', ' / ').replace('*', ' * ')
words = [w for w in s.split(' ') if w]
return words
if isinstance(v, _str_type):
... | def _normalize_coerce_to_field_dict(self, v) | coerces strings to a dict {'value': str} | 4.348073 | 4.187815 | 1.038268 |
if isinstance(
value, _int_types + (_str_type, float, date, datetime, bool)
):
return True | def _validate_type_scalar(self, value) | Is not a list or a dict | 10.373595 | 8.321564 | 1.246592 |
def subdict(d, keys):
new = {}
for k in keys:
if k in d:
new[k] = d[k]
return new
core_kwargs = subdict(obj, recipe_schema['schema'].keys())
core_kwargs = normalize_schema(recipe_schema, core_kwargs)
core_k... | def from_config(cls, shelf, obj, **kwargs) | Construct a Recipe from a plain Python dictionary.
Most of the directives only support named ingredients, specified as
strings, and looked up on the shelf. But filters can be specified as
objects.
Additionally, each RecipeExtension can extract and handle data from the
configura... | 3.510922 | 3.183777 | 1.102754 |
if shelf is None:
self._shelf = Shelf({})
elif isinstance(shelf, Shelf):
self._shelf = shelf
elif isinstance(shelf, dict):
self._shelf = Shelf(shelf)
else:
raise BadRecipe('shelf must be a dict or recipe.shelf.Shelf')
if s... | def shelf(self, shelf=None) | Defines a shelf to use for this recipe | 3.145984 | 2.983039 | 1.054624 |
for m in metrics:
self._cauldron.use(self._shelf.find(m, Metric))
self.dirty = True
return self | def metrics(self, *metrics) | Add a list of Metric ingredients to the query. These can either be
Metric objects or strings representing metrics on the shelf.
The Metric expression will be added to the query's select statement.
The metric value is a property of each row of the result.
:param metrics: Metrics to add ... | 16.323471 | 15.267656 | 1.069154 |
for d in dimensions:
self._cauldron.use(self._shelf.find(d, Dimension))
self.dirty = True
return self | def dimensions(self, *dimensions) | Add a list of Dimension ingredients to the query. These can either be
Dimension objects or strings representing dimensions on the shelf.
The Dimension expression will be added to the query's select statement
and to the group_by.
:param dimensions: Dimensions to add to the recipe. Dimen... | 17.643009 | 16.924868 | 1.042431 |
def filter_constructor(f, shelf=None):
if isinstance(f, BinaryExpression):
return Filter(f)
else:
return f
for f in filters:
self._cauldron.use(
self._shelf.find(
f, (Filter, Having), const... | def filters(self, *filters) | Add a list of Filter ingredients to the query. These can either be
Filter objects or strings representing filters on the service's shelf.
``.filters()`` are additive, calling .filters() more than once will add
to the list of filters being used by the recipe.
The Filter expression will b... | 8.813971 | 9.064137 | 0.9724 |
# Order bys shouldn't be added to the _cauldron
self._order_bys = []
for ingr in order_bys:
order_by = self._shelf.find(ingr, (Dimension, Metric))
self._order_bys.append(order_by)
self.dirty = True
return self | def order_by(self, *order_bys) | Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Order_bys to add to the recipe. Order_bys can
... | 8.266769 | 5.596025 | 1.477257 |
if self._limit != limit:
self.dirty = True
self._limit = limit
return self | def limit(self, limit) | Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int | 5.227784 | 6.613022 | 0.790529 |
if self._offset != offset:
self.dirty = True
self._offset = offset
return self | def offset(self, offset) | Offset a number of rows before returning rows from the database.
:param offset: The number of rows to offset in the recipe. 0 will
return from the first available row
:type offset: int | 4.822442 | 6.799496 | 0.709235 |
if self._is_postgres_engine is None:
is_postgres_engine = False
try:
dialect = self.session.bind.engine.name
if 'redshift' in dialect or 'postg' in dialect or 'pg' in \
dialect:
is_postgres_engine = True... | def _is_postgres(self) | Determine if the running engine is postgres | 3.166925 | 2.835436 | 1.116909 |
order_bys = OrderedSet()
if self._order_bys:
for ingredient in self._order_bys:
if isinstance(ingredient, Dimension):
# Reverse the ordering columns so that dimensions
# order by their label rather than their id
... | def _prepare_order_bys(self) | Build a set of order by columns | 3.723117 | 3.46806 | 1.073544 |
if len(self._cauldron.ingredients()) == 0:
raise BadRecipe('No ingredients have been added to this recipe')
if not self.dirty and self._query:
return self._query
# Step 1: Gather up global filters and user filters and
# apply them as if they had been add... | def query(self) | Generates a query using the ingredients supplied by the recipe.
:return: A SQLAlchemy query | 4.18103 | 4.094531 | 1.021125 |
if self._dirty:
return True
else:
for extension in self.recipe_extensions:
if extension.dirty:
return True
return False | def dirty(self) | The recipe is dirty if it is flagged dirty or any extensions are
flagged dirty | 5.679003 | 2.923841 | 1.942309 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.