INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Horn Schunck legacy OpenCV function requires we use these old - fashioned cv matrices not numpy array | def setupuv(rc):
"""
Horn Schunck legacy OpenCV function requires we use these old-fashioned cv matrices, not numpy array
"""
if cv is not None:
(r, c) = rc
u = cv.CreateMat(r, c, cv.CV_32FC1)
v = cv.CreateMat(r, c, cv.CV_32FC1)
return (u, v)
else:
return [Non... |
Initialize a CatDict object checking for errors. | def _init_cat_dict(self, cat_dict_class, key_in_self, **kwargs):
"""Initialize a CatDict object, checking for errors.
"""
# Catch errors associated with crappy, but not unexpected data
try:
new_entry = cat_dict_class(self, key=key_in_self, **kwargs)
except CatDictErro... |
Add a CatDict to this Entry if initialization succeeds and it doesn t already exist within the Entry. | def _add_cat_dict(self,
cat_dict_class,
key_in_self,
check_for_dupes=True,
**kwargs):
"""Add a CatDict to this Entry if initialization succeeds and it
doesn't already exist within the Entry.
"""
# Try... |
Wrapper for tqdm progress bar. | def pbar(iter, desc='', **kwargs):
"""Wrapper for `tqdm` progress bar.
"""
return tqdm(
iter,
desc=('<' + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '> ' +
desc),
dynamic_ncols=True,
**kwargs) |
Wrapper for tqdm progress bar which also sorts list of strings | def pbar_strings(files, desc='', **kwargs):
"""Wrapper for `tqdm` progress bar which also sorts list of strings
"""
return tqdm(
sorted(files, key=lambda s: s.lower()),
desc=('<' + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '> ' +
desc),
dynamic_ncols=True,
... |
Get the task priority corresponding to the given task_priority. | def _get_task_priority(tasks, task_priority):
"""Get the task `priority` corresponding to the given `task_priority`.
If `task_priority` is an integer or 'None', return it.
If `task_priority` is a str, return the priority of the task it matches.
Otherwise, raise `ValueError`.
"""
if task_priorit... |
Run all of the import tasks. | def import_data(self):
"""Run all of the import tasks.
This is executed by the 'scripts.main.py' when the module is run as an
executable. This can also be run as a method, in which case default
arguments are loaded, but can be overriden using `**kwargs`.
"""
tasks_list ... |
Load the list of tasks in this catalog s input/ tasks. json file. | def load_task_list(self):
"""Load the list of tasks in this catalog's 'input/tasks.json' file.
A `Task` object is created for each entry, with the parameters filled
in. These are placed in an OrderedDict, sorted by the `priority`
parameter, with positive values and then negative values,... |
Find an existing entry in or add a new one to the entries dict. | def add_entry(self, name, load=True, delete=True):
"""Find an existing entry in, or add a new one to, the `entries` dict.
FIX: rename to `create_entry`???
Returns
-------
entries : OrderedDict of Entry objects
newname : str
Name of matching entry found in `e... |
Return the first entry name with the given alias included in its list of aliases. | def find_entry_name_of_alias(self, alias):
"""Return the first entry name with the given 'alias' included in its
list of aliases.
Returns
-------
name of matching entry (str) or 'None' if no matches
"""
if alias in self.aliases:
name = self.aliases[a... |
Used by merge_duplicates | def copy_entry_to_entry(self,
fromentry,
destentry,
check_for_dupes=True,
compare_to_existing=True):
"""Used by `merge_duplicates`
"""
self.log.info("Copy entry object '{}' to '{}'".fo... |
Merge and remove duplicate entries. | def merge_duplicates(self):
"""Merge and remove duplicate entries.
Compares each entry ('name') in `stubs` to all later entries to check
for duplicates in name or alias. If a duplicate is found, they are
merged and written to file.
"""
if len(self.entries) == 0:
... |
Load all events in their stub ( name alias etc only ) form. | def load_stubs(self, log_mem=False):
"""Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode.
"""
# Initialize parameter related to diagnostic output of memory usage
if log_mem:
import psutil
process = psutil.Process(os.getp... |
Delete the file associated with the given entry. | def _delete_entry_file(self, entry_name=None, entry=None):
"""Delete the file associated with the given entry.
"""
if entry_name is None and entry is None:
raise RuntimeError("Either `entry_name` or `entry` must be given.")
elif entry_name is not None and entry is not None:
... |
Write all entries in entries to files and clear. Depending on arguments and tasks. | def journal_entries(self,
clear=True,
gz=False,
bury=False,
write_stubs=False,
final=False):
"""Write all entries in `entries` to files, and clear. Depending on
arguments and `tasks`.... |
Choose between each entries given name and its possible aliases for the best one. | def set_preferred_names(self):
"""Choose between each entries given name and its possible aliases for
the best one.
"""
if len(self.entries) == 0:
self.log.error("WARNING: `entries` is empty, loading stubs")
self.load_stubs()
task_str = self.get_current_t... |
Get a list of files which should be added to the given repository. | def _prep_git_add_file_list(self,
repo,
size_limit,
fail=True,
file_types=None):
"""Get a list of files which should be added to the given repository.
Notes
-----
... |
Load the given URL or a cached - version. | def load_url(self,
url,
fname,
repo=None,
timeout=120,
post=None,
fail=False,
write=True,
json_sort=None,
cache_only=False,
archived_mode=None,
... |
Download text from the given url. | def download_url(self, url, timeout, fail=False, post=None, verify=True):
"""Download text from the given url.
Returns `None` on failure.
Arguments
---------
self
url : str
URL web address to download.
timeout : int
Duration after which U... |
Merge the source alias lists of two CatDicts. | def append_sources_from(self, other):
"""Merge the source alias lists of two CatDicts."""
# Get aliases lists from this `CatDict` and other
self_aliases = self[self._KEYS.SOURCE].split(',')
other_aliases = other[self._KEYS.SOURCE].split(',')
# Store alias to `self`
self[... |
Name of current action for progress - bar output. | def current_task(self, args):
"""Name of current action for progress-bar output.
The specific task string is depends on the configuration via `args`.
Returns
-------
ctask : str
String representation of this task.
"""
ctask = self.nice_name if self.n... |
Whether previously archived data should be loaded. | def load_archive(self, args):
"""Whether previously archived data should be loaded.
"""
import warnings
warnings.warn("`Task.load_archive()` is deprecated! "
"`Catalog.load_url` handles the same functionality.")
return self.archived or args.archived |
Use git rev - parse HEAD <REPO > to get current SHA. | def get_sha(path=None, log=None, short=False, timeout=None):
"""Use `git rev-parse HEAD <REPO>` to get current SHA.
"""
# git_command = "git rev-parse HEAD {}".format(repo_name).split()
# git_command = "git rev-parse HEAD".split()
git_command = ["git", "rev-parse"]
if short:
git_command.... |
Add all files in each data repository tree commit push. | def git_add_commit_push_all_repos(cat):
"""Add all files in each data repository tree, commit, push.
Creates a commit message based on the current catalog version info.
If either the `git add` or `git push` commands fail, an error will be
raised. Currently, if `commit` fails an error *WILL NOT* be ra... |
Perform a git pull in each data repository. | def git_pull_all_repos(cat, strategy_recursive=True, strategy='theirs'):
"""Perform a 'git pull' in each data repository.
> `git pull -s recursive -X theirs`
"""
# raise RuntimeError("THIS DOESNT WORK YET!")
log = cat.log
log.debug("gitter.git_pull_all_repos()")
log.warning("WARNING: using ... |
Perform a git clone for each data repository that doesnt exist. | def git_clone_all_repos(cat):
"""Perform a 'git clone' for each data repository that doesnt exist.
"""
log = cat.log
log.debug("gitter.git_clone_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
out_repos = cat.PATHS.get_repo_output_folders()
for repo in all_repos:
log.info... |
Perform a git reset in each data repository. | def git_reset_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git reset' in each data repository.
"""
log = cat.log
log.debug("gitter.git_reset_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
for repo in all_repos:
log.warning("Repo in: '{}'".format(repo))
... |
Perform a git status in each data repository. | def git_status_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git status' in each data repository.
"""
log = cat.log
log.debug("gitter.git_status_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
for repo_name in all_repos:
log.info("Repo in: '{}'".format(re... |
Given a list of repositories make sure they re all cloned. | def clone(repo, log, depth=1):
"""Given a list of repositories, make sure they're all cloned.
Should be called from the subclassed `Catalog` objects, passed a list
of specific repository names.
Arguments
---------
all_repos : list of str
*Absolute* path specification of each target rep... |
Use subprocess to call a command in a certain ( repo ) directory. | def _call_command_in_repo(comm, repo, log, fail=False, log_flag=True):
"""Use `subprocess` to call a command in a certain (repo) directory.
Logs the output (both `stderr` and `stdout`) to the log, and checks the
return codes to make sure they're valid. Raises error if not.
Raises
------
excep... |
Check that spectrum has legal combination of attributes. | def _check(self):
"""Check that spectrum has legal combination of attributes."""
# Run the super method
super(Spectrum, self)._check()
err_str = None
has_data = self._KEYS.DATA in self
has_wave = self._KEYS.WAVELENGTHS in self
has_flux = self._KEYS.FLUXES in self... |
Check if spectrum is duplicate of another. | def is_duplicate_of(self, other):
"""Check if spectrum is duplicate of another."""
if super(Spectrum, self).is_duplicate_of(other):
return True
row_matches = 0
for ri, row in enumerate(self.get(self._KEYS.DATA, [])):
lambda1, flux1 = tuple(row[0:2])
if... |
Logic for sorting keys in a Spectrum relative to one another. | def sort_func(self, key):
"""Logic for sorting keys in a `Spectrum` relative to one another."""
if key == self._KEYS.TIME:
return 'aaa'
if key == self._KEYS.DATA:
return 'zzy'
if key == self._KEYS.SOURCE:
return 'zzz'
return key |
Sorting logic for Quantity objects. | def sort_func(self, key):
"""Sorting logic for `Quantity` objects."""
if key == self._KEYS.VALUE:
return 'aaa'
if key == self._KEYS.SOURCE:
return 'zzz'
return key |
Return this class s attribute names ( those not stating with _ ). | def keys(cls):
"""Return this class's attribute names (those not stating with '_').
Also retrieves the attributes from base classes, e.g.
For: ``ENTRY(KeyCollection)``, ``ENTRY.keys()`` gives just the
attributes of `ENTRY` (`KeyCollection` has no keys).
For: ``SUPERNOVA(ENT... |
Return this class s attribute values ( those not stating with _ ). | def vals(cls):
"""Return this class's attribute values (those not stating with '_').
Returns
-------
_vals : list of objects
List of values of internal attributes. Order is effectiely random.
"""
if cls._vals:
return cls._vals
# If `_val... |
Return this class s attribute values ( those not stating with _ ) but only for attributes with compare set to True. | def compare_vals(cls, sort=True):
"""Return this class's attribute values (those not stating with '_'),
but only for attributes with `compare` set to `True`.
Returns
-------
_compare_vals : list of objects
List of values of internal attributes to use when comparing
... |
Return a pretty string representation of this Key. | def pretty(self):
"""Return a 'pretty' string representation of this `Key`.
note: do not override the builtin `__str__` or `__repr__` methods!
"""
retval = ("Key(name={}, type={}, listable={}, compare={}, "
"priority={}, kind_preference={}, "
"replace... |
Make sure given value is consistent with this Key specification. | def check(self, val):
"""Make sure given value is consistent with this `Key` specification.
NOTE: if `type` is 'None', then `listable` also is *not* checked.
"""
# If there is no `type` requirement, everything is allowed
if self.type is None:
return True
is_... |
Create a standard logger object which logs to file and or stdout stream. | def get_logger(name=None, stream_fmt=None, file_fmt=None, date_fmt=None,
stream_level=None, file_level=None,
tofile=None, tostr=True):
"""Create a standard logger object which logs to file and or stdout stream.
If a logger has already been created in this session, it is returned
... |
Log an error message and raise an error. | def log_raise(log, err_str, err_type=RuntimeError):
"""Log an error message and raise an error.
Arguments
---------
log : `logging.Logger` object
err_str : str
Error message to be logged and raised.
err_type : `Exception` object
Type of error to raise.
"""
log.error(err... |
Log the current memory usage. | def log_memory(log, pref=None, lvl=logging.DEBUG, raise_flag=True):
"""Log the current memory usage.
"""
import os
import sys
cyc_str = ""
KB = 1024.0
if pref is not None:
cyc_str += "{}: ".format(pref)
# Linux returns units in Bytes; OSX in kilobytes
UNIT = KB*KB if sys.pla... |
img: can be RGB ( MxNx3 ) or gray ( MxN ) http:// docs. opencv. org/ master/ modules/ features2d/ doc/ drawing_function_of_keypoints_and_matches. html http:// docs. opencv. org/ trunk/ modules/ features2d/ doc/ drawing_function_of_keypoints_and_matches. html | def doblob(morphed, blobdet, img, anno=True):
"""
img: can be RGB (MxNx3) or gray (MxN)
http://docs.opencv.org/master/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html
http://docs.opencv.org/trunk/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html
"""
keypo... |
Parse arguments and return configuration settings. | def load_args(self, args, clargs):
"""Parse arguments and return configuration settings.
"""
# Parse All Arguments
args = self.parser.parse_args(args=clargs, namespace=args)
# Print the help information if no subcommand is given
# subcommand is required for operation
... |
Create argparse instance and setup with appropriate parameters. | def _setup_argparse(self):
"""Create `argparse` instance, and setup with appropriate parameters.
"""
parser = argparse.ArgumentParser(
prog='catalog', description='Parent Catalog class for astrocats.')
subparsers = parser.add_subparsers(
description='valid subcom... |
Create parser for import subcommand and associated arguments. | def _add_parser_arguments_import(self, subparsers):
"""Create parser for 'import' subcommand, and associated arguments.
"""
import_pars = subparsers.add_parser(
"import", help="Import data.")
import_pars.add_argument(
'--update', '-u', dest='update',
... |
Create a sub - parsers for git subcommands. | def _add_parser_arguments_git(self, subparsers):
"""Create a sub-parsers for git subcommands.
"""
subparsers.add_parser(
"git-clone",
help="Clone all defined data repositories if they dont exist.")
subparsers.add_parser(
"git-push",
help="... |
Create a parser for the analyze subcommand. | def _add_parser_arguments_analyze(self, subparsers):
"""Create a parser for the 'analyze' subcommand.
"""
lyze_pars = subparsers.add_parser(
"analyze",
help="Perform basic analysis on this catalog.")
lyze_pars.add_argument(
'--count', '-c', dest='coun... |
Compress the file with the given name and delete the uncompressed file. | def compress_gz(fname):
"""Compress the file with the given name and delete the uncompressed file.
The compressed filename is simply the input filename with '.gz' appended.
Arguments
---------
fname : str
Name of the file to compress and delete.
Returns
-------
comp_fname : st... |
draws flow vectors on image this came from opencv/ examples directory another way: http:// docs. opencv. org/ trunk/ doc/ py_tutorials/ py_gui/ py_drawing_functions/ py_drawing_functions. html | def draw_flow(img, flow, step=16, dtype=uint8):
"""
draws flow vectors on image
this came from opencv/examples directory
another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html
"""
maxval = iinfo(img.dtype).max
# scaleFact = 1. #arbit... |
mag must be uint8 uint16 uint32 and 2 - D ang is in radians ( float ) | def draw_hsv(mag, ang, dtype=uint8, fn=None):
"""
mag must be uint8, uint16, uint32 and 2-D
ang is in radians (float)
"""
assert mag.shape == ang.shape
assert mag.ndim == 2
maxval = iinfo(dtype).max
hsv = dstack(((degrees(ang)/2).astype(dtype), # /2 to keep less than 255
... |
flow dimensions y x 2 3 - D. flow [... 0 ] is magnitude flow [... 1 ] is angle | def flow2magang(flow, dtype=uint8):
"""
flow dimensions y,x,2 3-D. flow[...,0] is magnitude, flow[...,1] is angle
"""
fx, fy = flow[..., 0], flow[..., 1]
return hypot(fx, fy).astype(dtype), arctan2(fy, fx) + pi |
dir One of IOC_NONE IOC_WRITE IOC_READ or IOC_READ|IOC_WRITE. Direction is from the application s point of view not kernel s. size ( 14 - bits unsigned integer ) Size of the buffer passed to ioctl s arg argument. | def IOC(dir, type, nr, size):
"""
dir
One of IOC_NONE, IOC_WRITE, IOC_READ, or IOC_READ|IOC_WRITE.
Direction is from the application's point of view, not kernel's.
size (14-bits unsigned integer)
Size of the buffer passed to ioctl's "arg" argument.
"""
assert dir <= _IOC_DIRM... |
Returns the size of given type and check its suitability for use in an ioctl command number. | def IOC_TYPECHECK(t):
"""
Returns the size of given type, and check its suitability for use in an
ioctl command number.
"""
result = ctypes.sizeof(t)
assert result <= _IOC_SIZEMASK, result
return result |
An ioctl with read parameters. | def IOR(type, nr, size):
"""
An ioctl with read parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
"""
return IOC(IOC_READ, type, nr, IOC_TYPECHECK(size)) |
An ioctl with write parameters. | def IOW(type, nr, size):
"""
An ioctl with write parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
"""
return IOC(IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
An ioctl with both read an writes parameters. | def IOWR(type, nr, size):
"""
An ioctl with both read an writes parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
"""
return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
Get a path including only the trailing num directories. | def _get_last_dirs(path, num=1):
"""Get a path including only the trailing `num` directories.
Returns
-------
last_path : str
"""
head, tail = os.path.split(path)
last_path = str(tail)
for ii in range(num):
head, tail = os.path.split(head)
last_path = os.path.join(tail,... |
Run the analysis routines determined from the given args. | def analyze(self, args):
"""Run the analysis routines determined from the given `args`.
"""
self.log.info("Running catalog analysis")
if args.count:
self.count()
return |
Analyze the counts of... things. | def count(self):
"""Analyze the counts of ...things.
Returns
-------
retvals : dict
Dictionary of 'property-name: counts' pairs for further processing
"""
self.log.info("Running 'count'")
retvals = {}
# Numbers of 'tasks'
num_tasks =... |
Count the number of tasks both in the json and directory. | def _count_tasks(self):
"""Count the number of tasks, both in the json and directory.
Returns
-------
num_tasks : int
The total number of all tasks included in the `tasks.json` file.
"""
self.log.warning("Tasks:")
tasks, task_names = self.catalog._lo... |
Count the number of files in the data repositories. | def _count_repo_files(self):
"""Count the number of files in the data repositories.
`_COUNT_FILE_TYPES` are used to determine which file types are checked
explicitly.
`_IGNORE_FILES` determine which files are ignored in (most) counts.
Returns
-------
repo_files ... |
Construct a string showing the number of different file types. | def _file_nums_str(self, n_all, n_type, n_ign):
"""Construct a string showing the number of different file types.
Returns
-------
f_str : str
"""
# 'other' is the difference between all and named
n_oth = n_all - np.sum(n_type)
f_str = "{} Files".format(n... |
Count files in the given path with the given pattern. | def _count_files_by_type(self, path, pattern, ignore=True):
"""Count files in the given path, with the given pattern.
If `ignore = True`, skip files in the `_IGNORE_FILES` list.
Returns
-------
num_files : int
"""
# Get all files matching the given path and pat... |
Given a URL try to find the ADS bibcode. | def bibcode_from_url(cls, url):
"""Given a URL, try to find the ADS bibcode.
Currently: only `ads` URLs will work, e.g.
Returns
-------
code : str or 'None'
The Bibcode if found, otherwise 'None'
"""
try:
code = url.split('/abs/')
... |
Return the path that this Entry should be saved to. | def _get_save_path(self, bury=False):
"""Return the path that this Entry should be saved to."""
filename = self.get_filename(self[self._KEYS.NAME])
# Put objects that shouldn't belong in this catalog in the boneyard
if bury:
outdir = self.catalog.get_repo_boneyard()
... |
Convert the object into a plain OrderedDict. | def _ordered(self, odict):
"""Convert the object into a plain OrderedDict."""
ndict = OrderedDict()
if isinstance(odict, CatDict) or isinstance(odict, Entry):
key = odict.sort_func
else:
key = None
nkeys = list(sorted(odict.keys(), key=key))
for ... |
Return a unique hash associated with the listed keys. | def get_hash(self, keys=[]):
"""Return a unique hash associated with the listed keys."""
if not len(keys):
keys = list(self.keys())
string_rep = ''
oself = self._ordered(deepcopy(self))
for key in keys:
string_rep += json.dumps(oself.get(key, ''), sort_ke... |
Clean quantity value before it is added to entry. | def _clean_quantity(self, quantity):
"""Clean quantity value before it is added to entry."""
value = quantity.get(QUANTITY.VALUE, '').strip()
error = quantity.get(QUANTITY.E_VALUE, '').strip()
unit = quantity.get(QUANTITY.U_VALUE, '').strip()
kind = quantity.get(QUANTITY.KIND, ''... |
Convert OrderedDict into Entry or its derivative classes. | def _convert_odict_to_classes(self,
data,
clean=False,
merge=True,
pop_schema=True,
compare_to_existing=True,
filter... |
Check that a source exists and that a quantity isn t erroneous. | def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs):
"""Check that a source exists and that a quantity isn't erroneous."""
# Make sure that a source is given
source = kwargs.get(cat_dict_class._KEYS.SOURCE, None)
if source is None:
raise CatDictError(
... |
Add a CatDict to this Entry. | def _add_cat_dict(self,
cat_dict_class,
key_in_self,
check_for_dupes=True,
compare_to_existing=True,
**kwargs):
"""Add a `CatDict` to this `Entry`.
CatDict only added if initialization succeeds... |
Construct a new Entry instance from an input file. | def init_from_file(cls,
catalog,
name=None,
path=None,
clean=False,
merge=True,
pop_schema=True,
ignore_keys=[],
compare_to_existing=Tru... |
Add an alias optionally cleaning the alias string. | def add_alias(self, alias, source, clean=True):
"""Add an alias, optionally 'cleaning' the alias string.
Calls the parent `catalog` method `clean_entry_name` - to apply the
same name-cleaning as is applied to entry names themselves.
Returns
-------
alias : str
... |
Add an Error instance to this entry. | def add_error(self, value, **kwargs):
"""Add an `Error` instance to this entry."""
kwargs.update({ERROR.VALUE: value})
self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs)
return |
Add a Photometry instance to this entry. | def add_photometry(self, compare_to_existing=True, **kwargs):
"""Add a `Photometry` instance to this entry."""
self._add_cat_dict(
Photometry,
self._KEYS.PHOTOMETRY,
compare_to_existing=compare_to_existing,
**kwargs)
return |
Merge two entries that correspond to the same entry. | def merge_dupes(self):
"""Merge two entries that correspond to the same entry."""
for dupe in self.dupe_of:
if dupe in self.catalog.entries:
if self.catalog.entries[dupe]._stub:
# merge = False to avoid infinite recursion
self.catalog.l... |
Add an Quantity instance to this entry. | def add_quantity(self,
quantities,
value,
source,
check_for_dupes=True,
compare_to_existing=True,
**kwargs):
"""Add an `Quantity` instance to this entry."""
success = True
... |
Add a source that refers to the catalog itself. | def add_self_source(self):
"""Add a source that refers to the catalog itself.
For now this points to the Open Supernova Catalog by default.
"""
return self.add_source(
bibcode=self.catalog.OSC_BIBCODE,
name=self.catalog.OSC_NAME,
url=self.catalog.OSC_... |
Add a Source instance to this entry. | def add_source(self, allow_alias=False, **kwargs):
"""Add a `Source` instance to this entry."""
if not allow_alias and SOURCE.ALIAS in kwargs:
err_str = "`{}` passed in kwargs, this shouldn't happen!".format(
SOURCE.ALIAS)
self._log.error(err_str)
rais... |
Add a Model instance to this entry. | def add_model(self, allow_alias=False, **kwargs):
"""Add a `Model` instance to this entry."""
if not allow_alias and MODEL.ALIAS in kwargs:
err_str = "`{}` passed in kwargs, this shouldn't happen!".format(
SOURCE.ALIAS)
self._log.error(err_str)
raise R... |
Add a Spectrum instance to this entry. | def add_spectrum(self, compare_to_existing=True, **kwargs):
"""Add a `Spectrum` instance to this entry."""
spec_key = self._KEYS.SPECTRA
# Make sure that a source is given, and is valid (nor erroneous)
source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs)
if source i... |
Check that the entry has the required fields. | def check(self):
"""Check that the entry has the required fields."""
# Make sure there is a schema key in dict
if self._KEYS.SCHEMA not in self:
self[self._KEYS.SCHEMA] = self.catalog.SCHEMA.URL
# Make sure there is a name key in dict
if (self._KEYS.NAME not in self o... |
Retrieve the aliases of this object as a list of strings. | def get_aliases(self, includename=True):
"""Retrieve the aliases of this object as a list of strings.
Arguments
---------
includename : bool
Include the 'name' parameter in the list of aliases.
"""
# empty list if doesnt exist
alias_quanta = self.get(... |
Retrieve the raw text from a file. | def get_entry_text(self, fname):
"""Retrieve the raw text from a file."""
if fname.split('.')[-1] == 'gz':
with gz.open(fname, 'rt') as f:
filetext = f.read()
else:
with codecs.open(fname, 'r') as f:
filetext = f.read()
return filet... |
Given an alias find the corresponding source in this entry. | def get_source_by_alias(self, alias):
"""Given an alias, find the corresponding source in this entry.
If the given alias doesn't exist (e.g. there are no sources), then a
`ValueError` is raised.
Arguments
---------
alias : str
The str-integer (e.g. '8') of t... |
Get a new Entry which contains the stub of this one. | def get_stub(self):
"""Get a new `Entry` which contains the 'stub' of this one.
The 'stub' is only the name and aliases.
Usage:
-----
To convert a normal entry into a stub (for example), overwrite the
entry in place, i.e.
>>> entries[name] = entries[name].get_st... |
Check if attribute has been marked as being erroneous. | def is_erroneous(self, field, sources):
"""Check if attribute has been marked as being erroneous."""
if self._KEYS.ERRORS in self:
my_errors = self[self._KEYS.ERRORS]
for alias in sources.split(','):
source = self.get_source_by_alias(alias)
bib_err... |
Check if attribute is private. | def is_private(self, key, sources):
"""Check if attribute is private."""
# aliases are always public.
if key == ENTRY.ALIAS:
return False
return all([
SOURCE.PRIVATE in self.get_source_by_alias(x)
for x in sources.split(',')
]) |
Sanitize the data ( sort it etc. ) before writing it to disk. | def sanitize(self):
"""Sanitize the data (sort it, etc.) before writing it to disk.
Template method that can be overridden in each catalog's subclassed
`Entry` object.
"""
name = self[self._KEYS.NAME]
aliases = self.get_aliases(includename=False)
if name not in ... |
Write entry to JSON file in the proper location. | def save(self, bury=False, final=False):
"""Write entry to JSON file in the proper location.
Arguments
---------
bury : bool
final : bool
If this is the 'final' save, perform additional sanitization and
cleaning operations.
"""
outdir, f... |
Used to sort keys when writing Entry to JSON format. | def sort_func(self, key):
"""Used to sort keys when writing Entry to JSON format.
Should be supplemented/overridden by inheriting classes.
"""
if key == self._KEYS.SCHEMA:
return 'aaa'
if key == self._KEYS.NAME:
return 'aab'
if key == self._KEYS.S... |
Set photometry dictionary from a counts measurement. | def set_pd_mag_from_counts(photodict,
c='',
ec='',
lec='',
uec='',
zp=DEFAULT_ZP,
sig=DEFAULT_UL_SIGMA):
"""Set photometry dictionary from a counts measur... |
Set photometry dictionary from a flux density measurement. | def set_pd_mag_from_flux_density(photodict,
fd='',
efd='',
lefd='',
uefd='',
sig=DEFAULT_UL_SIGMA):
"""Set photometry dictionary from a flux density me... |
Check that entry attributes are legal. | def _check(self):
"""Check that entry attributes are legal."""
# Run the super method
super(Photometry, self)._check()
err_str = None
has_flux = self._KEYS.FLUX in self
has_flux_dens = self._KEYS.FLUX_DENSITY in self
has_u_flux = self._KEYS.U_FLUX in self
... |
Specify order for attributes. | def sort_func(self, key):
"""Specify order for attributes."""
if key == self._KEYS.TIME:
return 'aaa'
if key == self._KEYS.MODEL:
return 'zzy'
if key == self._KEYS.SOURCE:
return 'zzz'
return key |
Run migrations in offline mode. | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... |
Run migrations in online mode. | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = create_engine(get_url())
connection = engine.connect()
context.configure(
connection=connection,
target_m... |
return all instances by user name perm name and resource id | def by_resource_user_and_perm(
cls, user_id, perm_name, resource_id, db_session=None
):
"""
return all instances by user name, perm name and resource id
:param user_id:
:param perm_name:
:param resource_id:
:param db_session:
:return:
"""
... |
Get the next sensor while iterating. | def tdSensor(self):
"""Get the next sensor while iterating.
:return: a dict with the keys: protocol, model, id, datatypes.
"""
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(proto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.