code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
from ambry.orm.file import File
for f in self.list_records():
pref = preference if preference else f.record.preference
if pref == File.PREFERENCE.FILE:
self._bundle.logger.debug(' Cleaning objects for file {}'.format(f.path))
f.clean_... | def record_to_objects(self, preference=None) | Create objects from files, or merge the files into the objects. | 5.41336 | 4.779018 | 1.132735 |
from ambry.orm.file import File
raise NotImplementedError("Still uses obsolete file_info_map")
for file_const, (file_name, clz) in iteritems(file_info_map):
f = self.file(file_const)
pref = preference if preference else f.record.preference
if pref ... | def objects_to_record(self, preference=None) | Create file records from objects. | 10.444152 | 9.840877 | 1.061303 |
for const_name, c in file_classes.items():
if c.multiplicity == '1':
f = self.file(const_name)
if not f.record.unpacked_contents:
f.setcontent(f.default) | def set_defaults(self) | Add default content to any file record that is empty | 13.174022 | 9.769236 | 1.348521 |
print("Server running on {}:{}".format(host, port))
app_router = Router()
server = make_server(host, port, app_router)
server.serve_forever() | def run(host='127.0.0.1', port=8000) | Run web server. | 3.439716 | 3.361567 | 1.023248 |
if args is None:
args = sys.argv[1:]
o = Options()
try:
o.parseOptions(args)
except usage.UsageError, e:
raise SystemExit(str(e))
else:
return createSSLCertificate(o) | def main(args=None) | Create a private key and a certificate and write them to a file. | 3.609036 | 3.134259 | 1.15148 |
for p in self.__mapper__.attrs:
if p.key == 'oid':
continue
try:
setattr(self, p.key, getattr(f, p.key))
except AttributeError:
# The dict() method copies data property values into the main dict,
# an... | def update(self, f) | Copy another files properties into this one. | 9.911228 | 9.468252 | 1.046785 |
if self.__timeoutCall is not None and self.timeOut is not None:
self.__timeoutCall.reset(self.timeOut) | def resetTimeout(self) | Reset the timeout count down | 6.385375 | 5.981038 | 1.067603 |
prev = self.timeOut
self.timeOut = period
if self.__timeoutCall is not None:
if period is None:
self.__timeoutCall.cancel()
self.__timeoutCall = None
else:
self.__timeoutCall.reset(period)
elif period is no... | def setTimeout(self, period) | Change the timeout period
@type period: C{int} or C{NoneType}
@param period: The period, in seconds, to change the timeout to, or
C{None} to disable the timeout. | 3.01002 | 2.958025 | 1.017578 |
for file_name in os.listdir(os.path.join(self._project_dir, 'controllers')):
# ignore disabled controllers
if not file_name.startswith('_'):
module_name = file_name.split('.', 1)[0]
module_path = "controllers.{}".format(module_name)
... | def _load_controllers(self) | Load all controllers from folder 'controllers'.
Ignore files with leading underscore (for example: controllers/_blogs.py) | 2.614881 | 2.44669 | 1.068742 |
views_engine = get_config('rails.views.engine', 'jinja')
templates_dir = os.path.join(self._project_dir, "views", "templates")
self._view = View(views_engine, templates_dir) | def _init_view(self) | Initialize View with project settings. | 6.047844 | 5.320655 | 1.136673 |
try_actions = [
controller_name + '/' + action_name,
controller_name + '/not_found',
# call Index controller to catch all unhandled pages
'index/not_found'
]
# search first appropriate action handler
for path in try_actions:
... | def get_action_handler(self, controller_name, action_name) | Return action of controller as callable.
If requested controller isn't found - return 'not_found' action
of requested controller or Index controller. | 6.501932 | 5.133323 | 1.266613 |
'''
Start a server::
./manage.py flup:start [--daemonize]
'''
if daemonize:
safe_makedirs(self.logfile, self.pidfile)
flup_fastcgi(self.app, bind=self.bind, pidfile=self.pidfile,
logfile=self.logfile, daemonize=daemonize,
... | def command_start(self, daemonize=False) | Start a server::
./manage.py flup:start [--daemonize] | 5.577801 | 3.842799 | 1.451494 |
'''
Stop a server::
./manage.py flup:stop
'''
if self.pidfile:
if not os.path.exists(self.pidfile):
sys.exit("Pidfile {!r} doesn't exist".format(self.pidfile))
with open(self.pidfile) as pidfile:
pid = int(pidfile.read(... | def command_stop(self) | Stop a server::
./manage.py flup:stop | 3.902197 | 3.247249 | 1.201693 |
new_query = None
if asql_query.strip().lower().startswith('index'):
logger.debug(
'_preprocess_index: create index query found.\n asql query: {}'
.format(asql_query))
index = parse_index(asql_query)
partition = library.partition(index.source)
t... | def _preprocess_sqlite_index(asql_query, library, backend, connection) | Creates materialized view for each indexed partition found in the query.
Args:
asql_query (str): asql query
library (ambry.Library):
backend (SQLiteBackend):
connection (apsw.Connection):
Returns:
str: converted asql if it contains index query. If not, returns asql_quer... | 3.548001 | 3.346682 | 1.060155 |
virtual_table = partition.vid
table = partition.vid if not table_name else table_name
if self._relation_exists(connection, table):
if logger:
logger.debug("Skipping '{}'; already installed".format(table))
return
else:
if logg... | def install(self, connection, partition, table_name = None, index_columns=None, materialize=False,
logger = None) | Creates virtual table or read-only table for gion.
Args:
ref (str): id, vid, name or versioned name of the partition.
materialize (boolean): if True, create read-only table. If False create virtual table.
Returns:
str: name of the created table. | 3.427903 | 3.428001 | 0.999971 |
import hashlib
query_tmpl = '''
CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({columns});
'''
if not isinstance(columns,(list,tuple)):
columns = [columns]
col_list = ','.join('"{}"'.format(col) for col in columns)
col_hash ... | def index(self, connection, partition, columns) | Create an index on the columns.
Args:
connection (apsw.Connection): connection to sqlite database who stores mpr table or view.
partition (orm.Partition):
columns (list of str): | 3.36784 | 3.223546 | 1.044763 |
if getattr(self, '_connection', None):
logger.debug('Closing sqlite connection.')
self._connection.close()
self._connection = None | def close(self) | Closes connection to sqlite database. | 4.615607 | 3.341021 | 1.381496 |
logger.debug(
'Looking for view of the table.\n table: {}'.format(table.vid))
view = self.get_view_name(table)
view_exists = self._relation_exists(connection, view)
if view_exists:
logger.debug(
'View of the table exists.\n table: {}... | def _get_mpr_view(self, connection, table) | Finds and returns view name in the sqlite db represented by given connection.
Args:
connection: connection to sqlite db where to look for partition table.
table (orm.Table):
Raises:
MissingViewError: if database does not have partition table.
Returns:
... | 4.506684 | 3.904438 | 1.154247 |
# TODO: This is the first candidate for optimization. Add field to partition
# with table name and update it while table creation.
# Optimized version.
#
# return partition.mpr_table or raise exception
# Not optimized version.
#
# first check eit... | def _get_mpr_table(self, connection, partition) | Returns name of the sqlite table who stores mpr data.
Args:
connection (apsw.Connection): connection to sqlite database who stores mpr data.
partition (orm.Partition):
Returns:
str:
Raises:
MissingTableError: if partition table not found in the ... | 4.63053 | 4.257735 | 1.087557 |
query = 'SELECT 1 FROM sqlite_master WHERE (type=\'table\' OR type=\'view\') AND name=?;'
cursor = connection.cursor()
cursor.execute(query, [relation])
result = cursor.fetchall()
return result == [(1,)] | def _relation_exists(self, connection, relation) | Returns True if relation (table or view) exists in the sqlite db. Otherwise returns False.
Args:
connection (apsw.Connection): connection to sqlite database who stores mpr data.
partition (orm.Partition):
Returns:
boolean: True if relation exists, False otherwise. | 2.856853 | 2.770811 | 1.031053 |
TYPE_MAP = {
'int': 'INTEGER',
'float': 'REAL',
six.binary_type.__name__: 'TEXT',
six.text_type.__name__: 'TEXT',
'date': 'DATE',
'datetime': 'TIMESTAMP WITHOUT TIME ZONE'
}
columns_types = []
if not include... | def _get_create_query(partition, tablename, include=None) | Creates and returns `CREATE TABLE ...` sql statement for given mprows.
Args:
partition (orm.Partition):
tablename (str): name of the table in the return create query.
include (list of str, optional): list of columns to include to query.
Returns:
str: cre... | 2.665462 | 2.843378 | 0.937428 |
if getattr(self, '_connection', None):
logger.debug('Connection to sqlite db already exists. Using existing one.')
else:
dsn = self._dsn
if dsn == 'sqlite://':
dsn = ':memory:'
else:
dsn = dsn.replace('sqlite:///', ... | def _get_connection(self) | Returns connection to sqlite db.
Returns:
connection to the sqlite db who stores mpr data. | 4.312551 | 4.19754 | 1.027399 |
logger.debug('Creating virtual table for partition.\n partition: {}'.format(partition.name))
sqlite_med.add_partition(connection, partition.datafile, partition.vid+'_vt') | def _add_partition(self, connection, partition) | Creates sqlite virtual table for mpr file of the given partition.
Args:
connection: connection to the sqlite db who stores mpr data.
partition (orm.Partition): | 20.163332 | 16.463617 | 1.224721 |
cursor = connection.cursor()
try:
cursor.execute(query)
except Exception as e:
from ambry.mprlib.exceptions import BadSQLError
raise BadSQLError("Failed to execute query: {}; {}".format(query, e))
if fetch:
return cursor.fetchall... | def _execute(self, connection, query, fetch=True) | Executes given query using given connection.
Args:
connection (apsw.Connection): connection to the sqlite db who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch.
Returns:
... | 4.285682 | 4.70784 | 0.910329 |
if self.logged:
self.server.stats.connectionClosed()
self.logged = False | def _log_disconnect(self) | Decrement connection count | 11.518306 | 9.708758 | 1.186383 |
self.set_header('Cache-Control', 'max-age=%d, public' % self.CACHE_TIME)
now = datetime.datetime.now()
expires = now + datetime.timedelta(seconds=self.CACHE_TIME)
self.set_header('Expires', expires.strftime('%a, %d %b %Y %H:%M:%S'))
self.set_header('access-control-max-... | def enable_cache(self) | Enable client-side caching for the current request | 2.218825 | 2.095948 | 1.058626 |
data = list_milestones_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | def list_milestones(page_size=200, page_index=0, q="", sort="") | List all ProductMilestones | 3.981149 | 4.321221 | 0.921302 |
data = update_milestone_raw(id, **kwargs)
if data:
return utils.format_json(data) | def update_milestone(id, **kwargs) | Update a ProductMilestone | 5.423538 | 6.437943 | 0.842433 |
data = close_milestone_raw(id, **kwargs)
if data:
return utils.format_json(data) | def close_milestone(id, **kwargs) | Close a milestone. This triggers its release process.
The user can optionally specify the release-date, otherwise today's date is
used.
If the wait parameter is specified and set to True, upon closing the milestone,
we'll periodically check that the release being processed is done.
Required:
... | 5.527041 | 11.844541 | 0.466632 |
app.config.setdefault('FLASK_AUTH_ALL', False)
app.config.setdefault('FLASK_AUTH_REALM', 'Login Required')
# Default set to bad file to trigger IOError
app.config.setdefault('FLASK_HTPASSWD_PATH', '/^^^/^^^')
# Load up user database
try:
self.load_us... | def init_app(self, app) | Find and configure the user database from specified file | 5.304246 | 5.228645 | 1.014459 |
valid = self.users.check_password(
username, password
)
if not valid:
log.warning('Invalid login from %s', username)
valid = False
return (
valid,
username
) | def check_basic_auth(self, username, password) | This function is called to check if a username /
password combination is valid via the htpasswd file. | 5.901914 | 5.737123 | 1.028724 |
return hashlib.sha256(
self.users.get_hash(username)
).hexdigest() | def get_hashhash(self, username) | Generate a digest of the htpasswd hash | 5.953421 | 5.413342 | 1.099768 |
serializer = self.get_signature()
return serializer.dumps(
{
'username': username,
'hashhash': self.get_hashhash(username)
}
).decode('UTF-8') | def generate_token(self, username) | assumes user exists in htpasswd file.
Return the token for the given user by signing a token of
the username and a hash of the htpasswd string. | 5.507618 | 5.614064 | 0.981039 |
serializer = self.get_signature()
try:
data = serializer.loads(token)
except BadSignature:
log.warning('Received bad token signature')
return False, None
if data['username'] not in self.users.users():
log.warning(
... | def check_token_auth(self, token) | Check to see who this is and if their token gets
them into the system. | 4.112164 | 4.057708 | 1.01342 |
basic_auth = request.authorization
is_valid = False
user = None
if basic_auth:
is_valid, user = self.check_basic_auth(
basic_auth.username, basic_auth.password
)
else: # Try token auth
token = request.headers.get('Auth... | def authenticate(self) | Authenticate user by any means and return either true or false.
Args:
Returns:
tuple (is_valid, username): True is valid user, False if not | 3.982483 | 4.111612 | 0.968594 |
@wraps(func)
def decorated(*args, **kwargs):
is_valid, user = self.authenticate()
if not is_valid:
return self.auth_failed()
kwargs['user'] = user
return func(*args, **kwargs)
return decorated | def required(self, func) | Decorator function with basic and token authentication handler | 2.847248 | 2.704806 | 1.052663 |
d = dict([(k, getattr(self, k)) for k, _, _ in self.name_parts])
if with_name:
d['name'] = self.name
try:
d['vname'] = self.vname
except ValueError:
pass
return self.clear_dict(d) | def _dict(self, with_name=True) | Returns the identity as a dict.
values that are empty are removed | 4.490992 | 4.799217 | 0.935776 |
# Need to do this to ensure the function produces the
# bundle path when called from subclasses
names = [k for k, _, _ in self._name_parts]
parts = [self.source]
if self.bspace:
parts.append(self.bspace)
parts.append(
self._path_join(na... | def source_path(self) | The name in a form suitable for use in a filesystem.
Excludes the revision | 9.126688 | 9.289515 | 0.982472 |
try:
return self.path
except TypeError:
raise TypeError("self.path is invalild: '{}', '{}'".format(str(self.path), type(self.path))) | def cache_key(self) | The name in a form suitable for use as a cache-key | 8.442489 | 7.445319 | 1.133932 |
c = self.clone()
c.version = self._parse_version(self.version)
return c | def ver(self, revision) | Clone and change the version. | 11.401337 | 7.190576 | 1.585594 |
return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items()))) | def as_partition(self, **kwargs) | Return a PartitionName based on this name. | 10.462478 | 5.496226 | 1.903575 |
return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items()))) | def promote(self, name) | Promote to a PartitionName by combining with a bundle Name. | 12.568042 | 7.183114 | 1.749665 |
# Need to do this to ensure the function produces the
# bundle path when called from subclasses
names = [k for k, _, _ in Name._name_parts]
return os.path.join(self.source,
self._path_join(names=names, excludes=['source', 'format'], sep=self.NAME_PA... | def path(self) | The path of the bundle source.
Includes the revision. | 16.184343 | 14.45348 | 1.119754 |
try:
return os.path.join(*(self._local_parts()))
except TypeError as e:
raise TypeError(
"Path failed for partition {} : {}".format(
self.name,
e.message)) | def sub_path(self) | The path of the partition source, excluding the bundle path parts.
Includes the revision. | 9.533198 | 8.066401 | 1.18184 |
d = self._dict(with_name=False)
d = {k: d.get(k) for k, _, _ in PartialPartitionName._name_parts if d.get(k, False)}
if 'format' in d and d['format'] == Name.DEFAULT_FORMAT:
del d['format']
d['name'] = self.name
return d | def partital_dict(self, with_name=True) | Returns the name as a dict, but with only the items that are
particular to a PartitionName. | 6.071605 | 4.989128 | 1.216967 |
d = dict([(k, getattr(self, k)) for k, _, _ in self.name_parts])
return self.clear_dict(d) | def _dict(self, with_name=True) | Returns the identity as a dict.
values that are empty are removed | 9.196687 | 10.253842 | 0.896902 |
n = self.clone()
for k, _, _ in n.name_parts:
if getattr(n, k) == n.NONE:
delattr(n, k)
n.use_clear_dict = False
return n | def with_none(self) | Convert the NameQuery.NONE to None. This is needed because on the
kwargs list, a None value means the field is not specified, which
equates to ANY. The _find_orm() routine, however, is easier to write if
the NONE value is actually None.
Returns a clone of the origin, with NONE converted... | 9.90566 | 7.623314 | 1.29939 |
default = PartialMixin.ANY
np = ([(k, default, True)
for k, _, _ in super(NameQuery, self).name_parts]
+
[(k, default, True)
for k, _, _ in Name._generated_names]
)
return np | def name_parts(self) | Works with PartialNameMixin.clear_dict to set NONE and ANY
values. | 13.688155 | 10.862346 | 1.260147 |
default = PartialMixin.ANY
return ([(k, default, True)
for k, _, _ in PartitionName._name_parts]
+
[(k, default, True)
for k, _, _ in Name._generated_names]
) | def name_parts(self) | Works with PartialNameMixin.clear_dict to set NONE and ANY
values. | 15.40749 | 11.760271 | 1.31013 |
return None
if not on_str:
raise NotObjectNumberError("Got null input")
if not isinstance(on_str, string_types):
raise NotObjectNumberError("Must be a string. Got a {} ".format(type(on_str)))
# if isinstance(on_str, unicode):
# dataset = on_str.... | def parse(cls, on_str, force_type=None): # @ReservedAssignment
on_str_orig = on_str
if on_str is None | Parse a string into one of the object number classes. | 2.275823 | 2.220975 | 1.024695 |
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
arr.append(alphabet[rem])
arr... | def base62_encode(cls, num) | Encode a number in Base X.
`num`: The number to encode
`alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479 | 1.898888 | 1.825167 | 1.040392 |
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
base = len(alphabet)
strlen = len(string)
num = 0
idx = 0
for char in string:
power = (strlen - (idx + 1))
try:
num += alphabet.index(char) * (b... | def base62_decode(cls, string) | Decode a Base X encoded string into the number.
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479 | 2.424536 | 2.307896 | 1.05054 |
if not isinstance(v, ObjectNumber):
v = ObjectNumber.parse(v)
return v.rev(v.revision+1) | def increment(cls, v) | Increment the version number of an object number of object number string | 11.117471 | 6.834353 | 1.626704 |
on = copy(self)
on.revision = i
return on | def rev(self, i) | Return a clone with a different revision. | 18.149998 | 6.707524 | 2.705916 |
from math import log
# Use the ln(N)/ln(base) trick to find the right number of hext digits
# to use
hex_digits = int(
round(log(62 ** TopNumber.DLEN.DATASET_CLASSES[assignment_class]) / log(16), 0))
i = int(h[:hex_digits], 16)
return TopNumber(... | def from_hex(cls, h, space, assignment_class='self') | Produce a TopNumber, with a length to match the given assignment
class, based on an input hex string.
This can be used to create TopNumbers from a hash of a string. | 13.475275 | 11.553004 | 1.166387 |
import hashlib
hs = hashlib.sha1(s).hexdigest()
return cls.from_hex(hs, space) | def from_string(cls, s, space) | Produce a TopNumber by hashing a string. | 5.624971 | 4.902246 | 1.147427 |
# from collections import namedtuple
s = str(o)
if o is None:
raise ValueError("Input cannot be None")
class IdentityParts(object):
on = None
name = None
isa = None
name = None
vname = None
sn... | def classify(cls, o) | Break an Identity name into parts, or describe the type of other
forms.
Break a name or object number into parts and classify them. Returns a named tuple
that indicates which parts of input string are name components, object number and
version number. Does not completely parse the name ... | 3.198824 | 3.110626 | 1.028354 |
# from collections import OrderedDict
if not md5:
if not file:
raise ValueError('Must specify either file or md5')
md5 = md5_for_file(file)
size = os.stat(file).st_size
else:
size = None
return {
'id'... | def to_meta(self, md5=None, file=None) | Return a dictionary of metadata, for use in the Remote api. | 4.786717 | 4.526221 | 1.057553 |
INCLUDE_KEYS = ['name', 'vname', 'vid']
d = {k: v for k, v in iteritems(self.dict) if k in INCLUDE_KEYS}
d['fqname'] = self.fqname
return d | def names_dict(self) | A dictionary with only the generated names, name, vname and fqname. | 5.866745 | 4.060405 | 1.444867 |
SKIP_KEYS = ['name','vname','fqname','vid','cache_key']
return {k: v for k, v in iteritems(self.dict) if k not in SKIP_KEYS} | def ident_dict(self) | A dictionary with only the items required to specify the identy,
excluding the generated names, name, vname and fqname. | 9.478371 | 5.236318 | 1.810121 |
assert isinstance(self._name, Name), "Wrong type: {}".format(type(self._name))
assert isinstance(self._on, DatasetNumber), "Wrong type: {}".format(type(self._on))
name = self._name.as_partition(**kwargs)
on = self._on.as_partition(partition)
return PartitionIdentity(n... | def as_partition(self, partition=0, **kwargs) | Return a new PartitionIdentity based on this Identity.
:param partition: Integer partition number for PartitionObjectNumber
:param kwargs: | 3.890869 | 3.537242 | 1.099973 |
if not self.partitions:
self.partitions = {}
self.partitions[p.vid] = p | def add_partition(self, p) | Add a partition identity as a child of a dataset identity. | 5.066229 | 5.781796 | 0.876238 |
if not self.files:
self.files = set()
self.files.add(f)
self.locations.set(f.type_) | def add_file(self, f) | Add a partition identity as a child of a dataset identity. | 7.967487 | 7.903629 | 1.00808 |
if not self.partitions:
return None
if len(self.partitions) > 1:
raise ValueError(
"Can't use this method when there is more than one partition")
return list(self.partitions.values())[0] | def partition(self) | Convenience function for accessing the first partition in the
partitions list, when there is only one. | 3.838473 | 2.966283 | 1.294035 |
d = self.dict
d['revision'] = rev
return self.from_dict(d) | def rev(self, rev) | Return a new identity with the given revision | 6.531964 | 5.033854 | 1.297607 |
d = OrderedDict()
d['vid'] = self.vid
d['sname'] = self.sname
d['vname'] = self.vname
return d | def _info(self) | Returns an OrderedDict of information, for human display. | 4.876294 | 3.702707 | 1.316954 |
name = PartitionIdentity._name_class(**d)
if 'id' in d and 'revision' in d:
# The vid should be constructed from the id and the revision
on = (ObjectNumber.parse(d['id']).rev(d['revision']))
elif 'vid' in d:
on = ObjectNumber.parse(d['vid'])
... | def from_dict(cls, d) | Like Identity.from_dict, but will cast the class type based on the
format. i.e. if the format is hdf, return an HdfPartitionIdentity.
:param d:
:return: | 6.508568 | 6.197998 | 1.050108 |
on = self.on.dataset
on.revision = self.on.revision
name = Name(**self.name.dict)
return Identity(name, on) | def as_dataset(self) | Convert this identity to the identity of the corresponding
dataset. | 19.955465 | 12.9828 | 1.53707 |
if self.next_time and time.time() < self.next_time:
time.sleep(self.next_time - time.time()) | def sleep(self) | Wait for the sleep time of the last response, to avoid being rate
limited. | 3.79354 | 3.230313 | 1.174357 |
from requests.exceptions import ConnectionError
all_remote_names = [ r.short_name for r in l.remotes ]
if args.all:
remotes = all_remote_names
else:
remotes = args.refs
prt("Sync with {} remotes or bundles ".format(len(remotes)))
if not remotes:
return
for r... | def root_sync(args, l, config) | Sync with the remote. For more options, use library sync | 4.865726 | 4.772593 | 1.019514 |
from ambry.dbexceptions import LoggedException
b = args[0] # The 'self' argument
try:
return f(*args, **kwargs)
except Exception as e:
raise
try:
b.set_error_state()
b.commit()
except Exception as e2:
b.log('Failed to set bundle... | def _CaptureException(f, *args, **kwargs) | Decorator implementation for capturing exceptions. | 5.442523 | 5.26351 | 1.03401 |
assert isinstance(source_url, string_types) or source_url is None or source_url is False
assert isinstance(build_url, string_types) or build_url is False
if source_url:
self._source_url = source_url
self.dataset.config.library.source.url = self._source_url
... | def set_file_system(self, source_url=False, build_url=False) | Set the source file filesystem and/or build file system | 2.045057 | 2.025761 | 1.009525 |
self._source_url = None
self.dataset.config.library.source.url = None
self._source_fs = None
self._build_url = None
self.dataset.config.library.build.url = None
self._build_fs = None
self.dataset.commit() | def clear_file_systems(self) | Remove references to build and source file systems, reverting to the defaults | 5.036262 | 3.774269 | 1.334367 |
self.import_lib()
self.load_requirements()
try:
self.commit() # To ensure the rollback() doesn't clear out anything important
bsf = self.build_source_files.file(File.BSFILE.BUILD)
except Exception as e:
self.log('Error trying to create a bun... | def cast_to_subclass(self) | Load the bundle file from the database to get the derived bundle class,
then return a new bundle built on that class
:return: | 10.193628 | 9.495555 | 1.073516 |
for module_name, pip_name in iteritems(self.metadata.requirements):
extant = self.dataset.config.requirements[module_name].url
force = (extant and extant != pip_name)
self._library.install_packages(module_name, pip_name, force=force)
self.dataset.conf... | def load_requirements(self) | If there are python library requirements set, append the python dir
to the path. | 5.934834 | 5.414069 | 1.096187 |
from ambry.orm.exc import NotFoundError
from ambry.dbexceptions import ConfigurationError
source = self.source(source_name)
ref = source.url
if not ref:
raise ValueError("Got an empty ref for source '{}' ".format(source.name))
try:
try... | def dep(self, source_name) | Return a bundle dependency from the sources list
:param source_name: Source name. The URL field must be a bundle or partition reference
:return: | 5.533444 | 5.147879 | 1.074898 |
# Return the documentation as a scalar term, which has .text() and .html methods to do
# metadata substitution using Jinja
s = ''
rc = self.build_source_files.documentation.record_content
if rc:
s += rc
for k, v in self.metadata.documentation.it... | def documentation(self) | Return the documentation, from the documentation.md file, with template substitutions | 14.083824 | 11.943603 | 1.179194 |
if not self._progress:
# If won't be building, only use one connection
new_connection = False if self._library.read_only else True
self._progress = ProcessLogger(self.dataset, self.logger, new_connection=new_connection)
return self._progress | def progress(self) | Returned a cached ProcessLogger to record build progress | 12.493618 | 8.084662 | 1.545348 |
from ambry.orm.exc import NotFoundError
from sqlalchemy.orm.exc import NoResultFound
if not ref and not kwargs:
return None
if ref:
for p in self.partitions:
if ref == p.name or ref == p.vname or ref == p.vid or ref == p.id:
... | def partition(self, ref=None, **kwargs) | Return a partition in this bundle for a vid reference or name parts | 4.057179 | 3.666143 | 1.106662 |
from ambry.orm import Partition
p = self.session.query(Partition).filter(Partition.vid == str(ref)).first()
if p:
return self.wrap_partition(p)
else:
return None | def partition_by_vid(self, ref) | A much faster way to get partitions, by vid only | 4.668059 | 4.231347 | 1.103209 |
from ambry.orm import Table
from sqlalchemy.orm import lazyload
return (self.dataset.session.query(Table)
.filter(Table.d_vid == self.dataset.vid)
.options(lazyload('*'))
.all()) | def tables(self) | Return a iterator of tables in this bundle
:return: | 5.115944 | 5.177173 | 0.988173 |
return self.dataset.new_table(name=name, add_id=add_id, **kwargs) | def new_table(self, name, add_id=True, **kwargs) | Create a new table, if it does not exist, or update an existing table if it does
:param name: Table name
:param add_id: If True, add an id field ( default is True )
:param kwargs: Other options passed to table object
:return: | 3.728716 | 4.048078 | 0.921108 |
def set_bundle(s):
s._bundle = self
return s
return list(set_bundle(s) for s in self.dataset.sources) | def sources(self) | Iterate over downloadable sources | 10.421556 | 9.2597 | 1.125475 |
assert sources is None or tables is None
if not sources:
if tables:
sources = list(s for s in self.sources if s.dest_table_name in tables)
else:
sources = self.sources
elif not isinstance(sources, (list, tuple)):
sou... | def _resolve_sources(self, sources, tables, stage=None, predicate=None) | Determine what sources to run from an input of sources and tables
:param sources: A collection of source objects, source names, or source vids
:param tables: A collection of table names
:param stage: If not None, select only sources from this stage
:param predicate: If not none, a call... | 2.507675 | 2.489825 | 1.007169 |
def set_bundle(s):
s._bundle = self
return s
return list(set_bundle(s) for s in self.dataset.sources if not s.is_downloadable) | def refs(self) | Iterate over downloadable sources -- references and templates | 9.904475 | 6.964922 | 1.422051 |
from .files import BuildSourceFileAccessor
return BuildSourceFileAccessor(self, self.dataset, self.source_fs) | def build_source_files(self) | Return acessors to the build files | 22.790815 | 13.982716 | 1.629928 |
base_path = os.path.dirname(self.identity.cache_key)
if not self.build_fs.exists(base_path):
self.build_fs.makedir(base_path, recursive=True, allow_recreate=True)
return self.build_fs.opendir(base_path) | def build_partition_fs(self) | Return a pyfilesystem subdirectory for the build directory for the bundle. This the sub-directory
of the build FS that holds the compiled SQLite file and the partition data files | 3.610533 | 3.186205 | 1.133177 |
base_path = 'ingest'
if not self.build_fs.exists(base_path):
self.build_fs.makedir(base_path, recursive=True, allow_recreate=True)
return self.build_fs.opendir(base_path) | def build_ingest_fs(self) | Return a pyfilesystem subdirectory for the ingested source files | 3.180583 | 2.631629 | 1.208599 |
search = []
assert phase is not None
# Create a search list of names for getting a pipline from the metadata
if source and source.source_table_name:
search.append(phase + '-' + source.source_table_name)
if source and source.dest_table_name:
sea... | def phase_search_names(self, source, phase) | Search the bundle.yaml metadata file for pipeline configurations. Looks for:
- <phase>-<source_table>
- <phase>-<dest_table>
- <phase>-<source_name> | 4.285433 | 3.568624 | 1.200864 |
if not self._logger:
ident = self.identity
if self.multi:
template = '%(levelname)s %(process)d {} %(message)s'.format(ident.vid)
else:
template = '%(levelname)s {} %(message)s'.format(ident.vid)
try:
fi... | def logger(self) | The bundle logger. | 4.390905 | 4.267136 | 1.029005 |
with self.build_fs.open(self.log_file, 'a+') as f:
f.write(unicode(message + '\n')) | def log_to_file(self, message) | Write a log message only to the file | 6.780345 | 6.483608 | 1.045767 |
if set_error_state:
if message not in self._errors:
self._errors.append(message)
self.set_error_state()
self.logger.error(message) | def error(self, message, set_error_state=False) | Log an error messsage.
:param message: Log message. | 3.147426 | 3.699011 | 0.850883 |
self.logged_exception(e)
self.logger.exception(e) | def exception(self, e) | Log an error messsage.
:param e: Exception to log. | 7.341497 | 9.566339 | 0.76743 |
if str(e) not in self._errors:
self._errors.append(str(e))
self.set_error_state()
self.buildstate.state.exception_type = str(e.__class__.__name__)
self.buildstate.state.exception = str(e) | def logged_exception(self, e) | Record the exception, but don't log it; it's already been logged
:param e: Exception to log. | 4.460551 | 4.814951 | 0.926396 |
if message not in self._warnings:
self._warnings.append(message)
self.logger.warn(message) | def warn(self, message) | Log an error messsage.
:param message: Log message. | 3.724752 | 4.867089 | 0.765294 |
self.logger.fatal(message)
sys.stderr.flush()
if self.exit_on_fatal:
sys.exit(1)
else:
raise FatalError(message) | def fatal(self, message) | Log a fatal messsage and exit.
:param message: Log message. | 3.181071 | 3.860942 | 0.823911 |
from datetime import datetime
from ambry.etl.pipeline import CastColumns
self.build_fs.makedir('pipeline', allow_recreate=True)
try:
ccp = pl[CastColumns]
caster_code = ccp.pretty_code
except Exception as e:
caster_code = str(e)
... | def log_pipeline(self, pl) | Write a report of the pipeline out to a file | 5.793285 | 5.727896 | 1.011416 |
from ambry.etl.pipeline import Pipeline, PartitionWriter
from ambry.dbexceptions import ConfigurationError
if source:
source = self.source(source) if isinstance(source, string_types) else source
else:
source = None
sf, sp = self.source_pipe(sour... | def pipeline(self, source=None, phase='build', ps=None) | Construct the ETL pipeline for all phases. Segments that are not used for the current phase
are filtered out later.
:param source: A source object, or a source string name
:return: an etl Pipeline | 4.531195 | 4.480623 | 1.011287 |
row = self.dataset.row(fields)
# Modify for special fields
for i, f in enumerate(fields):
if f == 'bstate':
row[i] = self.state
elif f == 'dstate':
row[i] = self.dstate
elif f == 'source_fs':
row[i] = ... | def field_row(self, fields) | Return a list of values to match the fields values. This is used when listing bundles to
produce a table of information about the bundle.
:param fields: A list of names of data items.
:return: A list of values, in the same order as the fields input
The names in the fields llist can be:... | 3.603333 | 3.14817 | 1.14458 |
if isinstance(source, string_types):
source = self.source(source)
source.dataset = self.dataset
source._bundle = self
iter_source, source_pipe = self._iterable_source(source, ps)
if self.limited_run:
source_pipe.limit = 500
return ite... | def source_pipe(self, source, ps=None) | Create a source pipe for a source, giving it access to download files to the local cache | 5.908871 | 5.990093 | 0.986441 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.