code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Change password.
'''
params = {'usrName': usrname,
'oldPwd' : oldpwd,
'newPwd' : newpwd,
}
return self.execute_command('changePassword',
params, callback=callback) | def change_password(self, usrname, oldpwd, newpwd, callback=None) | Change password. | 3.812635 | 3.650987 | 1.044275 |
'''
Set systeim time
'''
if ntp_server not in ['time.nist.gov',
'time.kriss.re.kr',
'time.windows.com',
'time.nuri.net',
]:
raise ValueError('Unsupported ntp... | def set_system_time(self, time_source, ntp_server, date_format,
time_format, time_zone, is_dst, dst, year,
mon, day, hour, minute, sec, callback=None) | Set systeim time | 2.428405 | 2.23832 | 1.084923 |
'''
Set camera name
'''
params = {'devName': devname.encode('gbk')}
return self.execute_command('setDevName', params, callback=callback) | def set_dev_name(self, devname, callback=None) | Set camera name | 6.131792 | 4.580985 | 1.338531 |
'''
Set Infrared LED configuration
cmd: setInfraLedConfig
mode(0,1): 0=Auto mode, 1=Manual mode
'''
params = {'mode': mode}
return self.execute_command('setInfraLedConfig', params, callback=callback) | def set_infra_led_config(self, mode, callback=None) | Set Infrared LED configuration
cmd: setInfraLedConfig
mode(0,1): 0=Auto mode, 1=Manual mode | 4.882247 | 2.262695 | 2.157713 |
'''
Move to preset.
'''
params = {'name': name}
return self.execute_command('ptzGotoPresetPoint', params, callback=callback) | def ptz_goto_preset(self, name, callback=None) | Move to preset. | 5.918896 | 4.880756 | 1.212701 |
'''
Get the current config and set the motion detection on or off
'''
result, current_config = self.get_motion_detect_config()
if result != FOSCAM_SUCCESS:
return result
current_config['isEnable'] = enabled
self.set_motion_detect_config(current_config)... | def set_motion_detection(self, enabled=1) | Get the current config and set the motion detection on or off | 4.977913 | 3.99465 | 1.246145 |
'''
Get the current config and set the motion detection on or off
'''
result, current_config = self.get_motion_detect_config1()
if result != FOSCAM_SUCCESS:
return result
current_config['isEnable'] = enabled
self.set_motion_detect_config1(current_confi... | def set_motion_detection1(self, enabled=1) | Get the current config and set the motion detection on or off | 5.841941 | 4.602057 | 1.26942 |
'''
Set alarm record config
Return: set result(0-success, -1-error)
'''
params = {'isEnablePreRecord': is_enable_prerecord,
'preRecordSecs' : prerecord_secs,
'alarmRecordSecs' : alarm_record_secs
}
return self.execu... | def set_alarm_record_config(self, is_enable_prerecord=1,
prerecord_secs=5, alarm_record_secs=300, callback=None) | Set alarm record config
Return: set result(0-success, -1-error) | 3.116446 | 2.313214 | 1.347237 |
'''
Set local alarm-record config
`is_enable_local_alarm_record`: 0 disable, 1 enable
'''
params = {'isEnableLocalAlarmRecord': is_enable_local_alarm_record,
'localAlarmRecordSecs' : local_alarm_record_secs}
return self.execute_command('setLocalAlarmR... | def set_local_alarm_record_config(self, is_enable_local_alarm_record = 1,
local_alarm_record_secs = 30, callback=None) | Set local alarm-record config
`is_enable_local_alarm_record`: 0 disable, 1 enable | 2.973768 | 2.508722 | 1.185371 |
'''
Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode
'''
params = {'mode': mode}
return self.execute_command('setH264FrmRefMode', params, callback) | def set_h264_frm_ref_mode(self, mode=1, callback=None) | Set frame shipping reference mode of H264 encode stream.
params:
`mode`: see docstr of meth::get_h264_frm_ref_mode | 6.64856 | 2.303739 | 2.885986 |
'''
Set schedule record config.
cmd: setScheduleRecordConfig
args: See docstring of meth::get_schedule_record_config
'''
params = {'isEnable' : is_enable,
'isEnableAudio': is_enable_audio,
'recordLevel' : record_level,
... | def set_schedule_record_config(self, is_enable, record_level,
space_full_mode, is_enable_audio,
schedule0 = 0, schedule1 = 0, schedule2 = 0,
schedule3 = 0, schedule4 = 0, schedule5 = 0,
... | Set schedule record config.
cmd: setScheduleRecordConfig
args: See docstring of meth::get_schedule_record_config | 2.174737 | 1.589836 | 1.3679 |
'''
Set Record path: sd/ftp
cmd: setRecordPath
param:
path: (0,SD), (2, FTP)
'''
params = {'Path': path}
return self.execute_command('setRecordPath', params, callback=callback) | def set_record_path(self, path, callback=None) | Set Record path: sd/ftp
cmd: setRecordPath
param:
path: (0,SD), (2, FTP) | 12.764165 | 2.839289 | 4.495549 |
'''
Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return
'''
params = {'offset': offset, 'count': count}
return self.execute_command('getLog', params, callback=callback) | def get_log(self, offset, count=10, callback=None) | Retrieve log records from camera.
cmd: getLog
param:
offset: log offset for first record
count: number of records to return | 5.993144 | 2.392113 | 2.505377 |
uri = get_uri(expnum, ccd, ext=APCOR_EXT, version=version, prefix=prefix)
apcor_file_name = tempfile.NamedTemporaryFile()
client.copy(uri, apcor_file_name.name)
apcor_file_name.seek(0)
return [float(x) for x in apcor_file_name.readline().split()] | def get_apcor(expnum, ccd, version='p', prefix=None) | retrieve the aperture correction for this exposure
@param expnum:
@param ccd:
@param version:
@param prefix:
@return: | 3.088296 | 3.244658 | 0.951809 |
if use_ssos:
ssois_server = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/cadcbin/ssos/fixedssos.pl"
params = dict(pos="{0:f},{1:f}".format(ra.to(units.degree).value, dec.to(units.degree).value))
result = requests.get(ssois_server, params=params)
table = ascii.read(result.text, ... | def cone_search(ra, dec, dra=0.01, ddec=0.01, mjdate=None, calibration_level=2, use_ssos=True,
collection='CFHTMEGAPIPE') | Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016)
where taken after mjd and have calibration 'observable'.
@param ra: RA center of search cont
@type ra: Quantity
@param dec: float degrees
@type dec: Quantity
@param dra: float degrees
@type dra: Quantity
... | 4.018058 | 3.832245 | 1.048487 |
data_dest = get_uri(dataset_name, version='o', ext=FITS_EXT)
data_source = "%s/%so.{}" % (data_web_service_url, dataset_name, FITS_EXT)
mkdir(os.path.dirname(data_dest))
try:
client.link(data_source, data_dest)
except IOError as e:
if e.errno == errno.EEXIST:
pass... | def populate(dataset_name, data_web_service_url=DATA_WEB_SERVICE + "CFHT") | Given a dataset_name created the desired dbimages directories
and links to the raw data files stored at CADC.
@param dataset_name: the name of the CFHT dataset to make a link to.
@param data_web_servica_url: the URL of the data web service run by CADC. | 2.738368 | 2.786143 | 0.982853 |
if prefix is None:
prefix = ""
if len(prefix) > 0:
prefix += "_"
if len(field) > 0:
field += "_"
if ext is None:
ext = ""
if len(ext) > 0 and ext[0] != ".":
ext = ".{}".format(ext)
measure3_dir = MEASURE3
if block is not None:
measure3_... | def get_cands_uri(field, ccd, version='p', ext='measure3.cands.astrom', prefix=None,
block=None) | return the nominal URI for a candidate file.
@param field: the OSSOS field name
@param ccd: which CCD are the candidates on
@param version: either the 'p', or 's' (scrambled) candidates.
@param ext: Perhaps we'll change this one day.
@param prefix: if this is a 'fake' dataset then add 'fk'
@par... | 2.776784 | 3.119092 | 0.890254 |
if subdir is None:
subdir = str(expnum)
if prefix is None:
prefix = ''
uri = os.path.join(DBIMAGES, subdir)
if ext is None:
ext = ''
elif len(ext) > 0 and ext[0] != '.':
ext = '.' + ext
if version is None:
version = ''
if ccd is None:
u... | def get_uri(expnum, ccd=None,
version='p', ext=FITS_EXT,
subdir=None, prefix=None) | Build the uri for an OSSOS image stored in the dbimages
containerNode.
:rtype : basestring
expnum: CFHT exposure number
ccd: CCD in the mosaic [0-35]
version: one of p,s,o etc.
dbimages: dbimages containerNode.
@type subdir: str
@param expnum: int
@param ccd:
@param version:
... | 2.092656 | 2.069851 | 1.011018 |
uri = tag_uri(key)
force = uri not in get_tags(expnum)
value = get_tags(expnum, force=force).get(uri, None)
return value | def get_tag(expnum, key) | given a key, return the vospace tag value.
@param expnum: Number of the CFHT exposure that a tag value is needed for
@param key: The process tag (such as mkpsf_00) that is being looked up.
@return: the value of the tag
@rtype: str | 6.256202 | 7.648252 | 0.817991 |
return "%s_%s%s" % (program, str(version), str(ccd).zfill(2)) | def get_process_tag(program, ccd, version='p') | make a process tag have a suffix indicating which ccd its for.
@param program: Name of the process that a tag is built for.
@param ccd: the CCD number that this process ran on.
@param version: The version of the exposure (s, p, o) that the process ran on.
@return: The string that represents the processi... | 4.778994 | 5.821305 | 0.820949 |
key = get_process_tag(prefix+task, ccd, version)
status = get_tag(expnum, key)
logger.debug('%s: %s' % (key, status))
if return_message:
return status
else:
return status == SUCCESS | def get_status(task, prefix, expnum, version, ccd, return_message=False) | Report back status of the given program by looking up the associated VOSpace annotation.
@param task: name of the process or task that will be checked.
@param prefix: prefix of the file that was processed (often fk or None)
@param expnum: which exposure number (or base filename)
@param version: which ... | 4.636395 | 5.774042 | 0.802972 |
return set_tag(expnum, get_process_tag(prefix+task, ccd, version), status) | def set_status(task, prefix, expnum, version, ccd, status) | set the processing status of the given program.
@param task: name of the processing task
@param prefix: was there a prefix on the exposure number processed?
@param expnum: exposure number processed.
@param version: which version of the exposure? (p, s, o)
@param ccd: the number of the CCD processing... | 10.699544 | 16.368608 | 0.653662 |
uri = observation.get_image_uri()
cutout_filehandle = tempfile.NamedTemporaryFile()
disposition_filename = client.copy(uri + "({},{},{})".format(sky_coord.ra.to('degree').value,
sky_coord.dec.to('degree').value,
... | def _cutout_expnum(observation, sky_coord, radius) | Get a cutout from an exposure based on the RA/DEC location.
@param observation: The Observation object that contains the expusre number information.
@type observation: Observation
@param sky_coord: which RA/DEC is needed,
@type sky_coord: SkyCoord
@param radius:
@type radius: Quantity
@retu... | 3.293226 | 3.261851 | 1.009619 |
result = {}
parts = re.search('(?P<expnum>\d{7})(?P<type>\S)(?P<ccd>\d\d)', frameid)
assert parts is not None
result['expnum'] = parts.group('expnum')
result['ccd'] = parts.group('ccd')
result['version'] = parts.group('type')
return result | def frame2expnum(frameid) | Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary. | 3.022684 | 2.576448 | 1.173198 |
if cutout is None or cutout == "[*,*]":
return datasec
try:
datasec = datasec_to_list(datasec)
except:
return datasec
# check for '-*' in the cutout string and replace is naxis:1
cutout = cutout.replace(" ", "")
cutout = cutout.replace("[-*,", "{}:1,".format(naxis1... | def reset_datasec(cutout, datasec, naxis1, naxis2) | reset the datasec to account for a possible cutout.
@param cutout:
@param datasec:
@param naxis1: size of the original image in the 'x' direction
@param naxis2: size of the oringal image in the 'y' direction
@return: | 2.270257 | 2.287745 | 0.992355 |
try:
# the filename is based on the Simple FITS images file.
filename = os.path.basename(uri)
if os.access(filename, os.F_OK) and cutout is None:
logger.debug("File already on disk: {}".format(filename))
hdu_list = fits.open(filename, scale_back=True)
... | def get_hdu(uri, cutout=None) | Get a at the given uri from VOSpace, possibly doing a cutout.
If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the
datasec to reflect the cutout area being used.
@param uri: The URI in VOSpace of the image to HDU to retrieve.
@param cutout: A CADC dat... | 3.685852 | 3.596856 | 1.024743 |
uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix)
if uri not in fwhm:
key = "fwhm_{:1s}{:02d}".format(version, int(ccd))
fwhm[uri] = get_tag(expnum, key)
return fwhm[uri] | def get_fwhm_tag(expnum, ccd, prefix=None, version='p') | Get the FWHM from the VOSpace annotation.
@param expnum:
@param ccd:
@param prefix:
@param version:
@return: | 3.582725 | 4.17249 | 0.858654 |
uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix)
filename = os.path.basename(uri)
try:
return fwhm[uri]
except:
pass
try:
fwhm[uri] = float(open(filename, 'r').read())
return fwhm[uri]
except:
pass
try:
fwhm[uri] = float(... | def get_fwhm(expnum, ccd, prefix=None, version='p') | Get the FWHM computed for the given expnum/ccd combo.
@param expnum:
@param ccd:
@param prefix:
@param version:
@return: | 2.883504 | 3.187603 | 0.9046 |
if prefix is not None:
DeprecationWarning("Prefix is no longer used here as the 'fk' and 's' have the same zeropoint.")
key = "zeropoint_{:1s}{:02d}".format(version, int(ccd))
return get_tag(expnum, key) | def _get_zeropoint(expnum, ccd, prefix=None, version='p') | Retrieve the zeropoint stored in the tags associated with this image.
@param expnum: Exposure number
@param ccd: ccd of the exposure
@param prefix: possible prefix (such as 'fk')
@param version: which version: p, s, or o ?
@return: zeropoint | 8.591647 | 6.920311 | 1.241512 |
uri = get_uri(expnum, ccd, version, ext='zeropoint.used', prefix=prefix)
try:
return zmag[uri]
except:
pass
try:
zmag[uri] = float(open_vos_or_local(uri).read())
return zmag[uri]
except:
pass
zmag[uri] = 0.0
return zmag[uri] | def get_zeropoint(expnum, ccd, prefix=None, version='p') | Get the zeropoint for this exposure using the zeropoint.used file created during source planting..
This command expects that there is a file called #######p##.zeropoint.used which contains the zeropoint.
@param expnum: exposure to get zeropoint of
@param ccd: which ccd (extension - 1) to get zp
@param... | 4.665434 | 5.497172 | 0.848697 |
dir_list = []
while not client.isdir(dirname):
dir_list.append(dirname)
dirname = os.path.dirname(dirname)
while len(dir_list) > 0:
logging.info("Creating directory: %s" % (dir_list[-1]))
try:
client.mkdir(dir_list.pop())
except IOError as e:
... | def mkdir(dirname) | make directory tree in vospace.
@param dirname: name of the directory to make | 2.355973 | 2.589327 | 0.909878 |
basename = os.path.basename(filename)
if os.access(basename, os.R_OK):
return open(basename, 'r')
kwargs['view'] = kwargs.get('view', 'data')
return client.open(filename, **kwargs) | def vofile(filename, **kwargs) | Open and return a handle on a VOSpace data connection
@param filename:
@param kwargs:
@return: | 4.203417 | 4.278344 | 0.982487 |
filename = os.path.basename(path)
if os.access(filename, os.F_OK):
return open(filename, mode)
if path.startswith("vos:"):
primary_mode = mode[0]
if primary_mode == "r":
vofile_mode = os.O_RDONLY
elif primary_mode == "w":
vofile_mode = os.O_WRONLY... | def open_vos_or_local(path, mode="rb") | Opens a file which can either be in VOSpace or the local filesystem.
@param path:
@param mode:
@return: | 2.350306 | 2.475609 | 0.949385 |
logger.info("copying {} -> {}".format(source, dest))
return client.copy(source, dest) | def copy(source, dest) | use the vospace service to get a file.
@param source:
@param dest:
@return: | 5.094041 | 7.195357 | 0.707962 |
source_uri = get_uri(s_expnum, ccd=s_ccd, version=s_version, ext=s_ext, prefix=s_prefix)
link_uri = get_uri(l_expnum, ccd=l_ccd, version=l_version, ext=l_ext, prefix=l_prefix)
return client.link(source_uri, link_uri) | def vlink(s_expnum, s_ccd, s_version, s_ext,
l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None) | make a link between two version of a file.
@param s_expnum:
@param s_ccd:
@param s_version:
@param s_ext:
@param l_expnum:
@param l_ccd:
@param l_version:
@param l_ext:
@param s_prefix:
@param l_prefix:
@return: | 1.961233 | 2.205441 | 0.88927 |
uri = get_uri(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix)
remove(uri) | def delete(expnum, ccd, version, ext, prefix=None) | delete a file, no error on does not exist
@param expnum:
@param ccd:
@param version:
@param ext:
@param prefix:
@return: | 3.46069 | 3.961998 | 0.873471 |
result = []
if pattern[0:4] == 'vos:':
dirname = os.path.dirname(pattern)
flist = listdir(dirname)
for fname in flist:
fname = '/'.join([dirname, fname])
if fnmatch.fnmatch(fname, pattern):
result.append(fname)
else:
result = glob(... | def my_glob(pattern) | get a listing matching pattern
@param pattern:
@return: | 2.957355 | 3.123401 | 0.946838 |
if get_property(node_uri, property_name, ossos_base) is None:
return False
else:
return True | def has_property(node_uri, property_name, ossos_base=True) | Checks if a node in VOSpace has the specified property.
@param node_uri:
@param property_name:
@param ossos_base:
@return: | 2.599616 | 3.562161 | 0.729786 |
# Must use force or we could have a cached copy of the node from before
# properties of interest were set/updated.
node = client.get_node(node_uri, force=True)
property_uri = tag_uri(property_name) if ossos_base else property_name
if property_uri not in node.props:
return None
ret... | def get_property(node_uri, property_name, ossos_base=True) | Retrieves the value associated with a property on a node in VOSpace.
@param node_uri:
@param property_name:
@param ossos_base:
@return: | 6.10891 | 7.579256 | 0.806004 |
node = client.get_node(node_uri)
property_uri = tag_uri(property_name) if ossos_base else property_name
# If there is an existing value, clear it first
if property_uri in node.props:
node.props[property_uri] = None
client.add_props(node)
node.props[property_uri] = property_val... | def set_property(node_uri, property_name, property_value, ossos_base=True) | Sets the value of a property on a node in VOSpace. If the property
already has a value then it is first cleared and then set.
@param node_uri:
@param property_name:
@param property_value:
@param ossos_base:
@return: | 3.067299 | 3.342695 | 0.917613 |
logger.info("Epoch Field: {}, OBJECT_COUNT {}".format(str(epoch_field), str(OBJECT_COUNT)))
tag = epoch_field[1] + "-" + OBJECT_COUNT
if dry_run:
tag += "-DRYRUN"
return tag | def build_counter_tag(epoch_field, dry_run=False) | Builds the tag for the counter of a given epoch/field, without the OSSOS base.
@param epoch_field:
@param dry_run:
@return: | 5.532773 | 5.755036 | 0.961379 |
return get_property(node_uri, build_counter_tag(epoch_field, dry_run),
ossos_base=True) | def read_object_counter(node_uri, epoch_field, dry_run=False) | Reads the object counter for the given epoch/field on the specified node.
@param node_uri:
@param epoch_field:
@param dry_run:
@return: the current object count. | 16.346027 | 23.490711 | 0.695851 |
current_count = read_object_counter(node_uri, epoch_field, dry_run=dry_run)
if current_count is None:
new_count = "01"
else:
new_count = coding.base36encode(coding.base36decode(current_count) + 1,
pad_length=2)
set_property(node_uri,
... | def increment_object_counter(node_uri, epoch_field, dry_run=False) | Increment the object counter used to create unique object identifiers.
@param node_uri:
@param epoch_field:
@param dry_run:
@return: The object count AFTER incrementing. | 4.430201 | 5.036512 | 0.879617 |
prefix = prefix is None and "" or prefix
mopheader_uri = dbimages_uri(expnum=expnum,
ccd=ccd,
version=version,
prefix=prefix,
ext='.mopheader')
if mopheader_uri in mophead... | def get_mopheader(expnum, ccd, version='p', prefix=None) | Retrieve the mopheader, either from cache or from vospace
@param expnum:
@param ccd:
@param version:
@param prefix:
@return: Header | 3.468978 | 3.66869 | 0.945563 |
version = 'p'
key = "{}{}".format(expnum, version)
if key in sgheaders:
return sgheaders[key]
url = "http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHTSG/{}{}.head".format(expnum, version)
logging.getLogger("requests").setLevel(logging.ERROR)
logging.debug("Attempting to re... | def _get_sghead(expnum) | Use the data web service to retrieve the stephen's astrometric header.
:param expnum: CFHT exposure number you want the header for
:rtype : list of astropy.io.fits.Header objects. | 3.800102 | 3.917 | 0.970156 |
if uri not in astheaders:
astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header
return astheaders[uri] | def get_header(uri) | Pull a FITS header from observation at the given URI
@param uri: The URI of the image in VOSpace. | 8.749885 | 10.761759 | 0.813053 |
logger.debug("Getting ast header for {}".format(expnum))
if version == 'p':
try:
# Get the SG header if possible.
sg_key = "{}{}".format(expnum, version)
if sg_key not in sgheaders:
_get_sghead(expnum)
if sg_key in sgheaders:
... | def get_astheader(expnum, ccd, version='p', prefix=None) | Retrieve the header for a given dbimages file.
@param expnum: CFHT odometer number
@param ccd: which ccd based extension (0..35)
@param version: 'o','p', or 's'
@param prefix:
@return: | 2.691925 | 2.69864 | 0.997512 |
return "{}{}_{}{:02d}".format(self.target.prefix,
self,
self.target.version,
self.target.ccd) | def tag(self) | Get the string representation of the tag used to annotate the status in VOSpace.
@return: str | 11.367978 | 11.576779 | 0.981964 |
mjds = []
fobjs = []
for expnum in expnums:
filename = storage.get_image(expnum, ccd=ccd, version=version)
fobjs.append(fits.open(filename))
# Pull out values to replace in headers.. must pull them
# as otherwise we get pointers...
mjds.append(fobjs[-1][0].heade... | def scramble(expnums, ccd, version='p', dry_run=False) | run the plant script on this combination of exposures | 3.162954 | 3.249759 | 0.973289 |
parser = argparse.ArgumentParser()
parser.add_argument('--ccd',
action='store',
type=int,
default=None,
help='which ccd to process')
parser.add_argument("--dbimages",
action="store",... | def main() | Run the script. | 3.483778 | 3.486645 | 0.999178 |
## confirm destination directory exists.
destdir = os.path.dirname(
storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='fits'))
if not dry_run:
storage.mkdir(destdir)
## get image from the vospace storage area
filename = storage.get_image(expnum, ccd, version... | def mk_mopheader(expnum, ccd, version, dry_run=False, prefix="") | Run the OSSOS mopheader script. | 5.244447 | 5.014111 | 1.045938 |
import sre
lines=file(filename).readlines()
exps=[]
cands=[]
coo=[]
for line in lines:
if ( line[0:2]=="##" ) :
break
exps.append(line[2:].strip())
for line in lines:
if ( line[0]=="#" ) :
continue
if len(line.strip())==0:
... | def read_cands(filename) | Read in the contents of a cands comb file | 4.117061 | 4.040324 | 1.018993 |
import pyraf, pyfits
pyraf.iraf.tv()
display = pyraf.iraf.tv.display
width=128
cands = record['cands']
exps= record['fileId']
### load some header info from the mophead file
headers={}
for exp in exps:
f = pyfits.open(exp+".fits")
headers[exp]={}
... | def discands(record) | Display the candidates contained in a candidate record list | 3.015643 | 2.944246 | 1.02425 |
data = {"QUERY": ("SELECT Observation.target_name as TargetName, "
"COORD1(CENTROID(Plane.position_bounds)) AS RA,"
"COORD2(CENTROID(Plane.position_bounds)) AS DEC, "
"Plane.time_bounds_lower AS StartDate, "
"Plane.time_ex... | def query_for_observations(mjd, observable, runid_list) | Do a QUERY on the TAP service for all observations that are part of runid,
where taken after mjd and have calibration 'observable'.
Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables
mjd : float
observable: str ( 2 or 1 )
runid: tuple eg. ('13AP05', '13AP06') | 4.22634 | 4.219917 | 1.001522 |
logging.info("writing text log to %s" % outfile)
stamp = "#\n# Last Updated: " + time.asctime() + "\n#\n"
header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % (
"EXPNUM", "OBS-DATE", "FIELD", "EXPTIME(s)", "RA", "DEC", "RUNID")
bar = "=" * (len(header) - 1) + "\n"
if out... | def create_ascii_table(observation_table, outfile) | Given a table of observations create an ascii log file for easy parsing.
Store the result in outfile (could/should be a vospace dataNode)
observation_table: astropy.votable.array object
outfile: str (name of the vospace dataNode to store the result to) | 2.96825 | 2.928652 | 1.013521 |
# camera dimensions
width = 0.98
height = 0.98
ax = None
if outfile[0:4] == 'vos:':
temp_file = tempfile.NamedTemporaryFile(suffix='.pdf')
pdf = PdfPages(temp_file.name)
else:
pdf = PdfPages(outfile)
saturn = ephem.Saturn()
uranus = ephem.Uranus()
t2 ... | def create_sky_plot(observation_table, outfile) | Given a VOTable that describes the observation coverage provide a PDF of the skycoverge.
observation_table: vostable.arrary
outfile: name of file to write results to. | 2.896281 | 2.88966 | 1.002292 |
for filename in filenames:
if re.search(regex, filename) is None:
logging.warning("Skipping {}".format(filename))
continue
print os.path.join(path,filename)
obs = mpc.MPCReader().read(os.path.join(path,filename))
for ob in obs:
if rename:
... | 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.
:rtype : None
:param observations: dictionary to store observtions into
:param path: the directory where filenames are.
:param filenames: list of file... | 3.200444 | 3.25457 | 0.983369 |
fits.PrimaryHDU(header=self).writeto(filename, output_verify='ignore', **kwargs) | def writeto(self, filename, **kwargs) | Write the header to a fits file.
:param filename:
:return: | 5.359096 | 6.322858 | 0.847575 |
try:
return self.wcs.crpix1, self.wcs.crpix2
except Exception as ex:
logging.debug("Couldn't get CRPIX from WCS: {}".format(ex))
logging.debug("Switching to use DATASEC for CRPIX value computation.")
try:
(x1, x2), (y1, y2) = util.get_pix... | def crpix(self) | The location of the reference coordinate in the pixel frame.
First simple respond with the header values, if they don't exist try usnig the DETSEC values
@rtype: float, float | 3.761746 | 3.664411 | 1.026562 |
# TODO Check if this exposure was taken afer or before correction needed.
try:
utc_end = self['UTCEND']
exposure_time = float(self['EXPTIME'])
date_obs = self['DATE-OBS']
except KeyError as ke:
raise KeyError("Header missing keyword: {}, ... | def mjd_obsc(self) | Given a CFHT Megaprime image header compute the center of exposure.
This routine uses the calibration provide by Richard Wainscoat:
From: Richard Wainscoat <rjw@ifa.hawaii.edu>
Subject: Fwd: timing for MegaCam
Date: April 24, 2015 at 7:23:09 PM EDT
To: David Tholen <tholen@ifa.... | 5.075913 | 4.242062 | 1.196568 |
try:
return self.wcs.crval1, self.wcs.crval2
except Exception as ex:
logging.debug("Couldn't get CRVAL from WCS: {}".format(ex))
logging.debug("Trying RA/DEC values")
try:
return (float(self['RA-DEG']),
float(self['DEC... | def crval(self) | Get the world coordinate of the reference pixel.
@rtype: float, float | 5.437424 | 5.629509 | 0.965879 |
try:
(x, y) = self['NAXIS1'] / 2.0, self['NAXIS2'] / 2.0
p1 = SkyCoord(*self.wcs.xy2sky(x, y) * units.degree)
p2 = SkyCoord(*self.wcs.xy2sky(x + 1, y + 1) * units.degree)
return round(p1.separation(p2).to(units.arcsecond).value / math.sqrt(2), 3)
... | def pixscale(self) | Return the pixel scale of the detector, in arcseconds.
This routine first attempts to compute the size of a pixel using the WCS. Then looks for PIXSCAL in header.
@return: pixscal
@rtype: float | 3.391782 | 3.254286 | 1.042251 |
import os, string
rate_command='rate.pl --file %s %d ' % ( file, au_min)
rate=os.popen(rate_command)
line=rate.readline()
print line
rate.close()
(min_rate, min_ang, min_aw, min_rmin, min_rmax)=string.split(line)
rate_command='rate.pl --file %s %d ' % ( file, au_min)
rate=os.po... | def get_rates(file,au_min=25,au_max=150) | Use the rates program to determine the minimum and maximum bounds for planting | 2.498686 | 2.387107 | 1.046742 |
header=get_rates(file)
print header
import pyfits
hdulist=pyfits.open(file)
header['xmin']=1
header['xmax']=hdulist[0].header.get('NAXIS1',2048)
header['ymin']=1
header['aw']=round(header['aw'],2)
header['angle']=round(header['angle'],2)
header['ymax']=hdulist[0].header.get... | def kbo_gen(file,outfile='objects.list',mmin=22.5,mmax=24.5) | Generate a file with object moving at a range of rates and angles | 2.47321 | 2.469882 | 1.001347 |
parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.')
parser.add_argument("--filter",
action="store",
default='r',
dest="filter",
choices=['r', 'u'],... | def main() | Input asteroid family, filter type, and image type to query SSOIS | 4.100593 | 3.493634 | 1.173733 |
# establish input
family_list = '{}/{}_family.txt'.format(_FAMILY_LISTS, familyname)
if os.path.exists(family_list):
with open(family_list) as infile:
filestr = infile.read()
object_list = filestr.split('\n') # array of objects to query
elif familyname == 'all':
... | def get_family_info(familyname, filtertype='r', imagetype='p') | Query the ssois table for images of objects in a given family. Then parse through for desired image type,
filter, exposure time, and telescope instrument | 4.377736 | 4.387337 | 0.997812 |
# From the given input, identify the desired filter and rename appropriately Replace this?
if filtertype.lower().__contains__('r'):
filtertype = 'r.MP9601' # this is the old (standard) r filter for MegaCam
if filtertype.lower().__contains__('u'):
filtertype = 'u.MP9... | def get_member_info(object_name, filtertype='r', imagetype='p') | Query the ssois table for images of a given object. Then parse through for desired image type,
filter, exposure time, and telescope instrument | 3.728878 | 3.580092 | 1.041559 |
assert camera_filter in ['r.MP9601', 'u.MP9301']
ret_table = []
good_table = 0
table_reader = ascii.get_reader(Reader=ascii.Basic)
table_reader.inconsistent_handler = _skip_missing_data
table_reader.header.splitter.delimiter = '\t'
table_reader.data.splitter.delimiter = '\t'
tabl... | def parse_ssois_return(ssois_return, object_name, imagetype, camera_filter='r.MP9601',
telescope_instrument='CFHT/MegaCam') | Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument | 7.084015 | 7.133688 | 0.993037 |
pos1 = pos2 = numpy.array([])
if len(mopfile1.data) > 0:
X_COL = "X_{}".format(mopfile1.header.file_ids[0])
Y_COL = "Y_{}".format(mopfile1.header.file_ids[0])
pos1 = numpy.array([mopfile1.data[X_COL].data, mopfile1.data[Y_COL].data]).transpose()
if len(mopfile2.data) > 0:
... | def match_mopfiles(mopfile1, mopfile2) | Given an input list of 'real' detections and candidate detections provide a result file that contains
the measured values from candidate detections with a flag indicating if they are real or false.
@rtype MOPFile
@return mopfile2 with a new column containing index of matching entry in mopfile1 | 2.425078 | 2.387207 | 1.015864 |
import daophot
image_downloader = ImageDownloader()
observations = {}
for measure in measures:
for reading in measure:
if reading.obs not in observations:
observations[reading.obs] = {'x': [],
'y': [],
... | def measure_mags(measures) | Given a list of readings compute the magnitudes for all sources in each reading.
@param measures: list of readings
@return: None | 4.244061 | 4.1951 | 1.011671 |
if len(self) == 0:
# Special case, we make this the current item
self.index = 0
self.items.append(item) | def append(self, item) | Adds a new item to the end of the collection. | 7.084687 | 6.504266 | 1.089237 |
"At the moment this just checks for a single user's missing reals. Easy to generalise it to all users."
con = context.get_context(vos_dir)
user_progress = []
listing = con.get_listing(tasks.get_suffix('reals'))
mpc_listing = con.get_listing('mpc')
for filename in listing:
if not filename... | def fix_tags_on_cands_missing_reals(user_id, vos_dir, property) | At the moment this just checks for a single user's missing reals. Easy to generalise it to all users. | 6.21602 | 5.026667 | 1.236609 |
if error_class is None:
error_class = self.error_class if self.error_class else Error
return error_class(message) | def make_error(self,
message: str,
*,
error: Exception = None,
# ``error_class: Type[Exception]=None`` doesn't work on
# Python 3.5.2, but that is exact version ran by Read the
# Docs :( More info: http://s... | Return error instantiated from given message.
:param message: Message to wrap.
:param error: Validation error.
:param error_class:
Special class to wrap error message into. When omitted
``self.error_class`` will be used. | 3.180523 | 3.757568 | 0.846431 |
r
if not self._valid_request:
logger.error('Request not validated, cannot make response')
raise self.make_error('Request not validated before, cannot make '
'response')
if data is None and self.response_factory is None:
logge... | def make_response(self,
data: Any = None,
**kwargs: Any) -> Any | r"""Validate response data and wrap it inside response factory.
:param data: Response data. Could be ommited.
:param \*\*kwargs: Keyword arguments to be passed to response factory. | 4.243394 | 4.47116 | 0.949059 |
r
request_schema = getattr(self.module, 'request', None)
if request_schema is None:
logger.error(
'Request schema should be defined',
extra={'schema_module': self.module,
'schema_module_attrs': dir(self.module)})
rais... | def validate_request(self,
data: Any,
*additional: AnyMapping,
merged_class: Type[dict] = dict) -> Any | r"""Validate request data against request schema from module.
:param data: Request data.
:param \*additional:
Additional data dicts to be merged with base request data.
:param merged_class:
When additional data dicts supplied method by default will return
mer... | 3.980393 | 3.756464 | 1.059612 |
r
return defaults(
dict(data) if not isinstance(data, dict) else data,
*(dict(item) for item in additional)) | def _merge_data(self, data: AnyMapping, *additional: AnyMapping) -> dict | r"""Merge base data and additional dicts.
:param data: Base data.
:param \*additional: Additional data dicts to be merged into base dict. | 8.99755 | 11.700839 | 0.768966 |
if not isinstance(data, dict) and not isinstance(data, list):
try:
return dict(data)
except TypeError:
...
return data | def _pure_data(self, data: Any) -> Any | If data is dict-like object, convert it to pure dict instance, so it
will be possible to pass to default ``jsonschema.validate`` func.
:param data: Request or response data. | 4.489616 | 4.465111 | 1.005488 |
try:
return self.validate_func(schema, self._pure_data(data))
except self.validation_error_class as err:
logger.error(
'Schema validation error',
exc_info=True,
extra={'schema': schema, 'schema_module': self.module})
... | def _validate(self, data: Any, schema: AnyMapping) -> Any | Validate data against given schema.
:param data: Data to validate.
:param schema: Schema to use for validation. | 4.9669 | 5.087576 | 0.97628 |
if certfile is None:
certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem")
dirname = os.path.dirname(certfile)
try:
os.makedirs(dirname)
except OSError as e:
if os.path.isdir(dirname):
pass
elif e.errno == 20 or e.errno == 17:
... | def getCert(certHost=vos.vos.SERVER, certfile=None,
certQuery="/cred/proxyCert?daysValid=",daysValid=2) | Access the cadc certificate server | 2.813158 | 2.804776 | 1.002989 |
if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK):
auth=netrc.netrc().authenticators(host)
else:
auth=False
if not auth:
sys.stdout.write("CADC Username: ")
username=sys.stdin.readline().strip('\n')
password=getpass.getpass().strip('\n')
... | def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca') | Getting the username/password for host from .netrc filie | 2.381068 | 2.336179 | 1.019214 |
for ops in ops_set:
for fake in ops[0]:
for my_program in ops[1]:
for version in ops[2]:
props = {}
for ccd in my_ccds:
# print my_expnum, fake, my_program, version, ccd
key = storage.get_process_tag(fake + my_pr... | def clear_tags(my_expnum, ops_set, my_ccds, dry_run=True) | Clear the tags for the given expnum/ccd set.
@param ops:
@param my_expnum:
@return: | 4.356419 | 4.512883 | 0.965329 |
return bool(strtobool(value) if isinstance(value, str) else value) | def to_bool(value: Any) -> bool | Convert string or other Python object to boolean.
**Rationalle**
Passing flags is one of the most common cases of using environment vars and
as values are strings we need to have an easy way to convert them to
boolean Python value.
Without this function int or float string values can be converted... | 5.50982 | 8.238966 | 0.668751 |
try:
return int(value)
except (TypeError, ValueError):
return default | def to_int(value: str, default: T = None) -> Union[int, Optional[T]] | Convert given value to int.
If conversion failed, return default value without raising Exception.
:param value: Value to convert to int.
:param default: Default value to use in case of failed conversion. | 3.406627 | 5.389091 | 0.632134 |
rows=[]
for row in results:
row_dict={}
for idx in range(len(row)):
col=description[idx][0]
row_dict[col]=row[idx]
rows.append(row_dict)
return rows | def mk_dict(results,description) | Given a result list and descrition sequence, return a list
of dictionaries | 2.421654 | 2.535599 | 0.955062 |
sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, )
cfeps.execute(sql)
return mk_dict(cfeps.fetchall(),cfeps.description) | def get_orbits(official='%') | Query the orbit table for the object whose official desingation
matches parameter official. By default all entries are returned | 12.59014 | 11.230323 | 1.121084 |
sql= "SELECT m.* FROM measure m "
sql+="LEFT JOIN object o ON m.provisional LIKE o.provisional "
if not official:
sql+="WHERE o.official IS NULL"
else:
sql+="WHERE o.official LIKE '%s' " % ( official, )
sql+=" AND m.provisional LIKE '%s' " % ( provisional, )
cfeps.execut... | def get_astrom(official='%',provisional='%') | Query the measure table for all measurements of a particular object.
Default is to return all the astrometry in the measure table,
sorted by mjdate | 5.753785 | 5.645362 | 1.019206 |
DATA="www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca"
BASE="http://"+DATA+"/authProxy/getData"
archive="CFHT"
wcs="corrected"
import re
groups=re.match('^(?P<file_id>\d{6}).*',file_id)
if not groups:
return None
file_id=groups.group('file_id')
file_id+="p"
#### THIS IS N... | def getData(file_id,ra,dec) | Create a link that connects to a getData URL | 7.108197 | 6.602393 | 1.076609 |
ev = api.Event.create(self.journal.collection, event)
ev.save() | def create_event(self, event) | Create event
Parameters
----------
event : iCalendar file as a string
(calendar containing one event to be added) | 15.200665 | 19.465807 | 0.780891 |
ev_for_change = self.calendar.get(uid)
ev_for_change.content = event
ev_for_change.save() | def update_event(self, event, uid) | Edit event
Parameters
----------
event : iCalendar file as a string
(calendar containing one event to be updated)
uid : uid of event to be updated | 6.615431 | 7.235276 | 0.91433 |
ev_for_deletion = self.calendar.get(uid)
ev_for_deletion.delete() | def delete_event(self, uid) | Delete event and sync calendar
Parameters
----------
uid : uid of event to be deleted | 7.929069 | 8.772215 | 0.903884 |
def decorator(cls):
provider = \
ff.UserSpecifiedIdProvider(key='_id') \
if user_supplied_id else ff.UuidProvider()
class Settings(ff.PersistenceSettings):
id_provider = provider
key_builder = ff.StringDelimitedKeyBuilder('|')
databa... | def simple_lmdb_settings(path, map_size=1e9, user_supplied_id=False) | Creates a decorator that can be used to configure sane default LMDB
persistence settings for a model
Args:
path (str): The path where the LMDB database files will be created
map_size (int): The amount of space to allot for the database | 4.863418 | 4.890857 | 0.99439 |
class Settings(ff.PersistenceSettings):
id_provider = ff.UuidProvider()
key_builder = ff.StringDelimitedKeyBuilder()
database = ff.InMemoryDatabase(key_builder=key_builder)
class Model(cls, Settings):
pass
Model.__name__ = cls.__name__
Model.__module__ = cls.__mod... | def simple_in_memory_settings(cls) | Decorator that returns a class that "persists" data in-memory. Mostly
useful for testing
:param cls: the class whose features should be persisted in-memory
:return: A new class that will persist features in memory | 5.908762 | 5.616461 | 1.052044 |
eta = self._geometry[self.camera][index]["ra"]
xi = self._geometry[self.camera][index]["dec"]
ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree
dec = self.origin.dec - xi * units.degree + 45 * units.arcsec
self._coordinate = SkyCoord(ra, dec) | def offset(self, index=0) | Offset the camera pointing to be centred on a particular CCD. | 6.463771 | 5.659998 | 1.142009 |
if self._coordinate is None:
self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec)
return self._coordinate | def coord(self) | The center of the camera pointing in sky coordinates | 5.876308 | 4.972664 | 1.181722 |
if self.coord is None:
return None
ra = self.coord.ra.degree
dec = self.coord.dec.degree
ccds = []
for geo in self._geometry[self.camera]:
ycen = geo["dec"] + dec
xcen = geo["ra"] / math.cos(math.radians(ycen)) + ra
try:
... | def geometry(self) | Return an array of rectangles that represent the 'ra,dec' corners of the FOV
@rtype: list | 3.154958 | 2.889744 | 1.091778 |
if self.coord is None:
return None
return self.coord.separation(SkyCoord(ra, dec, unit=('degree', 'degree'))) | def separation(self, ra, dec) | Compute the separation between self and (ra,dec) | 3.961631 | 3.942603 | 1.004826 |
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])
if opt.verbose:
print "Trimming [%d:%d,%d:%d]" % ( l,r,b,t)
hdu.data = hdu.data[b:t,l:r]
hdu.header.update('DATA... | def trim(hdu) | TRIM a CFHT MEGAPRIME frame using the DATASEC keyword | 2.987444 | 2.837576 | 1.052815 |
for amp in (['A','B']):
AMPKW= 'ASEC'+amp
BIASKW= 'BSEC'+amp
dsec=re.findall(r'(\d+)',
hdu.header.get(AMPKW))
bias=re.findall(r'(\d+)',
hdu.header.get(BIASKW))
## the X-boundaries set the amp section off from the b... | def overscan(hdu) | Overscan subtract a CFHT MEGAPRIME frame.
oversan(hdu) --> status
The BIAS section keywords are expected to be BSEC[A|B] (for amps
A and B) and the AMP sectoin is ASEC[A|B]. | 6.16191 | 5.69248 | 1.082465 |
def new_lock_requiring_function(self, filename, *args, **kwargs):
if self.owns_lock(filename):
return function(self, filename, *args, **kwargs)
else:
raise RequiresLockException()
return new_lock_requiring_function | def requires_lock(function) | Decorator to check if the user owns the required lock.
The first argument must be the filename. | 4.155181 | 2.87009 | 1.447753 |
if suffixes is None:
suffixes = [DONE_SUFFIX, LOCK_SUFFIX, PART_SUFFIX]
for suffix in suffixes:
listing = self.working_context.get_listing(suffix)
for filename in listing:
self.working_context.remove(filename) | def clean(self, suffixes=None) | Remove all persistence-related files from the directory. | 4.829145 | 4.361286 | 1.107276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.