code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
from fs.zipfs import ZipOpenError
import os
from ambry_sources.sources import ( GoogleSource, CsvSource, TsvSource, FixedSource,
ExcelSource, PartitionSource, SourceError, DelayedOpen,
DelayedDownloa... | def get_source(self, source, clean=False, callback=None) | Download a file from a URL and return it wrapped in a row-generating acessor object.
:param spec: A SourceSpec that describes the source to fetch.
:param account_accessor: A callable to return the username and password to use for access FTP and S3 URLs.
:param clean: Delete files in cache and r... | 3.449853 | 3.44811 | 1.000506 |
self.buildstate.state.lasttime = time()
self.buildstate.commit()
return self.buildstate.state.error | def error_state(self) | Set the error condition | 11.117111 | 10.387995 | 1.070188 |
assert state != 'build_bundle'
self.buildstate.state.current = state
self.buildstate.state[state] = time()
self.buildstate.state.lasttime = time()
self.buildstate.state.error = False
self.buildstate.state.exception = None
self.buildstate.state.exceptio... | def state(self, state) | Set the current build state and record the time to maintain history.
Note! This is different from the dataset state. Setting the build set is commiteed to the
progress table/database immediately. The dstate is also set, but is not committed until the
bundle is committed. So, the dstate changes ... | 4.501056 | 3.890633 | 1.156895 |
key = '{}-{}'.format(phase, stage if stage else 1)
self.buildstate.state[key] = time() | def record_stage_state(self, phase, stage) | Record the completion times of phases and stages | 13.856658 | 13.297844 | 1.042023 |
import time
# time defeats check that value didn't change
self.buildstate.access.last = '{}-{}'.format(tag, time.time())
self.buildstate.commit() | def set_last_access(self, tag) | Mark the time that this bundle was last accessed | 23.266008 | 23.468739 | 0.991362 |
self.log('---- Sync In ----')
self.dstate = self.STATES.BUILDING
for path_name in self.source_fs.listdir():
f = self.build_source_files.instance_from_name(path_name)
if not f:
self.warn('Ignoring unknown file: {}'.format(path_name))
... | def sync_in(self, force=False) | Synchronize from files to records, and records to objects | 7.288238 | 6.398952 | 1.138974 |
self.log('---- Sync Files ----')
self.dstate = self.STATES.BUILDING
for f in self.build_source_files:
if self.source_fs.exists(f.record.path):
# print f.path, f.fs_modtime, f.record.modified, f.record.source_hash, f.fs_hash
if f.fs_is_newer... | def sync_in_files(self, force=False) | Synchronize from files to records | 6.944899 | 6.403162 | 1.084605 |
self.log('---- Sync Files ----')
for f in self.build_source_files:
f.record_to_objects()
# Only the metadata needs to be driven to the objects, since the other files are used as code,
# directly from the file record.
self.build_source_files.file(File.BSFILE... | def sync_in_records(self, force=False) | Synchronize from files to records | 15.743927 | 14.588001 | 1.079238 |
self.log('---- Sync Out ----')
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
for f in self.build_source_files.list_records():
if (f.sync_dir() == BuildSourceFile.SYNC_DIR.RECORD_TO_FILE or f.record.path == file_name) or force:
... | def sync_out(self, file_name=None, force=False) | Synchronize from objects to records | 8.524179 | 7.855281 | 1.085153 |
self.dstate = self.STATES.BUILDING
self.build_source_files.record_to_objects() | def sync_objects_in(self) | Synchronize from records to objects | 26.82855 | 19.908728 | 1.347577 |
self.log('---- Sync Objects Out ----')
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
for f in self.build_source_files.list_records():
self.log('Sync: {}'.format(f.record.path))
f.objects_to_record()
self.com... | def sync_objects_out(self, force=False) | Synchronize from objects to records, and records to files | 11.743126 | 9.952321 | 1.179938 |
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.BUILD, File.BSFILE.META, File.BSFILE.LIB, File.BSFILE.TEST, File.BSFILE.DOC]:
bsf = self.build_source_files.... | def sync_code(self) | Sync in code files and the meta file, avoiding syncing the larger files | 7.954621 | 7.466443 | 1.065383 |
from ambry.orm.file import File
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.SOURCES]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer or force:
self.log('Syncing {}'.format(bsf.file_name))
... | def sync_sources(self, force=False) | Sync in only the sources.csv file | 9.555163 | 9.147073 | 1.044614 |
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.SCHEMA, File.BSFILE.SOURCESCHEMA]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer:
... | def sync_schema(self) | Sync in code files and the meta file, avoiding syncing the larger files | 9.426168 | 8.870114 | 1.062688 |
self.commit()
self.build_source_files.schema.objects_to_record()
self.commit() | def update_schema(self) | Propagate schema object changes to file records | 24.204411 | 15.821627 | 1.529831 |
if self.is_finalized and not force:
self.warn("Can't clean; bundle is finalized")
return False
self.log('---- Cleaning ----')
self.state = self.STATES.CLEANING
self.dstate = self.STATES.BUILDING
self.commit()
self.clean_sources()
... | def clean(self, force=False) | Clean generated objects from the dataset, but only if there are File contents
to regenerate them | 4.312747 | 4.245551 | 1.015827 |
if self.is_finalized:
self.warn("Can't clean; bundle is finalized")
return False
self.log('---- Cleaning ----')
self.state = self.STATES.CLEANING
self.commit()
self.clean_sources()
self.clean_tables()
self.clean_partitions()
... | def clean_except_files(self) | Clean everything except the build source files | 4.436494 | 4.194829 | 1.05761 |
for src in self.dataset.sources:
src.st_id = None
src.t_id = None
self.dataset.sources[:] = []
self.dataset.source_tables[:] = []
self.dataset.st_sequence_id = 1 | def clean_sources(self) | Like clean, but also clears out files. | 5.870668 | 5.397725 | 1.087619 |
import shutil
from ambry.orm import ColumnStat
# FIXME. There is a problem with the cascades for ColumnStats that prevents them from
# being deleted with the partitions. Probably, they are seen to be owed by the columns instead.
self.session.query(ColumnStat).filter(Co... | def clean_partitions(self) | Delete partition records and any built partition files. | 11.396135 | 10.559721 | 1.079208 |
import shutil
if self.build_fs.exists:
try:
shutil.rmtree(self.build_fs.getsyspath('/'))
except NoSysPathError:
pass | def clean_build(self) | Delete the build directory and all ingested files | 7.413029 | 6.716561 | 1.103694 |
for s in self.sources:
df = s.datafile
if df.exists and not s.is_partition:
df.remove()
s.state = s.STATES.NEW
self.commit() | def clean_ingested(self) | Clean ingested files | 8.3769 | 7.818055 | 1.071481 |
ds = self.dataset
ds.config.build.clean()
ds.config.process.clean()
ds.commit()
self.state = self.STATES.CLEANED | def clean_process_meta(self) | Remove all process and build metadata | 8.700191 | 6.327938 | 1.374886 |
self.build_source_files.file(File.BSFILE.SOURCESCHEMA).remove()
self.build_source_files.file(File.BSFILE.SCHEMA).remove()
self.commit() | def clean_source_files(self) | Remove the schema.csv and source_schema.csv files | 11.389404 | 8.228726 | 1.384103 |
from itertools import groupby
from ambry.bundle.events import TAG
from fs.errors import ResourceNotFoundError
import zlib
self.log('---- Ingesting ----')
self.dstate = self.STATES.BUILDING
self.commit() # WTF? Without this, postgres blocks between tabl... | def ingest(self, sources=None, tables=None, stage=None, force=False, load_meta=False) | Ingest a set of sources, specified as source objects, source names, or destination tables.
If no stage is specified, execute the sources in groups by stage.
Note, however, that when this is called from run_stage, all of the sources have the same stage, so they
get grouped together. The result i... | 4.870866 | 4.8518 | 1.00393 |
from concurrent import ingest_mp
self.state = self.STATES.INGESTING
downloadable_sources = [s for s in sources if force or
(s.is_processable and not s.is_ingested and not s.is_built)]
errors = 0
with self.progress.start('ingest', stage... | def _ingest_sources(self, sources, stage, force=False) | Ingest a set of sources, usually for one stage | 6.926214 | 6.829228 | 1.014202 |
from ambry.bundle.process import call_interval
try:
from ambry.orm.exc import NotFoundError
if not source.is_partition and source.datafile.exists:
if not source.datafile.is_finalized:
source.datafile.remove()
elif f... | def _ingest_source(self, source, ps, force=None) | Ingest a single source | 4.865038 | 4.847347 | 1.00365 |
sources = self._resolve_sources(sources, tables, None,
predicate=lambda s: s.is_processable)
for source in sources:
source.update_table()
self.log("Creating source schema for '{}': Table {}, {} columns"
.for... | def source_schema(self, sources=None, tables=None, clean=False) | Process a collection of ingested sources to make source tables. | 5.922842 | 5.523989 | 1.072204 |
from itertools import groupby
from operator import attrgetter
from ambry.etl import Collect, Head
from ambry.orm.exc import NotFoundError
self.dstate = self.STATES.BUILDING
self.commit() # Workaround for https://github.com/CivicKnowledge/ambry/issues/171
... | def schema(self, sources=None, tables=None, clean=False, force=False, use_pipeline=False) | Generate destination schemas.
:param sources: If specified, build only destination tables for these sources
:param tables: If specified, build only these tables
:param clean: Delete tables and partitions first
:param force: Population tables even if the table isn't empty
:param ... | 4.961054 | 4.822968 | 1.028631 |
from ambry.orm.exc import NotFoundError
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
self.log("Removing old segment partition: {}".format(p.identity.name))
try:
self.wrap_partition(p).local_datafile.remove()
... | def _reset_build(self, sources) | Remove partition datafiles and reset the datafiles to the INGESTED state | 4.962986 | 4.3783 | 1.133542 |
sources = self._resolve_sources(None, [table])
for source in sources:
self.build_source(None, source, force=force)
self.unify_partitions() | def build_table(self, table, force=False) | Build all of the sources for a table | 7.848415 | 6.341957 | 1.237538 |
from ambry.bundle.process import call_interval
assert source.is_processable, source.name
if source.state == self.STATES.BUILT and not force:
ps.update(message='Source {} already built'.format(source.name), state='skipped')
return
pl = self.pipeline(sou... | def build_source(self, stage, source, ps, force=False) | Build a single source | 5.80207 | 5.758333 | 1.007595 |
from collections import defaultdict
# Group the segments by their parent partition name, which is the
# same name, but without the segment.
partitions = defaultdict(set)
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
name = p.... | def collect_segment_partitions(self) | Return a dict of segments partitions, keyed on the name of the parent partition | 7.246181 | 6.504399 | 1.114043 |
partitions = self.collect_segment_partitions()
# For each group, copy the segment partitions to the parent partitions, then
# delete the segment partitions.
with self.progress.start('coalesce', 0, message='Coalescing partition segments') as ps:
for name, segments... | def unify_partitions(self) | For all of the segments for a partition, create the parent partition, combine the
children into the parent, and delete the children. | 9.158134 | 7.655925 | 1.196215 |
import inspect
import dateutil.parser
import datetime
import random
from functools import partial
from ambry.valuetype.types import parse_date, parse_time, parse_datetime
import ambry.valuetype.types
import ambry.valuetype.exceptions
impor... | def exec_context(self, **kwargs) | Base environment for evals, the stuff that is the same for all evals. Primarily used in the
Caster pipe | 3.533296 | 3.526213 | 1.002009 |
from ambry.util.datestimes import expand_to_years
years = set()
# From the bundle about
if self.metadata.about.time:
for year in expand_to_years(self.metadata.about.time):
years.add(year)
# From the bundle name
if self.identity.btim... | def post_build_time_coverage(self) | Collect all of the time coverage for the bundle. | 4.695898 | 4.136475 | 1.135242 |
spaces = set()
grains = set()
def resolve(term):
places = list(self.library.search.search_identifiers(term))
if not places:
raise BuildError(
"Failed to find space identifier '{}' in full text identifier search".format(term)... | def post_build_geo_coverage(self) | Collect all of the geocoverage for the bundle. | 4.85042 | 4.632834 | 1.046966 |
return self.state == self.STATES.FINALIZED or self.state == self.STATES.INSTALLED | def is_finalized(self) | Return True if the bundle is installed. | 8.257111 | 4.883271 | 1.690898 |
self._run_event_methods(tag, stage)
self._run_tests(tag, stage) | def _run_events(self, tag, stage=None) | Run tests marked with a particular tag and stage | 6.192266 | 5.193088 | 1.192405 |
import inspect
from ambry.bundle.events import _runable_for_event
funcs = []
for func_name, f in inspect.getmembers(self, predicate=inspect.ismethod):
if _runable_for_event(f, tag, stage):
funcs.append(f)
for func in funcs:
func... | def _run_event_methods(self, tag, stage=None) | Run code in the bundle that is marked with events. | 4.162784 | 3.493048 | 1.191734 |
r = self.library.resolve(self.identity.vid)
return r is not None | def is_installed(self) | Return True if the bundle is installed. | 30.050541 | 17.581043 | 1.709258 |
'''Replicate property that is normally not replicated. Right now it's
meaningful for one-to-many relations only.'''
if isinstance(prop, QueryableAttribute):
prop = prop.property
assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty))
#assert isinstance(prop, RelationshipPrope... | def include(prop) | Replicate property that is normally not replicated. Right now it's
meaningful for one-to-many relations only. | 8.755172 | 3.735655 | 2.343678 |
'''Don't replicate property that is normally replicated: ordering column,
many-to-one relation that is marked for replication from other side.'''
if isinstance(prop, QueryableAttribute):
prop = prop.property
assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty))
_excluded.ad... | def exclude(prop) | Don't replicate property that is normally replicated: ordering column,
many-to-one relation that is marked for replication from other side. | 7.676267 | 3.251685 | 2.360704 |
'''Finds an object of class `model` with the same identifier as the
`source` object'''
if source is None:
return None
if cache and source in cache:
return cache[source]
db = object_session(source)
ident = identity_key(instance=source)[1]
assert ident is not None
return db... | def reflect(source, model, cache=None) | Finds an object of class `model` with the same identifier as the
`source` object | 5.613803 | 3.750174 | 1.496945 |
'''Replicates common SQLAlchemy attributes from the `source` object to the
`target` object.'''
target_manager = manager_of_class(type(target))
column_attrs = set()
relationship_attrs = set()
relationship_columns = set()
for attr in manager_of_class(type(source)).attributes:
if attr.k... | def replicate_attributes(source, target, cache=None) | Replicates common SQLAlchemy attributes from the `source` object to the
`target` object. | 3.014682 | 2.797576 | 1.077605 |
'''Replicates the `source` object to `model` class and returns its
reflection.'''
# `cache` is used to break circular dependency: we need to replicate
# attributes before merging target into the session, but replication of
# some attributes may require target to be in session to avoid infinite
#... | def replicate_no_merge(source, model, cache=None) | Replicates the `source` object to `model` class and returns its
reflection. | 6.356884 | 5.500031 | 1.155791 |
'''Replicates the `source` object to `model` class and returns its
reflection.'''
target = replicate_no_merge(source, model, cache=cache)
if target is not None:
db = object_session(source)
target = db.merge(target)
return target | def replicate(source, model, cache=None) | Replicates the `source` object to `model` class and returns its
reflection. | 7.086544 | 4.730039 | 1.4982 |
'''Replicates the list of objects to other class and returns their
reflections'''
targets = [replicate_no_merge(source, model, cache=cache)
for source in sources]
# Some objects may not be available in target DB (not published), so we
# have to exclude None from the list.
return [... | def replicate_filter(sources, model, cache=None) | Replicates the list of objects to other class and returns their
reflections | 9.937322 | 6.439749 | 1.543122 |
'''Returns the list of reflections of objects in the `source` list to other
class. Objects that are not found in target table are silently discarded.
'''
targets = [reflect(source, model, cache=cache) for source in sources]
# Some objects may not be available in target DB (not published), so we
... | def reflect_filter(sources, model, cache=None) | Returns the list of reflections of objects in the `source` list to other
class. Objects that are not found in target table are silently discarded. | 9.949047 | 4.238321 | 2.347403 |
from ambry.valuetype import resolve_value_type
if self.valuetype:
return resolve_value_type(self.valuetype)
else:
return resolve_value_type(self.datatype) | def valuetype_class(self) | Return the valuetype class, if one is defined, or a built-in type if it isn't | 4.667288 | 4.012384 | 1.163221 |
from ambry.valuetype import resolve_value_type
if self.valuetype and resolve_value_type(self.valuetype):
return resolve_value_type(self.valuetype)._pythontype
elif self.datatype:
try:
return self.types[self.datatype][1]
except KeyEr... | def python_type(self) | Return the python type for the row, possibly getting it from a valuetype reference | 4.434561 | 3.716137 | 1.193326 |
'''Return the code for the role, measure, dimension or error'''
from ambry.valuetype.core import ROLE
if not self.valuetype_class:
return ''
role = self.valuetype_class.role
if role == ROLE.UNKNOWN:
vt_code = self.valuetype_class.vt_code
if... | def role(self) | Return the code for the role, measure, dimension or error | 7.174164 | 4.691044 | 1.529332 |
from ambry.valuetype.core import ROLE
return self.role == ROLE.DIMENSION | def is_dimension(self) | Return true if the colum is a dimension | 50.806561 | 31.038609 | 1.636883 |
from ambry.valuetype.core import ROLE
return self.role == ROLE.MEASURE | def is_measure(self) | Return true if the colum is a dimension | 40.54401 | 27.562866 | 1.470965 |
from ambry.valuetype.core import ROLE
return self.role == ROLE.LABEL | def is_label(self) | Return true if the colum is a dimension | 42.749191 | 35.02507 | 1.220531 |
from ambry.valuetype.core import ROLE
return self.role == ROLE.ERROR | def is_error(self) | Return true if the colum is a dimension | 44.10276 | 35.907288 | 1.22824 |
for c in self.table.columns:
if c.parent == self.name and not c.valuetype_class.is_label():
yield c | def children(self) | Return the table's other column that have this column as a parent, excluding labels | 12.791637 | 6.559784 | 1.950009 |
if self.valuetype_class.is_label():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_label():
return c
return None | def label(self) | Return first child of the column that is marked as a label. Returns self if the column is a label | 7.451311 | 5.267674 | 1.414535 |
if self.valuetype_class.is_geoid():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_geoid():
return c | def geoid(self) | Return first child of the column, or self that is marked as a geographic identifier | 7.475076 | 4.874567 | 1.533485 |
if self.type_is_time():
dt = dateutil.parser.parse(v)
if self.datatype == Column.DATATYPE_TIME:
dt = dt.time()
if not isinstance(dt, self.python_type):
raise TypeError('{} was parsed to {}, expected {}'.format(v, type(dt), self.pytho... | def python_cast(self, v) | Cast a value to the type of the column.
Primarily used to check that a value is valid; it will throw an
exception otherwise | 5.946476 | 5.874862 | 1.01219 |
m = {
'int64': cls.DATATYPE_INTEGER64,
'float64': cls.DATATYPE_FLOAT,
'object': cls.DATATYPE_TEXT # Hack. Pandas makes strings into object.
}
t = m.get(dtype.name, None)
if not t:
raise TypeError(
"Failed to con... | def convert_numpy_type(cls, dtype) | Convert a numpy dtype into a Column datatype. Only handles common
types.
Implemented as a function to decouple from numpy | 5.003528 | 4.648234 | 1.076436 |
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs
if p.key not in ('table', 'stats', '_codes', 'data')}
if not d:
raise Exception(self.__dict__)
d['schema_type'] = self.schema_type
if self.data:
# Copy data fields into top le... | def dict(self) | A dict that holds key/values for all of the properties in the
object.
:return: | 5.121785 | 5.372015 | 0.95342 |
return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'} | def nonull_dict(self) | Like dict, but does not hold any null values.
:return: | 8.184706 | 11.72334 | 0.698155 |
import re
try:
return re.sub('_+', '_', re.sub('[^\w_]', '_', name).lower()).rstrip('_')
except TypeError:
raise TypeError(
'Trying to mangle name with invalid type of: ' + str(type(name))) | def mangle_name(name) | Mangles a column name to a standard form, remoing illegal
characters.
:param name:
:return: | 4.851493 | 5.10452 | 0.950431 |
return {c.value: (c.ikey if c.ikey else c.key) for c in self.codes} | def reverse_code_map(self) | Return a map from a code ( usually a string ) to the shorter numeric value | 11.100036 | 7.506471 | 1.478729 |
segments = self._expand_transform(self.transform)
if segments:
segments[0]['datatype'] = self.valuetype_class
for s in segments:
s['column'] = self
else:
segments = [self.make_xform_seg(datatype=self.valuetype_class, column=self)... | def expanded_transform(self) | Expands the transform string into segments | 8.43998 | 7.217833 | 1.169323 |
# from identity import ObjectNumber
# assert not target.fk_vid or not ObjectNumber.parse(target.fk_vid).revision
if target.sequence_id is None:
from ambry.orm.exc import DatabaseError
raise DatabaseError('Must have sequence_id before insertion')
# Chec... | def before_insert(mapper, conn, target) | event.listen method for Sqlalchemy to set the seqience_id for this
object and create an ObjectNumber value for the id_ | 8.02771 | 7.157033 | 1.121653 |
assert target.datatype or target.valuetype
target.name = Column.mangle_name(target.name)
Column.update_number(target) | def before_update(mapper, conn, target) | Set the column id number based on the table number and the sequence
id for the column. | 17.678003 | 13.374424 | 1.321777 |
env = env.copy()
pythonpath = []
for pkg in packages:
p = os.path.split(imp.find_module(pkg)[1])[0]
if p.startswith(os.path.join(sys.prefix, 'lib')):
continue
pythonpath.append(p)
pythonpath = list(set(pythonpath))
pythonpath.extend(env.get('PYTHONPATH', ''... | def spawnProcess(processProtocol, executable, args=(), env={},
path=None, uid=None, gid=None, usePTY=0,
packages=()) | Launch a process with a particular Python environment.
All arguments as to reactor.spawnProcess(), except for the
addition of an optional packages iterable. This should be
of strings naming packages the subprocess is to be able to
import. | 2.21528 | 2.215204 | 1.000034 |
return spawnProcess(processProtocol, sys.executable,
args, env, path, uid, gid, usePTY,
packages) | def spawnPythonProcess(processProtocol, args=(), env={},
path=None, uid=None, gid=None, usePTY=0,
packages=()) | Launch a Python process
All arguments as to spawnProcess(), except the executable
argument is omitted. | 2.676817 | 4.046371 | 0.661535 |
if not hasattr(f, '__ambry_event__'):
return False
f_tag, f_stage = f.__ambry_event__
if stage is None:
stage = 0
if tag != f_tag or stage != f_stage:
return False
return True | def _runable_for_event(f, tag, stage) | Loot at the event property for a function to see if it should be run at this stage. | 3.427681 | 3.358386 | 1.020634 |
if prefix and not import_path.startswith(prefix):
import_path = '.'.join([prefix, import_path])
log.debug(
'attempting to load a python object from an import path',
extra=dict(import_path=import_path, **ld))
try:
mod = importlib.import_module(import_path)
return... | def load_obj_from_path(import_path, prefix=None, ld=dict()) | import a python object from an import path
`import_path` - a python import path. For instance:
mypackage.module.func
or
mypackage.module.class
`prefix` (str) - a value to prepend to the import path
if it isn't already there. For instance:
load_obj_from_path... | 3.435568 | 3.355642 | 1.023819 |
allowed_values = ["NEW", "VERIFIED", "TESTED", "DEPRECATED", "BLACKLISTED", "DELETED", "TEMPORARY"]
if artifact_quality not in allowed_values:
raise ValueError(
"Invalid value for `artifact_quality` ({0}), must be one of {1}"
.format(artifact_quality,... | def artifact_quality(self, artifact_quality) | Sets the artifact_quality of this ArtifactRest.
:param artifact_quality: The artifact_quality of this ArtifactRest.
:type: str | 2.31236 | 2.140691 | 1.080193 |
# TODO: Move to the sqlite wrapper.
# TODO: Consider sqlalchemy mapping.
SQL_TO_PYTHON_TYPES = {
'INT': int,
'INTEGER': int,
'TINYINT': int,
'SMALLINT': int,
'MEDIUMINT': int,
'BIGINT': int,
'UNSIGNED BIG INT': int,
'INT': int,
'IN... | def _get_sqlite_columns(connection, table) | Returns list of tuple containg columns of the table.
Args:
connection: sqlalchemy connection to sqlite database.
table (str): name of the table
Returns:
list of (name, datatype, position): where name is column name, datatype is
python type of the column, position is ordinal... | 2.604675 | 2.427602 | 1.072942 |
if self.urltype != 'partition':
return None
return self._bundle.library.partition(self.url) | def partition(self) | For partition urltypes, return the partition specified by the ref | 22.655952 | 10.02848 | 2.259161 |
from ambry_sources import MPRowsFile
if self._datafile is None:
if self.urltype == 'partition':
self._datafile = self.partition.datafile
else:
self._datafile = MPRowsFile(self._bundle.build_ingest_fs, self.name)
return self._... | def datafile(self) | Return an MPR datafile from the /ingest directory of the build filesystem | 9.847216 | 7.20023 | 1.367625 |
from ambry_sources.sources import SourceSpec
d = self.dict
d['url'] = self.url
# Will get the URL twice; once as ref and once as URL, but the ref is ignored
return SourceSpec(**d) | def spec(self) | Return a SourceSpec to describe this source | 20.510021 | 15.206476 | 1.348769 |
from ambry.util import parse_url_to_dict
d = parse_url_to_dict(self.url)
return self._bundle.library.account(d['netloc']) | def account(self) | Return an account record, based on the host in the url | 7.791825 | 6.085751 | 1.280339 |
from ambry_sources.intuit import TypeIntuiter
st = self.source_table
if self.reftype == 'partition':
for c in self.partition.table.columns:
st.add_column(c.sequence_id, source_header=c.name, dest_header=c.name,
datatype=c.datat... | def update_table(self, unknown_type='str') | Update the source table from the datafile | 4.65849 | 4.495057 | 1.036358 |
if self.datafile.exists:
with self.datafile.reader as r:
self.header_lines = r.info['header_rows']
self.comment_lines = r.info['comment_rows']
self.start_line = r.info['data_start_row']
self.end_line = r.info['data_end_row'] | def update_spec(self) | Update the source specification with information from the row intuiter, but only if the spec values
are not already set. | 3.732346 | 3.560725 | 1.048198 |
SKIP_KEYS = ('_source_table', '_dest_table', 'd_vid', 't_vid', 'st_id',
'dataset', 'hash', 'process_records')
return OrderedDict([(k, getattr(self, k)) for k in self.properties if k not in SKIP_KEYS]) | def dict(self) | A dict that holds key/values for all of the properties in the
object.
:return: | 8.639977 | 9.551972 | 0.904523 |
return load(path, root=root, db=db) | def get_runconfig(path=None, root=None, db=None) | Load the main configuration files and accounts file.
Debprecated. Use load() | 7.703846 | 6.941003 | 1.109904 |
"Load all of the config files. "
config = load_config(path, load_user=load_user)
remotes = load_remotes(path, load_user=load_user)
# The external file overwrites the main config
if remotes:
if not 'remotes' in config:
config.remotes = AttrDict()
for k, v in remotes.re... | def load(path=None, root=None, db=None, load_user=True) | Load all of the config files. | 3.093189 | 2.881123 | 1.073605 |
paths = []
if extra_path is not None:
paths.append(extra_path)
if os.getenv(ENVAR.CONFIG):
paths.append(os.getenv(ENVAR.CONFIG))
if os.getenv(ENVAR.VIRT):
paths.append(os.path.join(os.getenv(ENVAR.VIRT), USER_DIR))
if load_user:
paths.append(os.path.expandus... | def find_config_file(file_name, extra_path=None, load_user=True) | Find a configuration file in one of these directories, tried in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- ~/ambry
- /etc/ambry
:param file_name:
:param ex... | 2.400986 | 2.349709 | 1.021823 |
from os.path import getmtime
try:
accts_file = find_config_file(ACCOUNTS_FILE, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
accts_file = None
if accts_file is not None and os.path.exists(accts_file):
config = AttrDict()
config.update_yam... | def load_accounts(extra_path=None, load_user=True) | Load the yaml account files
:param load_user:
:return: An `AttrDict` | 3.51155 | 3.452071 | 1.01723 |
from os.path import getmtime
try:
remotes_file = find_config_file(REMOTES_FILE, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
remotes_file = None
if remotes_file is not None and os.path.exists(remotes_file):
config = AttrDict()
config.upd... | def load_remotes(extra_path=None, load_user=True) | Load the YAML remotes file, which sort of combines the Accounts file with part of the
remotes sections from the main config
:return: An `AttrDict` | 2.873616 | 2.770729 | 1.037134 |
from os.path import getmtime
config = AttrDict()
if not path:
path = ROOT_DIR
config_file = find_config_file(CONFIG_FILE, extra_path=path, load_user=load_user)
if os.path.exists(config_file):
config.update_yaml(config_file)
config.loaded = [config_file, getmtime(co... | def load_config(path=None, load_user=True) | Load configuration information from a config directory. Tries directories in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- /etc/ambry
- ~/ambry
:param path: An it... | 4.778135 | 4.790699 | 0.997377 |
from ambry.util import select_from_url
try:
_ = config.library
except KeyError:
config.library = AttrDict()
try:
_ = config.filesystem
except KeyError:
config.filesystem = AttrDict()
try:
_ = config.accounts
except KeyError:
config.acc... | def update_config(config, use_environ=True) | Update the configuration from environmental variables. Updates:
- config.library.database from the AMBRY_DB environmental variable.
- config.library.filesystem_root from the AMBRY_ROOT environmental variable.
- config.accounts.password from the AMBRY_PASSWORD environmental variable.
:param config: An... | 3.033805 | 2.814482 | 1.077927 |
if isinstance(d, dict):
try:
# Convert from an AttrDict to a real dict
d = d.to_dict()
except AttributeError:
pass # Already a real dict
config = d
dsn = None
elif isinstance(d, string_types):
config = None
dsn = d
... | def normalize_dsn_or_dict(d) | Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version | 3.632463 | 3.541466 | 1.025695 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_new_product_version_with_http_info(**kwargs)
else:
(data) = self.create_new_product_version_with_http_info(**kwargs)
return data | def create_new_product_version(self, **kwargs) | Create a new ProductVersion for a Product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(res... | 1.471913 | 1.660139 | 0.88662 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_build_configuration_sets_with_http_info(id, **kwargs)
else:
(data) = self.get_build_configuration_sets_with_http_info(id, **kwargs)
return data | def get_build_configuration_sets(self, id, **kwargs) | Gets build configuration sets associated with a product version
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
... | 1.420677 | 1.637833 | 0.867413 |
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_build_configuration_sets_with_http_info(id, **kwargs)
else:
(data) = self.update_build_configuration_sets_with_http_info(id, **kwargs)
return data | def update_build_configuration_sets(self, id, **kwargs) | This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_build_co... | 1.454886 | 1.597093 | 0.910958 |
if execute:
if echo:
print("Executing: " + cmd)
return os.system(cmd)
else:
print(cmd)
return 0 | def execute_command(cmd, execute, echo=True) | Execute a command in shell or just print it if execute is False | 2.728736 | 2.586696 | 1.054912 |
lLevel = level.lower()
unrecognized = False
if (lLevel == 'debug-all'):
loglevel = logging.DEBUG
elif (lLevel == 'debug'):
loglevel = logging.DEBUG
elif (lLevel == 'info'):
loglevel = logging.INFO
elif (lLevel == 'warning'):
loglevel = logging.WARNING
eli... | def set_log_level(level) | Sets the desired log level. | 2.372434 | 2.378799 | 0.997324 |
args = {}
for rarg in argv:
if re.match("^--.*", rarg):
arg = rarg.replace('--','', 1)
fsplit = arg.split('=', 1)
if len(fsplit) != 2:
raise Exception(
"Command option '%s' not recognized." % rarg)
rkey, value = ... | def parse_conf_args(argv) | Parse command line options into {section: (option, key)} which can be
used for overlaying on top of config
:param argv: list of argumets to be parsed
:return: Dictionary in the following format: {section: (option, key)} | 2.962901 | 2.857157 | 1.03701 |
def wrap(f):
def wrappedf(*args):
result = f(*args)
if result is None or result == "":
raise Exception(
"Config option '%s' is required." % field)
else:
return result
return wrappedf
return wrap | def required(field) | Decorator that checks if return value is set, if not, raises exception. | 3.938785 | 3.346536 | 1.176974 |
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == escape:
try:
# skip the next character; it has been escaped!
if not unescape:
current.append(escape)
current.append(next(itr))
except StopI... | def split_unescape(s, delim, escape='\\', unescape=True) | >>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,bar', ',', '$')
['foo,bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=True)
['foo$', 'bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=False)
['foo$$', 'bar']
>>> s... | 2.769599 | 3.159634 | 0.876557 |
if variables is None:
variables = {}
template = self._engine.get_template(template_name)
return template.render(**variables) | def render(self, template_name, variables=None) | Render a template with the passed variables. | 2.373365 | 2.236849 | 1.06103 |
if variables is None:
variables = {}
template = self._engine.from_string(source)
return template.render(**variables) | def render_source(self, source, variables=None) | Render a source with the passed variables. | 2.955489 | 2.75139 | 1.07418 |
'''
url_template - str or unicode representing template
Constructed pattern expects urlencoded string!
returns (compiled re pattern,
dict {url param name: [converter name, converter args (str)]},
list of (variable name, converter name, converter args name))
If anonym... | def construct_re(url_template, match_whole_str=False, converters=None,
default_converter='string', anonymous=False) | url_template - str or unicode representing template
Constructed pattern expects urlencoded string!
returns (compiled re pattern,
dict {url param name: [converter name, converter args (str)]},
list of (variable name, converter name, converter args name))
If anonymous=True is ... | 5.882819 | 3.235986 | 1.817937 |
'''
path - str (urlencoded)
'''
m = self._pattern.match(path)
if m:
kwargs = m.groupdict()
# convert params
for url_arg_name, value_urlencoded in kwargs.items():
conv_obj = self._url_params[url_arg_name]
unicode_... | def match(self, path, **kw) | path - str (urlencoded) | 4.043624 | 3.644519 | 1.109509 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.