code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not ckan: raise EnvironmentError(MISSING_CREDENTIALS_MSG) # publish dataset. try: ckan.action.package_create(**_convert_bundle(bundle)) except ckanapi.ValidationError: if force: logger.warning( '{} dataset already exported, but new export forc...
def export(bundle, force=False, force_restricted=False)
Exports bundle to ckan instance. Args: bundle (ambry.bundle.Bundle): force (bool, optional): if True, ignore existance error and continue to export. force_restricted (bool, optional): if True, then export restricted bundles as private (for debugging purposes). Raises: ...
3.66436
3.349535
1.09399
if not ckan: raise EnvironmentError(MISSING_CREDENTIALS_MSG) params = {'q': 'name:{}'.format(bundle.dataset.vid.lower())} resp = ckan.action.package_search(**params) return len(resp['results']) > 0
def is_exported(bundle)
Returns True if dataset is already exported to CKAN. Otherwise returns False.
6.676599
5.275603
1.265561
# shortcut for metadata meta = bundle.dataset.config.metadata notes = '' for f in bundle.dataset.files: if f.path.endswith('documentation.md'): contents = f.unpacked_contents if isinstance(contents, six.binary_type): contents = contents.decode('utf-...
def _convert_bundle(bundle)
Converts ambry bundle to dict ready to send to CKAN API. Args: bundle (ambry.bundle.Bundle): bundle to convert. Returns: dict: dict to send to CKAN to create dataset. See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_create
4.06536
3.764339
1.079966
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create # convert bundle to csv. csvfile = six.StringIO() writer = unicodecsv.writer(csvfile) headers = partition.datafile.headers if headers: writer.writerow(headers) for row in partition: writer.wr...
def _convert_partition(partition)
Converts partition to resource dict ready to save to CKAN.
3.73473
3.349453
1.115027
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create schema_csv = None for f in bundle.dataset.files: if f.path.endswith('schema.csv'): contents = f.unpacked_contents if isinstance(contents, six.binary_type): contents = contents....
def _convert_schema(bundle)
Converts schema of the dataset to resource dict ready to save to CKAN.
4.099741
3.609417
1.135846
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create ret = { 'package_id': bundle.dataset.vid.lower(), 'url': external.url, 'description': external.description, 'name': name, } return ret
def _convert_external(bundle, name, external)
Converts external documentation to resource dict ready to save to CKAN.
4.669909
3.757712
1.242753
if not kwargs.get("dependency_ids"): kwargs["dependency_ids"] = [] if not kwargs.get("build_configuration_set_ids"): kwargs["build_configuration_set_ids"] = [] if kwargs.get("generic_parameters"): kwargs["generic_parameters"] = ast.literal_eval(kwargs.get("generic_parameters"...
def create_build_configuration_process(repository, revision, **kwargs)
Create a new BuildConfiguration. BuildConfigurations represent the settings and configuration required to run a build of a specific version of the associated Project's source code. If a ProductVersion ID is provided, the BuildConfiguration will have access to artifacts which were produced for that version, but may ...
3.80179
3.661007
1.038455
repo = create_repository_configuration_raw(repository, no_sync) if repo: return utils.format_json(repo)
def create_repository_configuration(repository, no_sync=False)
Create a new RepositoryConfiguration. If the provided repository URL is for external repository, it is cloned into internal one. :return BPM Task ID of the new RepositoryConfiguration creation
6.813304
9.362132
0.727751
success_event_types = ("RC_CREATION_SUCCESS", ) error_event_types = ("RC_REPO_CREATION_ERROR", "RC_REPO_CLONE_ERROR", "RC_CREATION_ERROR") while retry > 0: bpm_task = get_bpm_task_by_id(task_id) if contains_event_type(bpm_task.content.events, success_event_types): break ...
def wait_for_repo_creation(task_id, retry=30)
Using polling check if the task finished
3.280963
3.264467
1.005053
''' A count based on `count_field` and `format_args`. ''' args = self.format_args if args is None or \ (isinstance(args, dict) and self.count_field not in args): raise TypeError("count is required") return args[self.count_field] if isinstance(a...
def count(self)
A count based on `count_field` and `format_args`.
5.542848
3.099235
1.788457
if not is_input_valid(milestone_id, output): logging.error("invalid input") return 1 create_work_dir(output) download_sources_artifacts(milestone_id, output) create_zip(output)
def generate_sources_zip(milestone_id=None, output=None)
Generate a sources archive for given milestone id.
4.647176
4.39069
1.058416
response = utils.checked_api_call(pnc_api.repositories, 'get_specific', id=id) if response: return response.content
def get_repository_configuration(id)
Retrieve a specific RepositoryConfiguration
8.534945
8.960381
0.95252
to_update_id = id rc_to_update = pnc_api.repositories.get_specific(id=to_update_id).content if external_repository is None: external_repository = rc_to_update.external_url else: rc_to_update.external_url = external_repository if prebuild_sync is not None: rc_to_update...
def update_repository_configuration(id, external_repository=None, prebuild_sync=None)
Update an existing RepositoryConfiguration with new information
2.784259
2.785909
0.999408
response = utils.checked_api_call(pnc_api.repositories, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q) if response: return utils.format_json_list(response.content)
def list_repository_configurations(page_size=200, page_index=0, sort="", q="")
List all RepositoryConfigurations
3.653283
3.737527
0.97746
content = search_repository_configuration_raw(url, page_size, page_index, sort) if content: return utils.format_json_list(content)
def search_repository_configuration(url, page_size=10, page_index=0, sort="")
Search for Repository Configurations based on internal or external url
3.72338
3.79296
0.981656
response = utils.checked_api_call(pnc_api.repositories, 'search', page_size=page_size, page_index=page_index, sort=sort, search=url) if response: return response.content
def search_repository_configuration_raw(url, page_size=10, page_index=0, sort="")
Search for Repository Configurations based on internal or external url
4.375538
4.544249
0.962874
content = match_repository_configuration_raw(url, page_size, page_index, sort) if content: return utils.format_json_list(content)
def match_repository_configuration(url, page_size=10, page_index=0, sort="")
Search for Repository Configurations based on internal or external url with exact match
4.113383
4.170805
0.986232
'''Proxy method to form's environment render method''' return self.env.template.render(self.template, form=self)
def render(self)
Proxy method to form's environment render method
19.401592
7.361982
2.635376
''' Try to accpet MultiDict-like object and return if it is valid. ''' self.raw_data = MultiDict(data) self.errors = {} for field in self.fields: if field.writable: self.python_data.update(field.accept()) else: for n...
def accept(self, data)
Try to accpet MultiDict-like object and return if it is valid.
5.425235
3.929486
1.380647
''' Returns data representing current state of the form. While Form.raw_data may contain alien fields and invalid data, this method returns only valid fields that belong to this form only. It's designed to pass somewhere current state of the form (as query string or by ot...
def get_data(self, compact=True)
Returns data representing current state of the form. While Form.raw_data may contain alien fields and invalid data, this method returns only valid fields that belong to this form only. It's designed to pass somewhere current state of the form (as query string or by other means).
7.701185
2.114427
3.642209
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_configuration_with_http_info(id, **kwargs) else: (data) = self.add_configuration_with_http_info(id, **kwargs) return data
def add_configuration(self, id, **kwargs)
Adds a configuration to the Specified Set 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.515751
1.674865
0.904999
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.build_with_http_info(id, **kwargs) else: (data) = self.build_with_http_info(id, **kwargs) return data
def build(self, id, **kwargs)
Builds the Configurations for the Specified Set 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): >>> ppri...
1.532262
1.619755
0.945984
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.build_versioned_with_http_info(id, **kwargs) else: (data) = self.build_versioned_with_http_info(id, **kwargs) return data
def build_versioned(self, id, **kwargs)
Builds the configurations for the Specified Set with an option to specify exact revision of a BC 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 ...
1.526199
1.584056
0.963476
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.delete_specific_with_http_info(id, **kwargs) else: (data) = self.delete_specific_with_http_info(id, **kwargs) return data
def delete_specific(self, id, **kwargs)
Removes a specific Build Configuration Set 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(re...
1.49971
1.652306
0.907646
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_build_config_set_records_with_http_info(id, **kwargs) else: (data) = self.get_all_build_config_set_records_with_http_info(id, **kwargs) return data
def get_all_build_config_set_records(self, id, **kwargs)
Get all build config set execution records associated with this build config set, returns empty list if none are found 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 resp...
1.351801
1.556405
0.86854
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_build_records_with_http_info(id, **kwargs) else: (data) = self.get_build_records_with_http_info(id, **kwargs) return data
def get_build_records(self, id, **kwargs)
Gets all build records associated with the contained build configurations 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(respo...
1.446664
1.668471
0.86706
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_configurations_with_http_info(id, **kwargs) else: (data) = self.get_configurations_with_http_info(id, **kwargs) return data
def get_configurations(self, id, **kwargs)
Gets the Configurations for the Specified Set 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...
1.483645
1.723312
0.860926
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_configuration_with_http_info(id, config_id, **kwargs) else: (data) = self.remove_configuration_with_http_info(id, config_id, **kwargs) return data
def remove_configuration(self, id, config_id, **kwargs)
Removes a configuration from the specified config set 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.435535
1.583212
0.906723
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_configurations_with_http_info(id, **kwargs) else: (data) = self.update_configurations_with_http_info(id, **kwargs) return data
def update_configurations(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_configur...
1.535851
1.682926
0.912607
package = name.split('.') # Note that this may include directories which do not exist. It may be # preferable to remove such directories at this point, rather than allow # them to be searched later on. # # Note as well that only '__init__.py' will be considered to make a # directory a ...
def pluginPackagePaths(name)
Return a list of additional directories which should be searched for modules to be included as part of the named plugin package. @type name: C{str} @param name: The fully-qualified Python name of a plugin package, eg C{'twisted.plugins'}. @rtype: C{list} of C{str} @return: The absolute pat...
6.63591
6.458826
1.027417
'''Calls decorated method with VersionedStorage as self''' def wrap(self, *args, **kwargs): return func(self._root_storage, *args, **kwargs) return wrap
def storage_method(func)
Calls decorated method with VersionedStorage as self
6.060433
3.883925
1.560389
'Interface method called from `Template.render`' return self.env.get_template(template_name).render(**kw)
def render(self, template_name, **kw)
Interface method called from `Template.render`
10.06478
4.315994
2.331973
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.cancel_all_builds_in_group_with_http_info(id, **kwargs) else: (data) = self.cancel_all_builds_in_group_with_http_info(id, **kwargs) return data
def cancel_all_builds_in_group(self, id, **kwargs)
Cancel all builds running in the build group 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(...
1.401914
1.544926
0.907431
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_bc_with_http_info(id, **kwargs) else: (data) = self.get_all_for_bc_with_http_info(id, **kwargs) return data
def get_all_for_bc(self, id, **kwargs)
Gets running Build Records for a specific Build Configuration. 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.392259
1.574284
0.884376
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_for_bc_set_record_with_http_info(id, **kwargs) else: (data) = self.get_all_for_bc_set_record_with_http_info(id, **kwargs) return data
def get_all_for_bc_set_record(self, id, **kwargs)
Gets running Build Records for a specific Build Configuration Set Record. 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(respo...
1.321941
1.513141
0.873641
def init(self, d, *args, **kwargs): self._original_dict = d def getter_from_dict_path(path): if not callable(path) and len(path) < 1: raise ValueError('Dict paths should be iterables with at least one' ' key or callable objects that take on...
def dictmapper(typename, mapping)
A factory to create `namedtuple`-like classes from a field-to-dict-path mapping:: Person = dictmapper({'person':('person','name')}) example_dict = {'person':{'name':'John'}} john = Person(example_dict) assert john.name == 'John' If a function is specified as a mapping value ins...
4.181303
4.074156
1.026299
return dict( config=self._config, search=self._search, echo=self._echo, read_only=self.read_only )
def ctor_args(self)
Return arguments for constructing a copy
7.688868
7.657733
1.004066
from ambry.library.config import LibraryConfigSyncProxy lcsp = LibraryConfigSyncProxy(self) lcsp.sync(force=force)
def sync_config(self, force=False)
Sync the file config into the library proxy data in the root dataset
7.487715
5.464112
1.370344
import signal def debug_trace(sig, frame): self.log('Trace signal received') self.log(''.join(traceback.format_stack(frame))) signal.signal(signal.SIGUSR2, debug_trace)
def init_debug(self)
Initialize debugging features, such as a handler for USR2 to print a trace
5.837549
5.208993
1.120667
if not isinstance(ref, ObjectNumber): on = ObjectNumber.parse(ref) else: on = ref ds_on = on.as_dataset return ds_on
def resolve_object_number(self, ref)
Resolve a variety of object numebrs to a dataset number
7.582402
6.428649
1.17947
return self.database.dataset(ref, load_all=load_all, exception=exception)
def dataset(self, ref, load_all=False, exception=True)
Return all datasets
3.378175
3.20736
1.053257
if not ('id' in kwargs and bool(kwargs['id'])) or assignment_class is not None: kwargs['id'] = self.number(assignment_class) ds = self._db.new_dataset(**kwargs) self._db.commit() b = self.bundle(ds.vid) b.state = Bundle.STATES.NEW b.set_last_acces...
def new_bundle(self, assignment_class=None, **kwargs)
Create a new bundle, with the same arguments as creating a new dataset :param assignment_class: String. assignment class to use for fetching a number, if one is not specified in kwargs :param kwargs: :return:
6.651618
6.523897
1.019577
identity = Identity.from_dict(config['identity']) ds = self._db.dataset(identity.vid, exception=False) if not ds: ds = self._db.new_dataset(**identity.dict) b = Bundle(ds, self) b.commit() b.state = Bundle.STATES.NEW b.set_last_access(Bundl...
def new_from_bundle_config(self, config)
Create a new bundle, or link to an existing one, based on the identity in config data. :param config: A Dict form of a bundle.yaml file :return:
6.56808
6.468528
1.01539
from ..orm.exc import NotFoundError if isinstance(ref, Dataset): ds = ref else: try: ds = self._db.dataset(ref) except NotFoundError: ds = None if not ds: try: p = self.partition(re...
def bundle(self, ref, capture_exceptions=False)
Return a bundle build on a dataset, with the given vid or id reference
3.664668
3.353248
1.092871
if not ref: raise NotFoundError("No partition for empty ref") try: on = ObjectNumber.parse(ref) ds_on = on.as_dataset ds = self._db.dataset(ds_on) # Could do it in on SQL query, but this is easier. # The refresh is required becaus...
def partition(self, ref, localize=False)
Finds partition by ref and converts to bundle partition. :param ref: A partition reference :param localize: If True, copy a remote partition to local filesystem. Defaults to False :raises: NotFoundError: if partition with given ref not found. :return: orm.Partition: found partition.
6.626789
6.386859
1.037566
try: obj_number = ObjectNumber.parse(ref) ds_obj_number = obj_number.as_dataset dataset = self._db.dataset(ds_obj_number) # Could do it in on SQL query, but this is easier. table = dataset.table(ref) except NotObjectNumberError: q ...
def table(self, ref)
Finds table by ref and returns it. Args: ref (str): id, vid (versioned id) or name of the table Raises: NotFoundError: if table with given ref not found. Returns: orm.Table
5.824634
5.699687
1.021922
from six import string_types if isinstance(bundle, string_types): bundle = self.bundle(bundle) self.database.remove_dataset(bundle.dataset)
def remove(self, bundle)
Removes a bundle from the library and deletes the configuration for it from the library database.
6.090778
5.229927
1.164601
on = b.identity.on on.revision = on.revision + 1 try: extant = self.bundle(str(on)) if extant: raise ConflictError('Already have a bundle with vid: {}'.format(str(on))) except NotFoundError: pass d = b.dataset.dict ...
def duplicate(self, b)
Duplicate a bundle, with a higher version number. This only copies the files, under the theory that the bundle can be rebuilt from them.
7.652304
7.282392
1.050795
from ambry.orm.exc import NotFoundError db = Database('sqlite:///{}'.format(db_path)) db.open() if len(db.datasets) == 0: raise NotFoundError("Did not get a dataset in the {} bundle".format(db_path)) ds = db.dataset(db.datasets[0].vid) # There should onl...
def checkin_bundle(self, db_path, replace=True, cb=None)
Add a bundle, as a Sqlite file, to this library
5.944123
5.722513
1.038726
raise DeprecationWarning("Don't use any more?") from ambry.bundle.process import call_interval remote_name = self.resolve_remote(b) remote = self.remote(remote_name) db_path = b.package() with b.progress.start('checkin', 0, message='Check in bundle') as ps:...
def send_to_remote(self, b, no_partitions=False)
Copy a bundle to a new Sqlite file, then store the file on the remote. :param b: The bundle :return:
3.712937
3.664236
1.013291
if not remote: remote, vname = self.find_remote_bundle(ref) if vname: ref = vname else: pass if not remote: raise NotFoundError("Failed to find bundle ref '{}' in any remote".format(ref)) self.logger.info("Load '...
def checkin_remote_bundle(self, ref, remote=None)
Checkin a remote bundle to this library. :param ref: Any bundle reference :param remote: If specified, use this remote. If not, search for the reference in cached directory listings :param cb: A one argument progress callback :return:
4.524086
4.848545
0.933081
from ambry.bundle.process import call_interval from ambry.orm.exc import NotFoundError from ambry.orm import Remote from ambry.util.flo import copy_file_or_flo from tempfile import NamedTemporaryFile assert isinstance(remote, Remote) @call_interval(5) ...
def _checkin_remote_bundle(self, remote, ref)
Checkin a remote bundle from a remote :param remote: a Remote object :param ref: Any bundle reference :return: The vid of the loaded bundle
4.96977
4.964576
1.001046
from ambry.orm import Remote for r in self.database.session.query(Remote).all(): if not r.short_name: continue yield self.remote(r.short_name)
def remotes(self)
Return the names and URLs of the remotes
5.246758
6.118255
0.857558
from ambry.orm import Remote from sqlalchemy import or_ from ambry.orm.exc import NotFoundError from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound if not name.strip(): raise NotFoundError("Empty remote name") try: try: ...
def _remote(self, name)
Return a remote for which 'name' matches the short_name or url
2.829067
2.550394
1.109267
for r in self.remotes: if remote_service_type and r.service != remote_service_type: continue if 'list' not in r.data: continue for k, v in r.data['list'].items(): if ref in v.values(): return (r,...
def _find_remote_bundle(self, ref, remote_service_type='s3')
Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache directory lists stored in the remotes, which must be updated to be current. :param ref: :return: (remote,vname) or (None,None) if the ref is not found
3.985319
3.45667
1.152936
from ambry.identity import ObjectNumber remote, vid = self._find_remote_bundle(ref) if remote: return (remote, vid) if try_harder: on = ObjectNumber.parse(vid) if on: raise NotImplementedError() don = on.as...
def find_remote_bundle(self, ref, try_harder=None)
Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache directory lists stored in the remotes, which must be updated to be current. :param vid: A bundle or partition reference, vid, or name :param try_harder: If the reference isn't found, try par...
5.270664
4.428675
1.190122
from sqlalchemy.orm.exc import NoResultFound from ambry.orm.exc import NotFoundError from ambry.util import parse_url_to_dict from ambry.orm import Account pd = parse_url_to_dict(url) # Old method of storing account information. try: act = s...
def account(self, url)
Return accounts references for the given account id. :param account_id: :param accounts_password: The password for decrypting the secret :return:
4.422794
4.415983
1.001542
d = {} if False and not self._account_password: from ambry.dbexceptions import ConfigurationError raise ConfigurationError( "Can't access accounts without setting an account password" " either in the accounts.password config, or in the AM...
def accounts(self)
Return an account reference :param account_id: :param accounts_password: The password for decrypting the secret :return:
5.733675
5.682352
1.009032
if assignment_class == 'self': # When 'self' is explicit, don't look for number server config return str(DatasetNumber()) elif assignment_class is None: try: nsconfig = self.services['numbers'] except ConfigurationError: ...
def number(self, assignment_class=None, namespace='d')
Return a new number. :param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) , 'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and acquired locally, while the other assignment classes use the nu...
4.489179
4.022774
1.115941
ret = self._db.session\ .query(Config)\ .filter(Config.type == 'buildstate')\ .filter(Config.group == 'access')\ .filter(Config.key == 'last')\ .order_by(Config.modified.desc())\ .all() return ret
def edit_history(self)
Return config record information about the most recent bundle accesses and operations
5.361362
4.602103
1.164981
import yaml fs = fsopendir(dir) bundles = [] for f in fs.walkfiles(wildcard='bundle.yaml'): self.logger.info('Visiting {}'.format(f)) config = yaml.load(fs.getcontents(f)) if not config: self.logger.error("Failed to get a...
def import_bundles(self, dir, detach=False, force=False)
Import bundles from a directory :param dir: :return:
3.87407
3.92239
0.987681
from multiprocessing import cpu_count from ambry.bundle.concurrent import Pool, init_library if self.processes: cpus = self.processes else: cpus = cpu_count() self.logger.info('Starting MP pool with {} processors'.format(cpus)) return P...
def process_pool(self, limited_run=False)
Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value
6.860023
6.663517
1.02949
import sys import inspect try: raise Exception except: file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:]) line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno return "{}:{}".format(file_, line_)
def file_loc()
Return file and line number
4.134651
3.816939
1.083237
dest_headers = [c.name for c in dest_table.columns] row_processors = [] out = [file_header] transforms = list(dest_table.transforms) column_names = [] column_types = [] for i, segments in enumerate(transforms): seg_funcs = [] for col_num, (segment, column) in enume...
def make_row_processors(bundle, source_headers, dest_table, env)
Make multiple row processors for all of the columns in a table. :param source_headers: :return:
3.776835
3.831635
0.985698
import inspect from ambry.dbexceptions import ConfigurationError if inspect.isclass(f): try: args = inspect.getargspec(f.__init__).args except TypeError as e: raise TypeError("Failed to inspect {}: {}".format(f, e)) else: args = inspect.getargspec(f...
def calling_code(f, f_name=None, raise_for_missing=True)
Return the code string for calling a function.
3.511894
3.427585
1.024597
import string import random from ambry.valuetype import ValueType column = segment['column'] def make_line(column, t): preamble = [] line_t = "v = {} # {}" if isinstance(t, type) and issubclass(t, ValueType): # A valuetype class, from the datatype column. ...
def make_stack(env, stage, segment)
For each transform segment, create the code in the try/except block with the assignements for pipes in the segment
4.940564
4.701311
1.050891
visitor = ReplaceTG(env, tg_name) assert visitor.tg_name tree = visitor.visit(ast.parse(code)) if visitor.loc: loc = ' #' + visitor.loc else: loc = file_loc() # The AST visitor didn't match a call node if visitor.trans_gen: tg = meta.dump_python_source(visitor.t...
def rewrite_tg(env, tg_name, code)
Re-write a transform generating function pipe specification by extracting the tranform generating part, and replacing it with the generated transform. so: tgen(a,b,c).foo.bar becomes: tg = tgen(a,b,c) tg.foo.bar
7.918665
8.023721
0.986907
count = next(self.counter) heapq.heappush(self._queue, (el, count))
def push(self, el)
Put a new element in the queue.
7.021492
5.616149
1.250233
sc = self._p.space_coverage gc = self._p.grain_coverage if sc and gc: if parse_to_gvid(gc[0]).level == 'state' and parse_to_gvid(sc[0]).level == 'state': return parse_to_gvid(sc[0]).geo_name else: return ("{} in {}".format( ...
def geo_description(self)
Return a description of the geographic extents, using the largest scale space and grain coverages
3.752868
3.265861
1.149121
tc = [t for t in self._p.time_coverage if t] if not tc: return '' mn = min(tc) mx = max(tc) if not mn and not mx: return '' elif mn == mx: return mn else: return "{} to {}".format(mn, mx)
def time_description(self)
String description of the year or year range
4.16365
4.031028
1.0329
gd = self.geo_description td = self.time_description if gd and td: return '{}, {}. {} Rows.'.format(gd, td, self._p.count) elif gd: return '{}. {} Rows.'.format(gd, self._p.count) elif td: return '{}. {} Rows.'.format(td, self._p.coun...
def sub_description(self)
Time and space dscription
3.054815
2.875081
1.062515
if self.dataset is None: # The relationship will be null until the object is committed s = object_session(self) ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one() else: ds = self.dataset d = { 'id': self.id, ...
def identity(self)
Return this partition information as a PartitionId.
4.750531
4.169143
1.13945
from ambry.util.datestimes import expand_to_years scov = set() tcov = set() grains = set() def summarize_maybe(gvid): try: return parse_to_gvid(gvid).summarize() except: return None def simplifiy_maybe(va...
def set_coverage(self, stats)
Extract time space and grain coverage from the stats and store them in the partition
3.951663
3.865575
1.02227
d = self.dict def aug_col(c): d = c.dict d['stats'] = [s.dict for s in c.stats] return d d['table'] = self.table.dict d['table']['columns'] = [aug_col(c) for c in self.table.columns] return d
def detail_dict(self)
A more detailed dict that includes the descriptions, sub descriptions, table and columns.
4.255261
3.530239
1.205375
from ambry_sources import MPRowsFile from fs.errors import ResourceNotFoundError from ambry.orm.exc import NotFoundError try: return MPRowsFile(self._bundle.build_fs, self.cache_key) except ResourceNotFoundError: raise NotFoundError( ...
def local_datafile(self)
Return the datafile for this partition, from the build directory, the remote, or the warehouse
11.61154
9.130172
1.271777
from ambry.exc import NotFoundError ds = self.dataset if 'remote_name' not in ds.data: raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.fqname)) return self._bundle.library.remote(ds.data['remote_name'])
def remote(self)
Return the remote for this partition :return:
8.583617
7.614594
1.127259
from ambry.orm.exc import NotFoundError try: if self.local_datafile.exists: return True except NotFoundError: pass return False
def is_local(self)
Return true is the partition file is local
7.032487
5.981184
1.175768
from filelock import FileLock from ambry.util import ensure_dir_exists from ambry_sources import MPRowsFile from fs.errors import ResourceNotFoundError if self.is_local: return local = self._bundle.build_fs b = self._bundle.library.bundle(s...
def localize(self, ps=None)
Copy a non-local partition file to the local build directory
5.26358
5.094323
1.033225
from ambry.orm.exc import NotFoundError from fs.errors import ResourceNotFoundError try: return self.datafile.reader except ResourceNotFoundError: raise NotFoundError("Failed to find partition file, '{}' " .format(self.dat...
def reader(self)
The reader for the datafile
9.897749
10.440323
0.948031
# FIXME; in Python 3, use yield from with self.reader as r: for row in r.select(predicate, headers): yield row
def select(self, predicate=None, headers=None)
Select rows from the reader using a predicate to select rows and and itemgetter to return a subset of elements :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param headers: If defined, a list or tuple of h...
9.460071
7.991395
1.183782
if isinstance(self, PartitionProxy): return AnalysisPartition(self._obj) else: return AnalysisPartition(self)
def analysis(self)
Return an AnalysisPartition proxy, which wraps this partition to provide acess to dataframes, shapely shapes and other analysis services
11.617082
5.086102
2.284083
if isinstance(self, PartitionProxy): return MeasureDimensionPartition(self._obj) else: return MeasureDimensionPartition(self)
def measuredim(self)
Return a MeasureDimension proxy, which wraps the partition to provide access to columns in terms of measures and dimensions
10.959859
5.975441
1.83415
if sequence_id: self.sequence_id = sequence_id self._set_ids(force=True) if self.dataset: self._update_names()
def update_id(self, sequence_id=None)
Alter the sequence id, and all of the names and ids derived from it. This often needs to be done after an IntegrityError in a multiprocessing run
5.312443
4.800647
1.10661
d = dict( table=self.table_name, time=self.time, space=self.space, grain=self.grain, variant=self.variant, segment=self.segment ) assert self.dataset name = PartialPartitionName(**d).promote(self.dataset....
def _update_names(self)
Update the derived names
5.903363
5.458096
1.081579
target._set_ids() if target.name and target.vname and target.cache_key and target.fqname and not target.dataset: return Partition.before_update(mapper, conn, target)
def before_insert(mapper, conn, target)
event.listen method for Sqlalchemy to set the sequence for this object and create an ObjectNumber value for the id_
12.927606
13.404968
0.964389
from operator import itemgetter from ambry.pands import AmbryDataFrame df_class = df_class or AmbryDataFrame if columns: ig = itemgetter(*columns) else: ig = None columns = self.table.header if filtered_columns: ...
def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None)
Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_columns: If defined, the value is a dict of column names and associated values. Only rows where al...
3.380394
3.335862
1.013349
from shapely.wkt import loads if not predicate: predicate = lambda row: True if simplify: return [loads(row.geometry).simplify(simplify) for row in self if predicate(row)] else: return [loads(row.geometry) for row in self if predicate(row)]
def shapes(self, simplify=None, predicate=None)
Return geodata as a list of Shapely shapes :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. :param predicate: A single-argument function to select which records to include in the output. :return: A list of Shapely objects
2.600233
2.469146
1.05309
from descartes import PolygonPatch from shapely.wkt import loads from shapely.ops import transform if not predicate: predicate = lambda row: True def map_xform(x, y, z=None): return basemap(x, y) def make_patch(shape, row): ...
def patches(self, basemap, simplify=None, predicate=None, args_f=None, **kwargs)
Return geodata as a list of Matplotlib patches :param basemap: A mpl_toolkits.basemap.Basemap :param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry. :param predicate: A single-argument function to select which records to include in the output. ...
2.586681
2.537128
1.019531
from ambry.valuetype.core import ROLE return [c for c in self.columns if c.role == ROLE.MEASURE]
def measures(self)
Iterate over all measures
17.852997
16.050785
1.112282
from ambry.orm import Column if isinstance(vid, PartitionColumn): return vid elif isinstance(vid, Column): return PartitionColumn(vid) else: return PartitionColumn(self.table.column(vid), self)
def measure(self, vid)
Return a measure, given its vid or another reference
6.495097
6.241823
1.040577
if not dimensions: dimensions = self.primary_dimensions key = p_dim.name if s_dim: key += '/' + s_dim.name # Ignore if the key already exists or the primary and secondary dims are the same if key in extant or p_dim == s_dim: return...
def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set())
Return a dict that describes the combination of one or two dimensions, for a plot :param p_dim: :param s_dim: :param dimensions: :param extant: :return:
3.361736
3.260874
1.030931
for c in self.table.columns: if c.parent == self.name and 'label' in c.valuetype: return PartitionColumn(c, self._partition)
def label(self)
Return first child that of the column that is marked as a label
13.074973
9.258597
1.412198
from operator import itemgetter card = self.pstats.nuniques if self.label: ig = itemgetter(self.name, self.label.name) elif self.pstats.nuniques < MAX_LABELS: ig = itemgetter(self.name, self.name) else: return {} label_set ...
def value_labels(self)
Return a map of column code values mapped to labels, for columns that have a label column If the column is not assocaited with a label column, it returns an identity map. WARNING! This reads the whole partition, so it is really slow
5.684197
4.694662
1.210779
data = list_build_configuration_sets_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def list_build_configuration_sets(page_size=200, page_index=0, sort="", q="")
List all build configuration sets
3.297478
3.500723
0.941942
config_set = _create_build_config_set_object(**kwargs) response = utils.checked_api_call(pnc_api.build_group_configs, 'create_new', body=config_set) if response: return response.content
def create_build_configuration_set_raw(**kwargs)
Create a new BuildConfigurationSet.
5.994707
5.868659
1.021478
found_id = common.set_id(pnc_api.build_group_configs, id, name) response = utils.checked_api_call(pnc_api.build_group_configs, 'get_specific', id=found_id) if response: return response.content
def get_build_configuration_set_raw(id=None, name=None)
Get a specific BuildConfigurationSet by name or ID
5.581792
5.484836
1.017677
content = get_build_configuration_set_raw(id, name) if content: return utils.format_json(content)
def get_build_configuration_set(id=None, name=None)
Get a specific BuildConfigurationSet by name or ID
5.335052
6.033782
0.884197
data = update_build_configuration_set_raw(id, **kwargs) if data: return utils.format_json(data)
def update_build_configuration_set(id, **kwargs)
Update a BuildConfigurationSet
5.673866
5.336027
1.063313
logging.debug("temp_build: " + str(tempbuild)) logging.debug("timestamp_alignment: " + str(timestamp_alignment)) logging.debug("force: " + str(force)) if tempbuild is False and timestamp_alignment is True: logging.error("You can only activate timestamp alignment with the temporary build fla...
def build_set_raw(id=None, name=None, tempbuild=False, timestamp_alignment=False, force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT, **kwargs)
Start a build of the given BuildConfigurationSet
3.526641
3.4031
1.036303
content = build_set_raw(id, name, temporary_build, timestamp_alignment, force, rebuild_mode, **kwargs) if content: return utils.format_json(content)
def build_set(id=None, name=None, temporary_build=False, timestamp_alignment=False, force=False, rebuild_mode=common.REBUILD_MODES_DEFAULT, **kwargs)
Start a build of the given BuildConfigurationSet
4.326542
4.331864
0.998771