code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
json = self.get_basic_json()
if self.onboard_cards:
json['OnboardControllers'] = {
'OnboardController':
[c.get_json() for c in self.onboard_cards.values()]
}
if self.addon_cards:
json['AddOnCards'] = {
... | def get_json(self) | Create JSON data for slot.
:returns: JSON data for slot as follows:
{
"@SlotIdx":0,
"OnboardControllers":{
"OnboardController": [
]
},
"AddOnCards":{
"AddOnCard": [
... | 3.142843 | 2.151972 | 1.460448 |
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses and s... | def get_json(self) | Create JSON data for LANPort.
:returns: JSON data as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"BootProtocol":{
},
"VirtualAddress":{
"MAC":{
... | 5.414191 | 3.114772 | 1.73823 |
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses:
... | def get_json(self) | Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
... | 3.777721 | 2.333171 | 1.619136 |
port = self.get_basic_json()
port['Functions'] = {
'Function': [f.get_json() for f in self.functions.values()]
}
return port | def get_json(self) | Create JSON for CNA port.
:returns: JSON for CNA port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"Functions":{
}
} | 5.883156 | 4.247871 | 1.384966 |
json = self.get_basic_json()
for i in range(len(self.targets)):
# @FCTargetIdx starts from 1.
self.targets[i].set_index(i + 1)
json['FCTargets'] = {
'FCTarget': [t.get_json() for t in self.targets]
}
return {'FCBootEnvironment': json} | def get_json(self) | Create JSON for FCBootEnvironment.
:returns: JSON for FCBootEnvironment as follows:
{
"FCBootEnvironment":{
"FCTargets":{
"FCTarget":[
]
},
"FCLinkSpeed":{
... | 7.04441 | 3.912918 | 1.800296 |
if self.dhcp_usage:
return {'DHCPUsage': self.dhcp_usage,
'Name': self.iqn}
else:
return self.get_basic_json() | def get_json(self) | Create JSON data for iSCSI initiator.
:returns: JSON data for iSCSI initiator as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"SubnetMask":{
},
... | 8.809263 | 4.431955 | 1.98767 |
json = {
'DHCPUsage': self.dhcp_usage,
'AuthenticationMethod': self.auth_method,
}
if not self.dhcp_usage:
json['Name'] = self.iqn
json['IPv4Address'] = self.ip
json['PortNumber'] = self.port
json['BootLUN'] = self.... | def get_json(self) | Create JSON data for iSCSI target.
:returns: JSON data for iSCSI target as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"PortNumber":{
},
"B... | 3.09713 | 1.750718 | 1.769062 |
## pic 100 random elements along each dimension
## use zscale (see the IRAF display man page or
## http://iraf.net/article.php/20051205162333315
import random
x=[]
for i in random.sample(xrange(data.shape[0]),50):
for j in random.sample(xrange(data.shape[1]),50):
x.append(data[i,j])
yl=numarray.so... | def zscale(data,contrast,min=100,max=60000) | Scale the data cube into the range 0-255 | 5.120896 | 5.050603 | 1.013918 |
updating_params = {}
if iq_zeropt:
updating_params = get_iq_and_zeropoint(image_id, {})
if comment:
updating_params = {'comment': commdict[str(image_id)]}
if snr:
updating_params = get_snr(image_id, {})
ss = ims.images.update(ims.images.c.image_id == image_id)
ims.co... | def update_values(ims, image_id, iq_zeropt=True, comment=False, snr=False, commdict=None) | Update a row in ossuary with
:param ims: an ImageQuery, contains image table and a connector
:param image_id: the primary key of the row to be updated
:param iq_zeropt: Keyword set if iq and zeropoint are to be checked for updating
:param comment: Keyword set if image is to have a comment of Stephen's a... | 3.629574 | 3.119345 | 1.163569 |
parser = argparse.ArgumentParser()
parser.add_argument("-iq", "--iq", action="store_true",
help="Check existing images in ossuary that do not yet have "
"IQ/zeropoint information; update where possible.")
parser.add_argument("-comment", action="stor... | def main() | Update the ossuary Postgres db with images observed for OSSOS.
iq: Go through and check all ossuary's images for new existence of IQs/zeropoints.
comment: Go through all ossuary and
Then updates ossuary with new images that are at any stage of processing.
Constructs full image entries, including header ... | 4.046395 | 3.578204 | 1.130845 |
resampled_bands = [
self._resample(band, n_coeffs)
for band in self.iter_bands()]
stacked = np.vstack(resampled_bands).T
fdim = FrequencyDimension(self.scale)
# TODO: This feels like it could be wrapped up nicely elsewhere
chunk_frequency = Pic... | def square(self, n_coeffs, do_overlap_add=False) | Compute a "square" view of the frequency adaptive transform, by
resampling each frequency band such that they all contain the same
number of samples, and performing an overlap-add procedure in the
case where the sample frequency and duration differ
:param n_coeffs: The common size to whi... | 4.531077 | 4.403583 | 1.028952 |
x, y = point
(x1, y1) = x - self.x_offset, y - self.y_offset
logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1))
return x1, y1 | def convert(self, point) | Convert a point from one coordinate system to another.
Args:
point: tuple(int x, int y)
The point in the original coordinate system.
Returns:
converted_point: tuple(int x, int y)
The point in the new coordinate system.
Example: convert coordinate fr... | 3.685942 | 4.191989 | 0.879282 |
class Settings(ff.PersistenceSettings):
_id = cls.__name__
id_provider = ff.StaticIdProvider(_id)
key_builder = ff.StringDelimitedKeyBuilder()
database = ff.FileSystemDatabase(
path=_id, key_builder=key_builder, createdirs=True)
class Model(cls, Settings):
... | def simple_settings(cls) | Create sane default persistence settings for learning pipelines
:param cls: The class to decorate | 6.881705 | 6.609195 | 1.041232 |
network_is_cuda = next(network.parameters()).is_cuda
x = torch.from_numpy(x)
with torch.no_grad():
if network_is_cuda:
x = x.cuda()
if chunksize is None:
return from_var(network(x))
return np.concatenate(
[from_var(network(x[i: i + chunksi... | def apply_network(network, x, chunksize=None) | Apply a pytorch network, potentially in chunks | 2.631059 | 2.591999 | 1.015069 |
original = x
# square
x = x ** 2
# feature-map-wise sum
x = torch.sum(x, dim=1)
# scale by number of feature maps
x *= 1.0 / original.shape[1]
x += 10e-8
x = torch.sqrt(x)
return original / x.view(-1, 1, x.shape[-1]) | def sample_norm(x) | pixel norm as described in section 4.2 here:
https://arxiv.org/pdf/1710.10196.pdf | 4.738742 | 5.085233 | 0.931863 |
(x, y, idx) = self.world2pix(self.init_skycoord.ra,
self.init_skycoord.dec,
usepv=True)
self.update_pixel_location((x, y), idx) | def reset_coord(self) | Reset the source location based on the init_skycoord values
@return: | 8.755312 | 6.596847 | 1.327197 |
return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num()) | def pixel_coord(self) | Return the coordinates of the source in the cutout reference frame.
@return: | 15.64212 | 17.039633 | 0.917985 |
for (extno, hdu) in enumerate(self.hdulist):
if ccdnum == int(hdu.header.get('EXTVER', -1)) or str(ccdnum) in hdu.header.get('AMPNAME', ''):
return extno
raise ValueError("Failed to find requested CCD Number {} in cutout {}".format(ccdnum,
... | def get_hdulist_idx(self, ccdnum) | The SourceCutout is a list of HDUs, this method returns the index of the HDU that corresponds to the given
ccd number. CCDs are numbers from 0, but the first CCD (CCDNUM=0) is often in extension 1 of an MEF.
@param ccdnum: the number of the CCD in the MEF that is being referenced.
@return: the ... | 4.56902 | 4.648286 | 0.982947 |
x, y = point
if self.reading.compute_inverted():
naxis1 = self.reading.obs.header.get(self.reading.obs.HEADER_IMG_SIZE_X,
self.reading.obs.header.get('NAXIS1', 256))
naxis2 = self.reading.obs.header.get(self.reading.obs.HE... | def flip_flip(self, point) | Sometimes we 'flipped' the X/Y coordinates of the image during processing. This function takes an
(x,y) location from the processing pipeline and returns the x/y location relative to the original
reference frame. (Correctly checks if the coordinate is flipped to begin with.)
This is only for... | 3.214357 | 3.355917 | 0.957818 |
self.reading.pix_coord = self.get_observation_coordinates(new_pixel_location[0],
new_pixel_location[1],
hdu_index)
new_ccd = self.get_ccdnum(hdu_index)
if ... | def update_pixel_location(self, new_pixel_location, hdu_index) | Update the x/y location of the associated reading by using new_pixel_location and transforming from cutout
reference frame to observation refrence frame.
@param new_pixel_location: (x, y) location of the source in cutout pixel reference frame
@param hdu_index: index of the associate hdu in the h... | 3.768825 | 3.663253 | 1.028819 |
hdulist_index = self.get_hdulist_idx(ccdnum)
if isinstance(point[0], Quantity) and isinstance(point[1], Quantity):
pix_point = point[0].value, point[1].value
else:
pix_point = point
if self.reading.inverted:
pix_point = self.reading.obs.naxis1... | def get_pixel_coordinates(self, point, ccdnum) | Retrieves the pixel location of a point within the current HDUList given the
location in the original FITS image. This takes into account that
the image may be a cutout of a larger original.
Args:
point: tuple(float, float)
(x, y) in original.
Returns:
... | 3.341763 | 3.632329 | 0.920006 |
return self.hdulist[hdulist_index].converter.get_inverse_converter().convert((x, y)) | def get_observation_coordinates(self, x, y, hdulist_index) | Retrieves the location of a point using the coordinate system of
the original observation, i.e. the original image before any
cutouts were done.
Returns:
(x, y) in the original image coordinate system.
@param x: x-pixel location in the cutout frame of reference
@pa... | 10.331598 | 15.266703 | 0.676741 |
x, y, idx = (0, 0, 0)
for idx in range(1, len(self.hdulist)):
hdu = self.hdulist[idx]
x, y = hdu.wcs.sky2xy(ra, dec, usepv=usepv)
if 0 < x < hdu.header['NAXIS1'] and 0 < y < hdu.header['NAXIS2']:
# print "Inside the frame."
ret... | def world2pix(self, ra, dec, usepv=True) | Convert a given RA/DEC position to the X/Y/HDULIST_INDEX in the cutout frame.
Here we loop over the hdulist to find the extension is RA/DEC are from and then return the appropriate X/Y
:param ra: The Right Ascension of the point
:type ra: Quantity
:param dec: The Declination of the po... | 3.155322 | 2.909859 | 1.084356 |
if self._zmag is None:
hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num())
self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0)
return self._zmag | def zmag(self,) | Return the photometric zeropoint of the CCD associated with the reading.
@return: float | 4.323931 | 3.645204 | 1.186197 |
if self._apcor is None:
try:
self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri())
except:
self._apcor = ApcorData.from_string("5 15 99.99 99.99")
return self._apcor | def apcor(self) | return the aperture correction of for the CCD assocated with the reading.
@return: Apcor | 5.605297 | 5.132673 | 1.092082 |
# NOTE: this import is only here so that we don't load up IRAF
# unnecessarily (ex: for candidates processing).
max_count = float(self.astrom_header.get("MAXCOUNT", 30000))
(x, y, hdulist_index) = self.pixel_coord
tmp_file = self._hdu_on_disk(hdulist_index)
try:... | def get_observed_magnitude(self, centroid=True) | Get the magnitude at the current pixel x/y location.
:return: Table | 7.860105 | 8.170688 | 0.961988 |
if self._tempfile is None:
self._tempfile = tempfile.NamedTemporaryFile(
mode="r+b", suffix=".fits")
self.hdulist[hdulist_index].writeto(self._tempfile.name)
return self._tempfile.name | def _hdu_on_disk(self, hdulist_index) | IRAF routines such as daophot need input on disk.
Returns:
filename: str
The name of the file containing the FITS data. | 2.704813 | 2.98301 | 0.90674 |
if self._comparison_image_list is not None:
return self._comparison_image_list
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcmi... | def comparison_image_list(self) | returns a list of possible comparison images for the current cutout. Will query CADC to create the list when
first called.
@rtype: Table | 4.587904 | 4.264056 | 1.075949 |
# selecting comparator when on a comparator should load a new one.
collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM']
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
radius = self.radius is not None and self... | def retrieve_comparison_image(self) | Search the DB for a comparison image for this cutout. | 4.985807 | 4.813569 | 1.035782 |
# This provides authentication via CADC.
return gms.isMember(self.login, passwd, group) | def check_password(self, passwd, group) | check that the passwd provided matches the required password. | 53.044712 | 62.100624 | 0.854174 |
if isinstance(ts, slice):
try:
start = Seconds(0) if ts.start is None else ts.start
if start < Seconds(0):
start = self.end + start
stop = self.end if ts.stop is None else ts.stop
if stop < Seconds(0):
... | def integer_based_slice(self, ts) | Transform a :class:`TimeSlice` into integer indices that numpy can work
with
Args:
ts (slice, TimeSlice): the time slice to translate into integer
indices | 4.76974 | 4.702486 | 1.014302 |
for filename in filenames:
if re.search(regex, filename) is None:
logging.error("Skipping {}".format(filename))
continue
obs = mpc.MPCReader().read(os.path.join(path, filename))
for ob in obs:
if "568" not in ob.observatory_code:
cont... | def load_observations((observations, regex, rename), path, filenames) | Returns a provisional name based dictionary of observations of the object.
Each observations is keyed on the date. ie. a dictionary of dictionaries.
@param path: the directory where filenames are.
@type path str
@param filenames: list of files in path.
@type filenames list
@rtype None | 3.366322 | 3.441722 | 0.978092 |
iraf.set(uparm="./")
iraf.digiphot()
iraf.apphot()
iraf.daophot(_doprint=0)
iraf.images()
if shifts['nmag'] < 4:
logging.warning("Mag shift based on fewer than 4 common stars.")
fd = open("plant.WARNING", 'a')
fd.write("Mag shift based on fewer than 4 common stars.... | def plant_kbos(filename, psf, kbos, shifts, prefix) | Add KBOs to an image
:param filename: name of the image to add KBOs to
:param psf: the Point Spread Function in IRAF/DAOPHOT format to be used by ADDSTAR
:param kbos: list of KBOs to add, has format as returned by KBOGenerator
:param shifts: dictionary with shifts to transfer to coordinates to reference... | 4.852568 | 4.725808 | 1.026823 |
# Construct a list of artificial KBOs with positions in the image
# and rates of motion within the bounds given by the caller.
filename = storage.get_image(expnums[0],
ccd=ccd,
version=version)
header = fits.open(filename)[0].header... | def plant(expnums, ccd, rmin, rmax, ang, width, number=10, mmin=21.0, mmax=25.5, version='s', dry_run=False) | Plant artificial sources into the list of images provided.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to
:param ccd: which ccd to work on.
:param rmin: The minimum rate of motion to add sources at (''/hour)
:param rmax: The maximum rate of motion to add sources at (''/hou... | 5.004731 | 4.666033 | 1.072588 |
# call fitradec with mpcfile, abgfile, resfile
self.orbfit.fitradec.restype = ctypes.c_int
self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ]
mpc_file = tempfile.NamedTemporaryFile(suffix='.mpc')
for observation in self.observations:
... | def _fit_radec(self) | call fit_radec of BK passing in the observations. | 2.471333 | 2.372393 | 1.041704 |
time = Time(date, scale='utc', precision=6)
jd = ctypes.c_double(time.jd)
# call predict with agbfile, jdate, obscode
self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5)
self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ]
... | def predict(self, date, obs_code=568) | use the bk predict method to compute the location of the source on the given date. | 3.454733 | 3.402812 | 1.015258 |
def new_guithread_function(*args, **kwargs):
if wx.Thread_IsMain():
return function(*args, **kwargs)
else:
wx.CallAfter(function, *args, **kwargs)
return new_guithread_function | def guithread(function) | Decorator to make sure the function is called from wx's main GUI
thread. This is needed when trying to trigger UI updates from a thread
other than the main GUI thread (such as some asynchronous data loading
thread).
I learned about doing this from:
wxPython 2.8 Application Development Cookbook, Ch... | 2.854186 | 2.563848 | 1.113243 |
if order or format:
warnings.warn('Use of <order> and <format> depricated',DeprecationWarning)
## if the order of the columns isn't constrained just use the keys in what ever order
data='data'
if not order:
if not hdu.has_key('order'):
hdu['order']=hdu[data].keys()
... | def write(file,hdu,order=None,format=None) | Write a file in the crazy MOP format given an mop data hdu. | 2.853257 | 2.85051 | 1.000964 |
import MOPdbaccess
db=MOPdbaccess.connect(dbase,duser,dbSystem=dtype)
dbc=db.cursor()
### INSERT THE 'HEADER' in the meta-data table
file_id=hdu['header']['image']
for key in hdu['header'].keys():
if key == 'image':
continue
value=hdu['header'][key]
###... | def store(hdu,dbase='cfeps',duser='cfhls',dtype='MYSQL',table='source') | Write the contents of a MOP data structure to a SQL table | 3.922634 | 3.844563 | 1.020307 |
f = open(file,'r')
lines=f.readlines()
f.close()
import re, string
keywords=[]
values=[]
formats={}
header={}
cdata={}
for line in lines:
if ( re.match(r'^##',line)):
## header line
m=string.split(string.lstrip(line[2:]))
if... | def read(file) | Read in a file and create a data strucuture that is a hash with members 'header'
and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns.
To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header
information use hdu[header][KEYWORD]. | 4.830233 | 4.598205 | 1.05046 |
import math
import sys
output={}
files=[]
for filename in filenames:
this_file=read(filename)
## match files based on the 'X' and 'Y' column.
## if those don't exist then skip this file
if not this_file['data'].has_key('X') or not this_file['data'].has_key('Y'):
... | def xymatch(outfile, filenames, tol=2) | Given a list of MOPfiles merge them based on x/y coordinates matching.. | 2.336927 | 2.262137 | 1.033062 |
r
kwargs.setdefault('level', 'INFO')
return {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'ignore_errors': {
'()': IgnoreErrorsFilter,
},
},
'formatters': {
'default': {
'format': '%(... | def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny | r"""Prepare logging dict suitable with ``logging.config.dictConfig``.
**Usage**::
from logging.config import dictConfig
dictConfig(default_logging_dict('yourlogger'))
:param \*loggers: Enable logging for each logger in sequence.
:param \*\*kwargs: Setup additional logger params via keywor... | 1.816225 | 1.831248 | 0.991796 |
r
# No Sentry DSN, nothing to do
if not sentry_dsn:
return
# Add Sentry handler
kwargs['class'] = 'raven.handlers.logging.SentryHandler'
kwargs['dsn'] = sentry_dsn
logging_dict['handlers']['sentry'] = dict(
level=level or 'WARNING',
**kwargs)
loggers = tuple(log... | def update_sentry_logging(logging_dict: DictStrAny,
sentry_dsn: Optional[str],
*loggers: str,
level: Union[str, int] = None,
**kwargs: Any) -> None | r"""Enable Sentry logging if Sentry DSN passed.
.. note::
Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_
library to be installed.
**Usage**::
from logging.config import dictConfig
LOGGING = default_logging_dict()
SENTRY_DSN = '...'
updat... | 3.13905 | 3.524744 | 0.890575 |
datasec = re.findall(r'(\d+)',
hdu.header.get(datasec))
l = int(datasec[0]) - 1
r = int(datasec[1])
b = int(datasec[2]) - 1
t = int(datasec[3])
logger.info("Trimming [%d:%d,%d:%d]" % ( l, r, b, t))
hdu.data = hdu.data[b:t, l:r]
hdu.header.update('DATASEC',
... | def trim(hdu, datasec='DATASEC') | TRIM a CFHT MEGAPRIME frame using the DATASEC keyword | 2.588217 | 2.567491 | 1.008072 |
names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs',
'time', 'av_xres', 'av_yres', 'max_x', 'max_y', 'a', 'e_a', 'e', 'e_e', 'i', 'e_i', 'Omega', 'e_Omega',
'omega', 'e_omega', 'tperi', 'e_tperi', 'RAdeg', 'DEdeg', 'JD', 'rate']#, 'ef... | def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION) | extra fun as this is space-separated so using CSV parsers is not an option | 5.589881 | 5.390421 | 1.037003 |
retval = []
# working_context = context.get_context(directory)
# files = working_context.get_listing(suffix)
files = [f for f in os.listdir(directory) if (f.endswith('mpc') or f.endswith('ast') or f.endswith('DONE'))]
if single_object is not None:
files = filter(lambda name: name.start... | def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR,
suffix='ast',
no_nt_and_u=False,
single_object=None,
all_objects=True,
data_release=None,
) | Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field.
Default is to return only the objects corresponding to the current Data Release. | 4.951154 | 4.937794 | 1.002706 |
# discoveries = ossos_release_parser()
discoveries = []
observations = ossos_discoveries()
for obj in observations:
discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0]
tno = parameters.tno()
tno.dist = obj[1].distance
tno.ra_discov = discov.c... | def ossos_release_with_metadata() | Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines | 5.08615 | 4.833915 | 1.05218 |
lines = storage.open_vos_or_local(model_file).read().split('\n')
kbos = []
for line in lines:
if len(line) == 0 or line[0] == '#': # skip initial column descriptors and the final blank line
continue
kbo = ephem.EllipticalBody()
values = line.split()
kbo.name... | def _kbos_from_survey_sym_model_input_file(model_file) | Load a Survey Simulator model file as an array of ephem EllipticalBody objects.
@param model_file:
@return: | 3.583835 | 3.398731 | 1.054463 |
u = ufloat(num, uncert)
if pm:
return '{:.1uL}'.format(u)
else:
return '{:.1uLS}'.format(u) | def round_sig_error(num, uncert, pm=False) | Return a string of the number and its uncertainty to the right sig figs via uncertainty's print methods.
The uncertainty determines the sig fig rounding of the number.
https://pythonhosted.org/uncertainties/user_guide.html | 6.605055 | 5.210035 | 1.267756 |
try:
body = response.text
body_parts = body.split('\r\n')
if len(body_parts) > 0:
return jsonutils.loads(body_parts[-1])
else:
return None
except (TypeError, ValueError):
raise ELCMInvalidResponse('eLCM response does not contain valid json '
... | def _parse_elcm_response_body_as_json(response) | parse eLCM response body as json data
eLCM response should be in form of:
_
Key1: value1 <-- optional -->
Key2: value2 <-- optional -->
KeyN: valueN <-- optional -->
- CRLF -
JSON string
-
:param response: eLCM response
:return: json object if success
:raise ELCMInvali... | 3.968587 | 3.019528 | 1.314307 |
host = irmc_info['irmc_address']
port = irmc_info.get('irmc_port', 443)
auth_method = irmc_info.get('irmc_auth_method', 'basic')
userid = irmc_info['irmc_username']
password = irmc_info['irmc_password']
client_timeout = irmc_info.get('irmc_client_timeout', 60)
# Request headers, params... | def elcm_request(irmc_info, method, path, **kwargs) | send an eLCM request to the server
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', ... | 2.25508 | 1.977044 | 1.140632 |
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path=URL_PATH_PROFILE_MGMT + 'version')
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed... | def elcm_profile_get_versions(irmc_info) | send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00"
},
"HWConfigura... | 4.568272 | 4.42966 | 1.031292 |
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path=URL_PATH_PROFILE_MGMT + profile_name)
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
elif resp.status_code == 404:
raise EL... | def elcm_profile_get(irmc_info, profile_name) | send an eLCM request to get profile data
:param irmc_info: node info
:param profile_name: name of profile
:returns: dict object of profile data if succeed
:raises: ELCMProfileNotFound if profile does not exist
:raises: SCCIClientError if SCCI failed | 3.370961 | 3.052999 | 1.104148 |
# Send POST request to the server
# NOTE: This task may take time, so set a timeout
_irmc_info = dict(irmc_info)
_irmc_info['irmc_client_timeout'] = PROFILE_CREATE_TIMEOUT
resp = elcm_request(_irmc_info,
method='POST',
path=URL_PATH_PROFILE_MGMT ... | def elcm_profile_create(irmc_info, param_path) | send an eLCM request to create profile
To create a profile, a new session is spawned with status 'running'.
When profile is created completely, the session ends.
:param irmc_info: node info
:param param_path: path of profile
:returns: dict object of session info if succeed
{
'Ses... | 4.465194 | 4.483049 | 0.996017 |
# Prepare the data to apply
if isinstance(input_data, dict):
data = jsonutils.dumps(input_data)
else:
data = input_data
# Send POST request to the server
# NOTE: This task may take time, so set a timeout
_irmc_info = dict(irmc_info)
_irmc_info['irmc_client_timeout'] = P... | def elcm_profile_set(irmc_info, input_data) | send an eLCM request to set param values
To apply param values, a new session is spawned with status 'running'.
When values are applied or error, the session ends.
:param irmc_info: node info
:param input_data: param values to apply, eg.
{
'Server':
{
'SystemCon... | 4.688749 | 4.047516 | 1.158426 |
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path=URL_PATH_PROFILE_MGMT + profile_name)
if resp.status_code == 200:
# Profile deleted
return
elif resp.status_code == 404:
# Profile not fo... | def elcm_profile_delete(irmc_info, profile_name) | send an eLCM request to delete a profile
:param irmc_info: node info
:param profile_name: name of profile
:raises: ELCMProfileNotFound if the profile does not exist
:raises: SCCIClientError if SCCI failed | 3.315453 | 2.942663 | 1.126685 |
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path='/sessionInformation/')
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to list se... | def elcm_session_list(irmc_info) | send an eLCM request to list all sessions
:param irmc_info: node info
:returns: dict object of sessions if succeed
{
'SessionList':
{
'Contains':
[
{ 'Id': id1, 'Name': name1 },
{ 'Id': id2, 'Name': name2 },
{ 'Id': i... | 4.9366 | 4.638438 | 1.064281 |
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path='/sessionInformation/%s/status' % session_id)
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
elif resp.status_code == 404:
... | def elcm_session_get_status(irmc_info, session_id) | send an eLCM request to get session status
:param irmc_info: node info
:param session_id: session id
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': status
...
}
}
:raises: ELCMSessionNo... | 3.210446 | 2.889292 | 1.111153 |
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path='/sessionInformation/%s/terminate' % session_id)
if resp.status_code == 200:
return
elif resp.status_code == 404:
raise ELCMSessionNotFound('Sess... | def elcm_session_terminate(irmc_info, session_id) | send an eLCM request to terminate a session
:param irmc_info: node info
:param session_id: session id
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed | 3.347351 | 2.819692 | 1.187134 |
# Terminate the session first if needs to
if terminate:
# Get session status to check
session = elcm_session_get_status(irmc_info, session_id)
status = session['Session']['Status']
# Terminate session if it is activated or running
if status == 'running' or status ==... | def elcm_session_delete(irmc_info, session_id, terminate=False) | send an eLCM request to remove a session from the session list
:param irmc_info: node info
:param session_id: session id
:param terminate: a running session must be terminated before removing
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed | 3.258822 | 2.811455 | 1.159123 |
session_expiration = time.time() + session_timeout
while time.time() < session_expiration:
# Get session status to check
session = elcm_session_get_status(irmc_info=irmc_info,
session_id=session_id)
status = session['Session']['Status']
... | def _process_session_data(irmc_info, operation, session_id,
session_timeout=BIOS_CONFIG_SESSION_TIMEOUT) | process session for Bios config backup/restore or RAID config operation
:param irmc_info: node info
:param operation: one of 'BACKUP_BIOS', 'RESTORE_BIOS' or 'CONFIG_RAID'
:param session_id: session id
:param session_timeout: session timeout
:return: a dict with following values:
{
... | 3.283976 | 2.999647 | 1.094788 |
# 1. Make sure there is no BiosConfig profile in the store
try:
# Get the profile first, if not found, then an exception
# will be raised.
elcm_profile_get(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
# Profile found, delete it
elcm... | def backup_bios_config(irmc_info) | backup current bios configuration
This function sends a BACKUP BIOS request to the server. Then when the bios
config data are ready for retrieving, it will return the data to the
caller. Note that this operation may take time.
:param irmc_info: node info
:return: a dict with following values:
... | 4.341532 | 4.379169 | 0.991405 |
def _process_bios_config():
try:
if isinstance(bios_config, dict):
input_data = bios_config
else:
input_data = jsonutils.loads(bios_config)
# The input data must contain flag "@Processing":"execute" in the
# equivalent se... | def restore_bios_config(irmc_info, bios_config) | restore bios configuration
This function sends a RESTORE BIOS request to the server. Then when the
bios
is ready for restoring, it will apply the provided settings and return.
Note that this operation may take time.
:param irmc_info: node info
:param bios_config: bios config | 4.650304 | 4.500136 | 1.03337 |
result = backup_bios_config(irmc_info=irmc_info)
try:
bioscfg = result['bios_config']['Server']['SystemConfig']['BiosConfig']
return bioscfg['SecurityConfig']['SecureBootControlEnabled']
except KeyError:
msg = ("Failed to get secure boot mode from server %s. Upgrading iRMC "
... | def get_secure_boot_mode(irmc_info) | Get the status if secure boot is enabled or not.
:param irmc_info: node info.
:raises: SecureBootConfigNotFound, if there is no configuration for secure
boot mode in the bios.
:return: True if secure boot mode is enabled on the node, False otherwise. | 6.486766 | 5.065626 | 1.280546 |
bios_config_data = {
'Server': {
'@Version': '1.01',
'SystemConfig': {
'BiosConfig': {
'@Version': '1.01',
'SecurityConfig': {
'SecureBootControlEnabled': enable
}
... | def set_secure_boot_mode(irmc_info, enable) | Enable/Disable secure boot on the server.
:param irmc_info: node info
:param enable: True, if secure boot needs to be
enabled for next boot, else False. | 3.798672 | 4.034763 | 0.941486 |
logical_disk_list = target_raid_config['logical_disks']
raid_input['Server']['HWConfigurationIrmc'].update({'@Processing':
'execute'})
array_info = raid_input['Server']['HWConfigurationIrmc']['Adapters'][
'RAIDAdapter'][0]
array_info... | def _update_raid_input_data(target_raid_config, raid_input) | Process raid input data.
:param target_raid_config: node raid info
:param raid_input: raid information for creating via eLCM
:raises ELCMValueError: raise msg if wrong input
:return: raid_input: raid input data which create raid configuration
{
"Server":{
"HWConfigurationI... | 4.122861 | 3.228798 | 1.276903 |
existing_logical_drives = []
logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0].get('LogicalDrives')
if logical_drives is not None:
for drive in logical_drives['LogicalDrive']:
existing_logical_drives.append(drive['@Number'])
r... | def _get_existing_logical_drives(raid_adapter) | Collect existing logical drives on the server.
:param raid_adapter: raid adapter info
:returns: existing_logical_drives: get logical drive on server | 4.850005 | 5.126875 | 0.945996 |
try:
# Attempt erase exist adapter on BM Server
elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
session = elcm_profile_create(irmc_info, PARAM_PATH_RAID_CONFIG)
# Monitoring... | def _create_raid_adapter_profile(irmc_info) | Attempt delete exist adapter then create new raid adapter on the server.
:param irmc_info: node info
:returns: result: a dict with following values:
{
'raid_config': <data of raid adapter profile>,
'warning': <warning message if there is>
... | 10.22011 | 8.74135 | 1.169168 |
if len(target_raid_config['logical_disks']) < 1:
raise ELCMValueError(message="logical_disks must not be empty")
# Check RAID config in the new RAID adapter. Must be erased before
# create new RAID config.
raid_adapter = get_raid_adapter(irmc_info)
logical_drives = raid_adapter['Serve... | def create_raid_configuration(irmc_info, target_raid_config) | Process raid_input then perform raid configuration into server.
:param irmc_info: node info
:param target_raid_config: node raid information | 7.779609 | 7.51303 | 1.035482 |
# Attempt to get raid configuration on BM Server
raid_adapter = get_raid_adapter(irmc_info)
existing_logical_drives = _get_existing_logical_drives(raid_adapter)
# Ironic requires delete_configuration first. Will pass if blank raid
# configuration in server.
if not existing_logical_drives:
... | def delete_raid_configuration(irmc_info) | Delete whole raid configuration or one of logical drive on the server.
:param irmc_info: node info | 7.155328 | 7.110773 | 1.006266 |
bios_config_data = {
'Server': {
'SystemConfig': {
'BiosConfig': {}
}
}
}
versions = elcm_profile_get_versions(irmc_info)
server_version = versions['Server'].get('@Version')
bios_version = \
versions['Server']['SystemConfig']['Bi... | def set_bios_configuration(irmc_info, settings) | Set BIOS configurations on the server.
:param irmc_info: node info
:param settings: Dictionary containing the BIOS configuration.
:raise: BiosConfigNotFound, if there is wrong settings for bios
configuration. | 2.980482 | 2.901284 | 1.027297 |
bios_config = backup_bios_config(irmc_info)['bios_config']
bios_config_data = bios_config['Server']['SystemConfig']['BiosConfig']
settings = []
# TODO(trungnv): Allow working with multi levels of BIOS dictionary.
for setting_param in BIOS_CONFIGURATION_DICTIONARY:
type_config, config ... | def get_bios_settings(irmc_info) | Get the current BIOS settings on the server
:param irmc_info: node info.
:returns: a list of dictionary BIOS settings | 5.153199 | 5.249639 | 0.981629 |
def add_resource(url: str,
get: View = None,
*,
name: str = None,
**kwargs: Any) -> web.Resource:
kwargs['get'] = get
if url_prefix:
url = '/'.join((url_prefix.rstrip('/'), url.lstrip('/'))... | def add_resource_context(router: web.AbstractRouter,
url_prefix: str = None,
name_prefix: str = None) -> Iterator[Any] | Context manager for adding resources for given router.
Main goal of context manager to easify process of adding resources with
routes to the router. This also allow to reduce amount of repeats, when
supplying new resources by reusing URL & name prefixes for all routes
inside context manager.
Behin... | 2.656159 | 2.804637 | 0.94706 |
parts = urlparse(url)
db = parts.path[1:] or None # type: Optional[Union[str, int]]
if db:
db = int(db)
return {
'address': (parts.hostname, parts.port or 6379),
'db': db,
'password': parts.password} | def parse_aioredis_url(url: str) -> DictStrAny | Convert Redis URL string to dict suitable to pass to
``aioredis.create_redis(...)`` call.
**Usage**::
async def connect_redis(url=None):
url = url or 'redis://localhost:6379/0'
return await create_redis(**get_aioredis_parts(url))
:param url: URL to access Redis instance, s... | 2.946875 | 3.465461 | 0.850356 |
iys, ims, ids, ihmsfs = sofa_time.jd_dtf(self.scale.upper()
.encode('utf8'),
6,
self.jd1, self.jd2)
# Get the str_fmt element of the first allowed ... | def str_kwargs(self) | Generator that yields a dict of values corresponding to the
calendar date and time for the internal JD values.
Here we provide the additional 'fracday' element needed by 'mpc' format | 5.645734 | 4.923583 | 1.146672 |
try:
s = np.arange(s)
except TypeError:
s = np.arange(s[0])
i = np.sin((s + .5) / len(s) * np.pi) ** 2
f = np.sin(.5 * np.pi * i)
return f * (1. / f.max()) | def oggvorbis(s) | This is taken from the ogg vorbis spec
(http://xiph.org/vorbis/doc/Vorbis_I_spec.html)
:param s: the total length of the window, in samples | 4.73411 | 4.458846 | 1.061734 |
offset_x, offset_y = reference_reading.get_coordinate_offset(source_reading)
focus = source_reading.x + offset_x, source_reading.y + offset_y
return focus | def convert_source_location(self, source_reading, reference_reading) | Converts the source (x, y) location from reading into the coordinate
system of reference_reading. | 4.099922 | 3.428102 | 1.195974 |
middle_index = len(self.source.get_readings()) // 2
middle_reading = self.source.get_reading(middle_index)
return self.convert_source_location(middle_reading, reading) | def calculate_focus(self, reading) | Determines what the focal point of the downloaded image should be.
Returns:
focal_point: (x, y)
The location of the source in the middle observation, in the
coordinate system of the current source reading. | 5.368038 | 5.509058 | 0.974402 |
fc = ['b', '#E47833', 'k']
alpha = [0.85, 0.6, 1.]
marker = ['o', 'd']
size = [7, 25]
plottable = [] # Which blocks' discoveries to include?
for d in discoveries:
for n in plot_discoveries:
if d['object'].startswith(n): # can for sure be better, but this hack works. ... | def plot_ossos_discoveries(ax, discoveries, plot_discoveries,
plot_colossos=False, split_plutinos=False) | plotted at their discovery locations, provided by the Version Releases in decimal degrees. | 5.850326 | 5.751946 | 1.017104 |
ra_residuals = []
dec_residuals = []
ressum = []
for i, orbit in enumerate(discoveries):
if (orbit.da / orbit.a) < 0.01:
print i, len(discoveries), orbit.observations[0].provisional_name, orbit.da / orbit.a
res = orbit.residuals.split('\n')
for r in res:
... | def orbit_fit_residuals(discoveries, blockID='O13AE') | Brett: What are relevant and stunning are the actual orbit fit residuals
for orbits with d(a)/a<1%. I would be happy with a simple histogram of all those numbers,
although the 'tail' (probably blended and not yet completely flagged) should
perhaps be excluded. There will be a pretty clear gaussian I would ... | 3.844187 | 3.601512 | 1.067381 |
try:
bmc_name = snmp_client.get(BMC_NAME_OID)
irmc_firm_ver = snmp_client.get(IRMC_FW_VERSION_OID)
return ('%(bmc)s%(sep)s%(firm_ver)s' %
{'bmc': bmc_name if bmc_name else '',
'firm_ver': irmc_firm_ver if irmc_firm_ver else '',
'sep': '... | def get_irmc_firmware_version(snmp_client) | Get irmc firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bmc name and irmc firmware version. | 3.131866 | 2.752043 | 1.138015 |
try:
bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_OID)
return six.text_type(bios_firmware_version)
except SNMPFailure as e:
raise SNMPBIOSFirmwareFailure(
SNMP_FAILURE_MSG % ("GET BIOS FIRMWARE VERSION", e)) | def get_bios_firmware_version(snmp_client) | Get bios firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bios firmware version. | 4.959002 | 4.605744 | 1.076699 |
try:
server_model = snmp_client.get(SERVER_MODEL_OID)
return six.text_type(server_model)
except SNMPFailure as e:
raise SNMPServerModelFailure(
SNMP_FAILURE_MSG % ("GET SERVER MODEL", e)) | def get_server_model(snmp_client) | Get server model of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of server model. | 4.841463 | 4.518585 | 1.071456 |
if self.version == SNMP_V3:
# Handling auth/encryption credentials is not (yet) supported.
# This version supports a security name analogous to community.
return cmdgen.UsmUserData(self.security)
else:
mp_model = 1 if self.version == SNMP_V2C else... | def _get_auth(self) | Return the authorization data for an SNMP request.
:returns: A
:class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData`
object. | 8.241976 | 7.405375 | 1.112972 |
try:
results = self.cmd_gen.getCmd(self._get_auth(),
self._get_transport(),
oid)
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", e))
error_indica... | def get(self, oid) | Use PySNMP to perform an SNMP GET operation on a single object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: The value of the requested object. | 3.095708 | 2.796836 | 1.106861 |
try:
results = self.cmd_gen.nextCmd(self._get_auth(),
self._get_transport(),
oid)
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET_NEXT", e))
erro... | def get_next(self, oid) | Use PySNMP to perform an SNMP GET NEXT operation on a table object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: A list of values of the requested table object. | 3.091279 | 2.830868 | 1.09199 |
try:
results = self.cmd_gen.setCmd(self._get_auth(),
self._get_transport(),
(oid, value))
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", e))
err... | def set(self, oid, value) | Use PySNMP to perform an SNMP SET operation on a single object.
:param oid: The OID of the object to set.
:param value: The value of the object to set.
:raises: SNMPFailure if an SNMP request fails. | 3.166484 | 2.7844 | 1.137223 |
if self._filename is None:
self._filename = storage.get_file(self.basename,
self.ccd,
ext=self.extension,
version=self.type,
... | def filename(self) | Name if the MOP formatted file to parse.
@rtype: basestring
@return: filename | 6.465386 | 7.11623 | 0.908541 |
with open(self.filename, 'r') as fobj:
lines = fobj.read().split('\n')
# Create a header object with content at start of file
self.header = MOPHeader(self.subfmt).parser(lines)
# Create a data attribute to hold an astropy.table.Table object
self.data = MOPD... | def _parse(self) | read in a file and return a MOPFile object. | 7.282512 | 5.639972 | 1.291232 |
if self._table is None:
column_names = []
for fileid in self.header.file_ids:
for column_name in self.header.column_names:
column_names.append("{}_{}".format(column_name, fileid))
column_names.append("ZP_{}".format(fileid))
... | def table(self) | The astropy.table.Table object that will contain the data result
@rtype: Table
@return: data table | 2.733141 | 2.702105 | 1.011486 |
while len(lines) > 0:
if lines[0].startswith('##') and lines[1].startswith('# '):
# A two-line keyword/value line starts here.
self._header_append(lines.pop(0), lines.pop(0))
elif lines[0].startswith('# '):
# Lines with single comm... | def parser(self, lines) | Given a set of lines parse the into a MOP Header | 6.944271 | 6.681074 | 1.039394 |
try:
idx = kw.index('MJD-OBS-CENTER')
except ValueError:
return
if len(val) == len(kw):
return
if len(val) - 2 != len(kw):
raise ValueError("convert: keyword/value lengths don't match: {}/{}".format(kw, val))
val.insert(idx... | def _compute_mjd(self, kw, val) | Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value.
@param kw: a list of keywords
@param val: a list of matching values
@return: the MJD-OBS-CENTER as a julian date. | 4.558943 | 4.043256 | 1.127543 |
col_names=['object',
'e.expnum',
'mjdate',
'uttime',
'filter',
'elongation',
'obs_iq_refccd',
'triple', 'qso_status']
sql="SELECT "
sep=" "
for col_name in col_names:
sql=sql+sep+col_n... | def getExpInfo(expnum) | Return a dictionary of information about a particular exposure | 6.008945 | 5.879796 | 1.021965 |
col_names=['mjdate', 'filter', 'elongation', 'discovery','checkup', 'recovery', 'iq','block' ]
sql="SELECT mjdate md,"
sql=sql+" filter, avg(elongation), d.id, checkup.checkup, recovery.recovery , avg(obs_iq_refccd), b.qname "
sql=sql+"FROM triple_members t JOIN bucket.exposure e ON t.expnum=e.exp... | def getTripInfo(triple) | Return a dictionary of information about a particular triple | 5.772954 | 5.775488 | 0.999561 |
if night:
night=" floor(e.mjdate-0.0833)=%d " % ( night )
else:
night=''
sql="SELECT e.expnum "
sql=sql+"FROM bucket.exposure e "
sql=sql+"JOIN bucket.association a on e.expnum=a.expnum "
sql=sql+"WHERE a.pointing="+str(pointing)+" AND "+night
sql=sql+" ORDER BY ... | def getExpnums(pointing,night=None) | Get all exposures of specified pointing ID.
Default is to return a list of all exposure numbers | 7.861203 | 8.036025 | 0.978245 |
sql="SELECT id FROM triples t join triple_members m ON t.id=m.triple"
sql+=" join bucket.exposure e on e.expnum=m.expnum "
sql+=" WHERE pointing=%s group by id order by e.expnum "
cfeps.execute(sql, ( pointing, ) )
return(cfeps.fetchall()) | def getTriples(pointing) | Get all triples of a specified pointing ID.
Defaults is to return a complete list triples. | 11.325399 | 10.57242 | 1.071221 |
win.help("Building list of exposures to look for triples")
cols=('e.expnum', 'object',
'mjdate',
'uttime',
'elongation',
'filter',
'obs_iq_refccd','qso_status' )
header='%6s %-10s%-12s%10s%10s%10s%8s%10s' % cols
pointings=getNewTriples()
num_p=len(pointings)... | def createNewTriples(Win) | Add entries to the triples tables based on new images in the db | 5.920361 | 5.875367 | 1.007658 |
win.help("Getting a list of pointings with triples from the CFEPS db")
pointings=getPointingsWithTriples()
win.help("Select the "+table+" triple form the list...")
import time
for pointing in pointings:
header="%10s %10s %8s %10s %8s" % (pointing[1],'mjdate','Elongation','Filter', 'IQ... | def setDiscoveryTriples(win,table="discovery") | Provide user with a list of triples that could be discovery triples | 5.630741 | 5.571531 | 1.010627 |
message = storage.SUCCESS
if storage.get_status(task, prefix, expnum, version, ccd) and not force:
logging.info("{} completed successfully for {} {} {} {}".format(task, prefix, expnum, version, ccd))
return
with storage.LoggingManager(task, prefix, expnum, ccd, version, dry_ru... | def run(expnum,
ccd,
prefix='',
version='p',
sex_thresh=_SEX_THRESHOLD,
wave_thresh=_WAVE_THRESHOLD,
maxcount=_MAX_COUNT,
dry_run=False,
force=True) | run the actual step1jmp/matt codes.
expnum: the CFHT expousre to process
ccd: which ccd in the mosaic to process
fwhm: the image quality, FWHM, of the image. In pixels.
sex_thresh: the detection threhold to run sExtractor at
wave_thresh: the detection threshold for wavelet
maxcount: saturation... | 3.79021 | 3.672567 | 1.032033 |
if query is None:
query=(
.format(ra,dec,rad) )
tapURL = "http://TAPVizieR.u-strasbg.fr/TAPVizieR/tap/sync"
## Some default parameters for that TAP service queries.
tapParams={'REQUEST': 'doQuery',
'LANG': '... | def query(ra ,dec, rad=0.1, query=None) | Query the CADC TAP service to determine the list of images for the
NewHorizons Search. Things to determine:
a- Images to have the reference subtracted from.
b- Image to use as the 'REFERENCE' image.
c- Images to be used for input into the reference image
Logic: Given a particular Image/CCD find all the ... | 6.33879 | 6.234023 | 1.016806 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.