INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Replaces a settings module with a Module proxy to intercept an access to settings.
def proxy_settings_module(depth=3): """Replaces a settings module with a Module proxy to intercept an access to settings. :param int depth: Frame count to go backward. """ proxies = [] modules = sys.modules module_name = get_frame_locals(depth)['__name__'] module_real = modules[modul...
Registers preferences that should be handled by siteprefs.
def register_prefs(*args, **kwargs): """Registers preferences that should be handled by siteprefs. Expects preferences as *args. Use keyword arguments to batch apply params supported by ``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``. Batch kwargs: :param ...
Marks preferences group.
def pref_group(title, prefs, help_text='', static=True, readonly=False): """Marks preferences group. :param str|unicode title: Group title :param list|tuple prefs: Preferences to group. :param str|unicode help_text: Field help text. :param bool static: Leave this preference static (do not store ...
Marks a preference.
def pref(preference, field=None, verbose_name=None, help_text='', static=True, readonly=False): """Marks a preference. :param preference: Preference variable. :param Field field: Django model field to represent this preference. :param str|unicode verbose_name: Field verbose name. :param str|unic...
: param ModuleType module:: param list prefs: Preference names. Just to speed up __getattr__.
def bind(self, module, prefs): """ :param ModuleType module: :param list prefs: Preference names. Just to speed up __getattr__. """ self._module = module self._prefs = set(prefs)
Generate the versionwarning - data. json file.
def generate_versionwarning_data_json(app, config=None, **kwargs): """ Generate the ``versionwarning-data.json`` file. This file is included in the output and read by the AJAX request when accessing to the documentation and used to compare the live versions with the curent one. Besides, this f...
Gives objective functions a number of dimensions and parameter range
def objective(param_scales=(1, 1), xstar=None, seed=None): """Gives objective functions a number of dimensions and parameter range Parameters ---------- param_scales : (int, int) Scale (std. dev.) for choosing each parameter xstar : array_like Optimal parameters """ ndim = ...
Pointwise minimum of two quadratic bowls
def doublewell(theta): """Pointwise minimum of two quadratic bowls""" k0, k1, depth = 0.01, 100, 0.5 shallow = 0.5 * k0 * theta ** 2 + depth deep = 0.5 * k1 * theta ** 2 obj = float(np.minimum(shallow, deep)) grad = np.where(deep < shallow, k1 * theta, k0 * theta) return obj, grad
Objective and gradient for the rosenbrock function
def rosenbrock(theta): """Objective and gradient for the rosenbrock function""" x, y = theta obj = (1 - x)**2 + 100 * (y - x**2)**2 grad = np.zeros(2) grad[0] = 2 * x - 400 * (x * y - x**3) - 2 grad[1] = 200 * (y - x**2) return obj, grad
Matyas function
def matyas(theta): """Matyas function""" x, y = theta obj = 0.26 * (x ** 2 + y ** 2) - 0.48 * x * y grad = np.array([0.52 * x - 0.48 * y, 0.52 * y - 0.48 * x]) return obj, grad
Beale s function
def beale(theta): """Beale's function""" x, y = theta A = 1.5 - x + x * y B = 2.25 - x + x * y**2 C = 2.625 - x + x * y**3 obj = A ** 2 + B ** 2 + C ** 2 grad = np.array([ 2 * A * (y - 1) + 2 * B * (y ** 2 - 1) + 2 * C * (y ** 3 - 1), 2 * A * x + 4 * B * x * y + 6 * C * x * y...
Booth s function
def booth(theta): """Booth's function""" x, y = theta A = x + 2 * y - 7 B = 2 * x + y - 5 obj = A**2 + B**2 grad = np.array([2 * A + 4 * B, 4 * A + 2 * B]) return obj, grad
McCormick function
def mccormick(theta): """McCormick function""" x, y = theta obj = np.sin(x + y) + (x - y)**2 - 1.5 * x + 2.5 * y + 1 grad = np.array([np.cos(x + y) + 2 * (x - y) - 1.5, np.cos(x + y) - 2 * (x - y) + 2.5]) return obj, grad
Three - hump camel function
def camel(theta): """Three-hump camel function""" x, y = theta obj = 2 * x ** 2 - 1.05 * x ** 4 + x ** 6 / 6 + x * y + y ** 2 grad = np.array([ 4 * x - 4.2 * x ** 3 + x ** 5 + y, x + 2 * y ]) return obj, grad
Michalewicz function
def michalewicz(theta): """Michalewicz function""" x, y = theta obj = - np.sin(x) * np.sin(x ** 2 / np.pi) ** 20 - \ np.sin(y) * np.sin(2 * y ** 2 / np.pi) ** 20 grad = np.array([ - np.cos(x) * np.sin(x ** 2 / np.pi) ** 20 - (40 / np.pi) * x * np.sin(x) * np.sin(x ** 2 / np.pi) ...
One of the Bohachevsky functions
def bohachevsky1(theta): """One of the Bohachevsky functions""" x, y = theta obj = x ** 2 + 2 * y ** 2 - 0.3 * np.cos(3 * np.pi * x) - 0.4 * np.cos(4 * np.pi * y) + 0.7 grad = np.array([ 2 * x + 0.3 * np.sin(3 * np.pi * x) * 3 * np.pi, 4 * y + 0.4 * np.sin(4 * np.pi * y) * 4 * np.pi, ...
Zakharov function
def zakharov(theta): """Zakharov function""" x, y = theta obj = x ** 2 + y ** 2 + (0.5 * x + y) ** 2 + (0.5 * x + y) ** 4 grad = np.array([ 2.5 * x + y + 2 * (0.5 * x + y) ** 3, 4 * y + x + 4 * (0.5 * x + y) ** 3, ]) return obj, grad
Dixon - Price function
def dixon_price(theta): """Dixon-Price function""" x, y = theta obj = (x - 1) ** 2 + 2 * (2 * y ** 2 - x) ** 2 grad = np.array([ 2 * x - 2 - 4 * (2 * y ** 2 - x), 16 * (2 * y ** 2 - x) * y, ]) return obj, grad
Goldstein - Price function
def goldstein_price(theta): """Goldstein-Price function""" x, y = theta obj = (1 + (x + y + 1) ** 2 * (19 - 14 * x + 3 * x ** 2 - 14 * y + 6 * x * y + 3 * y ** 2)) * \ (30 + (2 * x - 3 * y) ** 2 * (18 - 32 * x + 12 * x ** 2 + 48 * y - 36 * x * y + 27 * x ** 2)) grad = np.array([ ...
Styblinski - Tang function
def styblinski_tang(theta): """Styblinski-Tang function""" x, y = theta obj = 0.5 * (x ** 4 - 16 * x ** 2 + 5 * x + y ** 4 - 16 * y ** 2 + 5 * y) grad = np.array([ 2 * x ** 3 - 16 * x + 2.5, 2 * y ** 3 - 16 * y + 2.5, ]) return obj, grad
Return a list of buckets in MimicDB.
def get_all_buckets(self, *args, **kwargs): """Return a list of buckets in MimicDB. :param boolean force: If true, API call is forced to S3 """ if kwargs.pop('force', None): buckets = super(S3Connection, self).get_all_buckets(*args, **kwargs) for bucket in bucke...
Return a bucket from MimicDB if it exists. Return a S3ResponseError if the bucket does not exist and validate is passed.
def get_bucket(self, bucket_name, validate=True, headers=None, force=None): """Return a bucket from MimicDB if it exists. Return a S3ResponseError if the bucket does not exist and validate is passed. :param boolean force: If true, API call is forced to S3 """ if force: ...
Add the bucket to MimicDB after successful creation.
def create_bucket(self, *args, **kwargs): """Add the bucket to MimicDB after successful creation. """ bucket = super(S3Connection, self).create_bucket(*args, **kwargs) if bucket: mimicdb.backend.sadd(tpl.connection, bucket.name) return bucket
Delete the bucket on S3 before removing it from MimicDB. If the delete fails ( usually because the bucket is not empty ) do not remove the bucket from the set.
def delete_bucket(self, *args, **kwargs): """Delete the bucket on S3 before removing it from MimicDB. If the delete fails (usually because the bucket is not empty), do not remove the bucket from the set. """ super(S3Connection, self).delete_bucket(*args, **kwargs) bucket...
Sync either a list of buckets or the entire connection.
def sync(self, *buckets): """Sync either a list of buckets or the entire connection. Force all API calls to S3 and populate the database with the current state of S3. :param \*string \*buckets: Buckets to sync """ if buckets: for _bucket in buckets: ...
Return the key from MimicDB.
def get_key(self, *args, **kwargs): """Return the key from MimicDB. :param boolean force: If true, API call is forced to S3 """ if kwargs.pop('force', None): headers = kwargs.get('headers', {}) headers['force'] = True kwargs['headers'] = headers ...
Return None if key is not in the bucket set.
def _get_key_internal(self, *args, **kwargs): """Return None if key is not in the bucket set. Pass 'force' in the headers to check S3 for the key, and after fetching the key from S3, save the metadata and key to the bucket set. """ if args[1] is not None and 'force' in args[1]: ...
Return a list of keys from MimicDB.
def get_all_keys(self, *args, **kwargs): """Return a list of keys from MimicDB. :param boolean force: If true, API call is forced to S3 """ if kwargs.pop('force', None): headers = kwargs.get('headers', args[0] if len(args) else None) or dict() headers['force'] = ...
Remove each key or key name in an iterable from the bucket set.
def delete_keys(self, *args, **kwargs): """Remove each key or key name in an iterable from the bucket set. """ ikeys = iter(kwargs.get('keys', args[0] if args else [])) while True: try: key = ikeys.next() except StopIteration: brea...
Remove key name from bucket set.
def _delete_key_internal(self, *args, **kwargs): """Remove key name from bucket set. """ mimicdb.backend.srem(tpl.bucket % self.name, args[0]) mimicdb.backend.delete(tpl.key % (self.name, args[0])) return super(Bucket, self)._delete_key_internal(*args, **kwargs)
Return an iterable of keys from MimicDB.
def list(self, *args, **kwargs): """Return an iterable of keys from MimicDB. :param boolean force: If true, API call is forced to S3 """ if kwargs.pop('force', None): headers = kwargs.get('headers', args[4] if len(args) > 4 else None) or dict() headers['force'] =...
If force is in the headers retrieve the list of keys from S3. Otherwise use the list () function to retrieve the keys from MimicDB.
def _get_all(self, *args, **kwargs): """If 'force' is in the headers, retrieve the list of keys from S3. Otherwise, use the list() function to retrieve the keys from MimicDB. """ headers = kwargs.get('headers', args[2] if len(args) > 2 else None) or dict() if 'force' in headers:...
Sync a bucket.
def sync(self): """Sync a bucket. Force all API calls to S3 and populate the database with the current state of S3. """ for key in mimicdb.backend.smembers(tpl.bucket % self.name): mimicdb.backend.delete(tpl.key % (self.name, key)) mimicdb.backend.delete(tpl.bucket ...
Nuclear norm
def nucnorm(x, rho, penalty, newshape=None): """ Nuclear norm Parameters ---------- penalty : float nuclear norm penalty hyperparameter newshape : tuple, optional Desired shape of the parameters to apply the nuclear norm to. The given parameters are reshaped to an array...
Proximal operator for the l1 - norm: soft thresholding
def sparse(x, rho, penalty): """ Proximal operator for the l1-norm: soft thresholding Parameters ---------- penalty : float Strength or weight on the l1-norm """ lmbda = penalty / rho return (x - lmbda) * (x >= lmbda) + (x + lmbda) * (x <= -lmbda)
Minimize the proximal operator of a given objective using L - BFGS
def lbfgs(x, rho, f_df, maxiter=20): """ Minimize the proximal operator of a given objective using L-BFGS Parameters ---------- f_df : function Returns the objective and gradient of the function to minimize maxiter : int Maximum number of L-BFGS iterations """ def f_df...
Applies a smoothing operator along one dimension
def smooth(x, rho, penalty, axis=0, newshape=None): """ Applies a smoothing operator along one dimension currently only accepts a matrix as input Parameters ---------- penalty : float axis : int, optional Axis along which to apply the smoothing (Default: 0) newshape : tuple, ...
Projection onto the semidefinite cone
def sdcone(x, rho): """Projection onto the semidefinite cone""" U, V = np.linalg.eigh(x) return V.dot(np.diag(np.maximum(U, 0)).dot(V.T))
Projection onto the probability simplex
def simplex(x, rho): """ Projection onto the probability simplex http://arxiv.org/pdf/1309.1541v1.pdf """ # sort the elements in descending order u = np.flipud(np.sort(x.ravel())) lambdas = (1 - np.cumsum(u)) / (1. + np.arange(u.size)) ix = np.where(u + lambdas > 0)[0].max() return...
Applies a proximal operator to the columns of a matrix
def columns(x, rho, proxop): """Applies a proximal operator to the columns of a matrix""" xnext = np.zeros_like(x) for ix in range(x.shape[1]): xnext[:, ix] = proxop(x[:, ix], rho) return xnext
Projection onto the fantope [ 1 ] _
def fantope(x, rho, dim, tol=1e-4): """ Projection onto the fantope [1]_ .. [1] Vu, Vincent Q., et al. "Fantope projection and selection: A near-optimal convex relaxation of sparse PCA." Advances in neural information processing systems. 2013. """ U, V = np.linalg.eigh(x) ...
Turns a coroutine into a gradient based optimizer.
def gradient_optimizer(coro): """Turns a coroutine into a gradient based optimizer.""" class GradientOptimizer(Optimizer): @wraps(coro) def __init__(self, *args, **kwargs): self.algorithm = coro(*args, **kwargs) self.algorithm.send(None) self.operators = [] ...
Adds a proximal operator to the list of operators
def add(self, operator, *args): """Adds a proximal operator to the list of operators""" if isinstance(operator, str): op = getattr(proxops, operator)(*args) elif isinstance(operator, proxops.ProximalOperatorBaseClass): op = operator else: raise ValueE...
Set key attributes to retrived metadata. Might be extended in the future to support more attributes.
def _load_meta(self, size, md5): """Set key attributes to retrived metadata. Might be extended in the future to support more attributes. """ if not hasattr(self, 'local_hashes'): self.local_hashes = {} self.size = int(size) if (re.match('^[a-fA-F0-9]{32}$', ...
Key name can be set by Key. key or Key. name. Key. key sets Key. name internally so just handle this property. When changing the key name try to load it s metadata from MimicDB. If it s not available the key hasn t been uploaded downloaded or synced so don t add it to the bucket set ( it also might have just been delet...
def name(self, value): """Key name can be set by Key.key or Key.name. Key.key sets Key.name internally, so just handle this property. When changing the key name, try to load it's metadata from MimicDB. If it's not available, the key hasn't been uploaded, downloaded or synced so don't add...
Called internally for any type of upload. After upload finishes make sure the key is in the bucket set and save the metadata.
def _send_file_internal(self, *args, **kwargs): """Called internally for any type of upload. After upload finishes, make sure the key is in the bucket set and save the metadata. """ super(Key, self)._send_file_internal(*args, **kwargs) mimicdb.backend.sadd(tpl.bucket % self.buck...
Memoizes an objective + gradient function and splits it into two functions that return just the objective and gradient respectively.
def wrap(f_df, xref, size=1): """ Memoizes an objective + gradient function, and splits it into two functions that return just the objective and gradient, respectively. Parameters ---------- f_df : function Must be unary (takes a single argument) xref : list, dict, or array_like ...
Decorates a function with the given docstring
def docstring(docstr): """ Decorates a function with the given docstring Parameters ---------- docstr : string """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.__doc__ = docstr return wrapper...
A simple implementation of a least recently used ( LRU ) cache. Memoizes the recent calls of a computationally intensive function.
def lrucache(func, size): """ A simple implementation of a least recently used (LRU) cache. Memoizes the recent calls of a computationally intensive function. Parameters ---------- func : function Must be unary (takes a single argument) size : int The size of the cache (num...
Compares the numerical gradient to the analytic gradient
def check_grad(f_df, xref, stepsize=1e-6, tol=1e-6, width=15, style='round', out=sys.stdout): """ Compares the numerical gradient to the analytic gradient Parameters ---------- f_df : function The analytic objective and gradient function to check x0 : array_like Parameter value...
Evaluate the files identified for checksum.
def evaluate(self, repo, spec, args): """ Evaluate the files identified for checksum. """ status = [] # Do we have to any thing at all? if len(spec['files']) == 0: return status with cd(repo.rootdir): rules = None ...
Check the integrity of the datapackage. json
def evaluate(self, repo, spec, args): """ Check the integrity of the datapackage.json """ status = [] with cd(repo.rootdir): files = spec.get('files', ['*']) resource_files = repo.find_matching_files(files) files = glob2.glob("**/*") ...
Guess the filetype and read the file into row sets
def read_file(self, filename): """ Guess the filetype and read the file into row sets """ #print("Reading file", filename) try: fh = open(filename, 'rb') table_set = any_tableset(fh) # guess the type... except: #traceback.print_exc() ...
Guess schema using messytables
def get_schema(self, filename): """ Guess schema using messytables """ table_set = self.read_file(filename) # Have I been able to read the filename if table_set is None: return [] # Get the first table as rowset row_set = table_...
Calculates a checksum for a Finnish national reference number
def int2fin_reference(n): """Calculates a checksum for a Finnish national reference number""" checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10) if checksum == 10: checksum = 0 return "%s%s" % (n, checksum)
Helper to make sure the given character is valid for a reference number
def iso_reference_valid_char(c, raise_error=True): """Helper to make sure the given character is valid for a reference number""" if c in ISO_REFERENCE_VALID: return True if raise_error: raise ValueError("'%s' is not in '%s'" % (c, ISO_REFERENCE_VALID)) return False
Creates the huge number from ISO alphanumeric ISO reference
def iso_reference_str2int(n): """Creates the huge number from ISO alphanumeric ISO reference""" n = n.upper() numbers = [] for c in n: iso_reference_valid_char(c) if c in ISO_REFERENCE_VALID_NUMERIC: numbers.append(c) else: numbers.append(str(iso_reference...
Validates ISO reference number
def iso_reference_isvalid(ref): """Validates ISO reference number""" ref = str(ref) cs_source = ref[4:] + ref[:4] return (iso_reference_str2int(cs_source) % 97) == 1
Calculates virtual barcode for IBAN account number and ISO reference
def barcode(iban, reference, amount, due=None): """Calculates virtual barcode for IBAN account number and ISO reference Arguments: iban {string} -- IBAN formed account number reference {string} -- ISO 11649 creditor reference amount {decimal.Decimal} -- Amount in euros, 0.01 - 999999.99...
Add a normal file including its source
def add_file_normal(f, targetdir, generator,script, source): """ Add a normal file including its source """ basename = os.path.basename(f) if targetdir != ".": relativepath = os.path.join(targetdir, basename) else: relativepath = basename relpath = os.path.relpath(f, os.get...
Extract the files to be added based on the includes
def extract_files(filename, includes): """ Extract the files to be added based on the includes """ # Load the execution strace log lines = open(filename).readlines() # Extract only open files - whether for read or write. You often # want to capture the json/ini configuration file as well ...
Run the executable and capture the input and output...
def run_executable(repo, args, includes): """ Run the executable and capture the input and output... """ # Get platform information mgr = plugins_get_mgr() repomgr = mgr.get(what='instrumentation', name='platform') platform_metadata = repomgr.get_metadata() print("Obtaining Commit Info...
Add files to the repository by explicitly specifying them or by specifying a pattern over files accessed during execution of an executable.
def add(repo, args, targetdir, execute=False, generator=False, includes=[], script=False, source=None): """ Add files to the repository by explicitly specifying them or by specifying a pattern over files accessed during execution of an executable. Parameters ---------- ...
For various actions we need files that match patterns
def find_matching_files(self, includes): """ For various actions we need files that match patterns """ if len(includes) == 0: return [] files = [f['relativepath'] for f in self.package['resources']] includes = r'|'.join([fnmatch.translate(x) for x in inclu...
Run a specific command using the manager
def run(self, cmd, *args): """ Run a specific command using the manager """ if self.manager is None: raise Exception("Fatal internal error: Missing repository manager") if cmd not in dir(self.manager): raise Exception("Fatal internal error: Invalid command...
Get metadata for a given file
def get_resource(self, p): """ Get metadata for a given file """ for r in self.package['resources']: if r['relativepath'] == p: r['localfullpath'] = os.path.join(self.rootdir, p) return r raise Exception("Invalid path")
Lookup all available repos
def lookup(self, username=None, reponame=None, key=None): """ Lookup all available repos """ if key is None: key = self.key(username, reponame) if key not in self.repos: raise UnknownRepository() return self.repos[key]
Working directory for the repo
def rootdir(self, username, reponame, create=True): """ Working directory for the repo """ path = os.path.join(self.workspace, 'datasets', username, reponame) if create: try: ...
Add repo to the internal lookup table...
def add(self, repo): """ Add repo to the internal lookup table... """ key = self.key(repo.username, repo.reponame) repo.key = key self.repos[key] = repo return key
Lookup a repo based on username reponame
def lookup(username, reponame): """ Lookup a repo based on username reponame """ mgr = plugins_get_mgr() # XXX This should be generalized to all repo managers. repomgr = mgr.get(what='repomanager', name='git') repo = repomgr.lookup(username=username, reponame=re...
List repos
def list_repos(remote=False): """ List repos Parameters ---------- remote: Flag """ mgr = plugins_get_mgr() if not remote: repomgr = mgr.get(what='repomanager', name='git') repos = repomgr.get_repo_list() repos.sort() return repos else: rais...
Run a shell command within the repo s context
def shellcmd(repo, args): """ Run a shell command within the repo's context Parameters ---------- repo: Repository object args: Shell command """ with cd(repo.rootdir): result = run(args) return result
Check if the datapackage exists...
def datapackage_exists(repo): """ Check if the datapackage exists... """ datapath = os.path.join(repo.rootdir, "datapackage.json") return os.path.exists(datapath)
Delete files
def delete(repo, args=[]): """ Delete files Parameters ---------- repo: Repository object args: Arguments to git command """ # Remove the files result = generic_repo_cmd(repo, 'delete', args) if result['status'] != 'success': return status with cd(repo.rootdir)...
Create the datapackage file..
def bootstrap_datapackage(repo, force=False, options=None, noinput=False): """ Create the datapackage file.. """ print("Bootstrapping datapackage") # get the directory tsprefix = datetime.now().date().isoformat() # Initial data package json package = OrderedD...
Initialize an empty repository with datapackage. json
def init(username, reponame, setup, force=False, options=None, noinput=False): """ Initialize an empty repository with datapackage.json Parameters ---------- username: Name of the user reponame: Name of the repo setup: Specify the 'configuration' (git only, git+s3 backend...
Clone a URL. Examples include:
def clone(url): """ Clone a URL. Examples include: - git@github.com:pingali/dgit.git - https://github.com:pingali/dgit.git - s3://mybucket/git/pingali/dgit.git Parameters ---------- url: URL of the repo """ backend = None backendmgr = None if url.startswit...
Update metadata with the content of the files
def annotate_metadata_data(repo, task, patterns=["*"], size=0): """ Update metadata with the content of the files """ mgr = plugins_get_mgr() keys = mgr.search('representation')['representation'] representations = [mgr.get_by_key('representation', k) for k in keys] matching_files = repo.f...
Update metadata with the commit information
def annotate_metadata_code(repo, files): """ Update metadata with the commit information """ package = repo.package package['code'] = [] for p in files: matching_files = glob2.glob("**/{}".format(p)) for f in matching_files: absf = os.path.abspath(f) prin...
Update metadata with the action history
def annotate_metadata_action(repo): """ Update metadata with the action history """ package = repo.package print("Including history of actions") with cd(repo.rootdir): filename = ".dgit/log.json" if os.path.exists(filename): history = open(...
Update metadata host information
def annotate_metadata_platform(repo): """ Update metadata host information """ print("Added platform information") package = repo.package mgr = plugins_get_mgr() repomgr = mgr.get(what='instrumentation', name='platform') package['platform'] = repomgr.get_metadata()
Collect information from the dependent repo s
def annotate_metadata_dependencies(repo): """ Collect information from the dependent repo's """ options = repo.options if 'dependencies' not in options: print("No dependencies") return [] repos = [] dependent_repos = options['dependencies'] for d in dependent_repos: ...
Post to metadata server
def post(repo, args=[]): """ Post to metadata server Parameters ---------- repo: Repository object (result of lookup) """ mgr = plugins_get_mgr() keys = mgr.search(what='metadata') keys = keys['metadata'] if len(keys) == 0: return # Incorporate pipeline informati...
Show details of available plugins
def plugins_show(what=None, name=None, version=None, details=False): """ Show details of available plugins Parameters ---------- what: Class of plugins e.g., backend name: Name of the plugin e.g., s3 version: Version of the plugin details: Show details be shown? """ global plug...
Load all plugins from dgit extension
def discover_all_plugins(self): """ Load all plugins from dgit extension """ for v in pkg_resources.iter_entry_points('dgit.plugins'): m = v.load() m.setup(self)
Registering a plugin
def register(self, what, obj): """ Registering a plugin Params ------ what: Nature of the plugin (backend, instrumentation, repo) obj: Instance of the plugin """ # print("Registering pattern", name, pattern) name = obj.name version = obj.v...
Search for a plugin
def search(self, what, name=None, version=None): """ Search for a plugin """ filtered = {} # The search may for a scan (what is None) or if what is None: whats = list(self.plugins.keys()) elif what is not None: if what not in self.plugins:...
Gather configuration requirements of all plugins
def gather_configs(self): """ Gather configuration requirements of all plugins """ configs = [] for what in self.order: for key in self.plugins[what]: mgr = self.plugins[what][key] c = mgr.config(what='get') if c is not ...
Gather configuration requirements of all plugins
def update_configs(self, config): """ Gather configuration requirements of all plugins """ for what in self.plugins: # backend, repo etc. for key in self.plugins[what]: # s3, filesystem etc. # print("Updating configuration of", what, key) self...
Receives the serial data into the self. _raw buffer: return:
def run(self): """ Receives the serial data into the self._raw buffer :return: """ run_once = True while (run_once or self._threaded) and self.end is False: self.service_tx_queue() self.parse_messages() run_once = False if...
Instantiate the validation specification
def instantiate(repo, validator_name=None, filename=None, rulesfiles=None): """ Instantiate the validation specification """ default_validators = repo.options.get('validator', {}) validators = {} if validator_name is not None: # Handle the case validator is specified.. if valid...
Validate the content of the files for consistency. Validators can look as deeply as needed into the files. dgit treats them all as black boxes.
def validate(repo, validator_name=None, filename=None, rulesfiles=None, args=[]): """ Validate the content of the files for consistency. Validators can look as deeply as needed into the files. dgit treats them all as black boxes. Parameters ...
Check if a URL exists
def url_is_valid(self, url): """ Check if a URL exists """ # Check if the file system path exists... if url.startswith("file://"): url = url.replace("file://","") return os.path.exists(url)
Post to the metadata server
def post(self, repo): """ Post to the metadata server Parameters ---------- repo """ datapackage = repo.package url = self.url token = self.token headers = { 'Authorization': 'Token {}'.format(token), 'Content-Ty...
imports and returns module class from path. to. module. Class argument
def get_module_class(class_path): """ imports and returns module class from ``path.to.module.Class`` argument """ mod_name, cls_name = class_path.rsplit('.', 1) try: mod = import_module(mod_name) except ImportError as ex: raise EvoStreamException('Error importing module %s: ...
Find max 5 executables that are responsible for this repo.
def find_executable_files(): """ Find max 5 executables that are responsible for this repo. """ files = glob.glob("*") + glob.glob("*/*") + glob.glob('*/*/*') files = filter(lambda f: os.path.isfile(f), files) executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH final = [] for filenam...
Initialize a repo - specific configuration file to execute dgit
def auto_init(autofile, force_init=False): """ Initialize a repo-specific configuration file to execute dgit Parameters ---------- autofile: Repo-specific configuration file (dgit.json) force_init: Flag to force to re-initialization of the configuration file """ if os.path.exists(aut...
Automatically get repo
def auto_get_repo(autooptions, debug=False): """ Automatically get repo Parameters ---------- autooptions: dgit.json content """ # plugin manager pluginmgr = plugins_get_mgr() # get the repo manager repomgr = pluginmgr.get(what='repomanager', name='git') repo = None ...
Look through the local directory to pick up files to check
def get_files_to_commit(autooptions): """ Look through the local directory to pick up files to check """ workingdir = autooptions['working-directory'] includes = autooptions['track']['includes'] excludes = autooptions['track']['excludes'] # transform glob patterns to regular expressions ...
Cleanup the paths and add
def auto_add(repo, autooptions, files): """ Cleanup the paths and add """ # Get the mappings and keys. mapping = { ".": "" } if (('import' in autooptions) and ('directory-mapping' in autooptions['import'])): mapping = autooptions['import']['directory-mapping'] # Apply the lo...