repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.change_user_name
def change_user_name(self, usrname, newusrname, callback=None): ''' Change user name. ''' params = {'usrName': usrname, 'newUsrName': newusrname, } return self.execute_command('changeUserName', params, callback=callback)
python
def change_user_name(self, usrname, newusrname, callback=None): ''' Change user name. ''' params = {'usrName': usrname, 'newUsrName': newusrname, } return self.execute_command('changeUserName', params, callback=callback)
[ "def", "change_user_name", "(", "self", ",", "usrname", ",", "newusrname", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'usrName'", ":", "usrname", ",", "'newUsrName'", ":", "newusrname", ",", "}", "return", "self", ".", "execute_command", ...
Change user name.
[ "Change", "user", "name", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L363-L370
train
47,700
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.change_password
def change_password(self, usrname, oldpwd, newpwd, callback=None): ''' Change password. ''' params = {'usrName': usrname, 'oldPwd' : oldpwd, 'newPwd' : newpwd, } return self.execute_command('changePassword', params, callback=callback)
python
def change_password(self, usrname, oldpwd, newpwd, callback=None): ''' 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", ")", ":", "params", "=", "{", "'usrName'", ":", "usrname", ",", "'oldPwd'", ":", "oldpwd", ",", "'newPwd'", ":", "newpwd", ",", "}", "ret...
Change password.
[ "Change", "password", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L372-L381
train
47,701
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_system_time
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 ''' if ntp_server not in ['time.nist.gov', 'time.kriss.re.kr', 'time.windows.com', 'time.nuri.net', ]: raise ValueError('Unsupported ntpServer') params = {'timeSource': time_source, 'ntpServer' : ntp_server, 'dateFormat': date_format, 'timeFormat': time_format, 'timeZone' : time_zone, 'isDst' : is_dst, 'dst' : dst, 'year' : year, 'mon' : mon, 'day' : day, 'hour' : hour, 'minute' : minute, 'sec' : sec } return self.execute_command('setSystemTime', params, callback=callback)
python
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 ''' if ntp_server not in ['time.nist.gov', 'time.kriss.re.kr', 'time.windows.com', 'time.nuri.net', ]: raise ValueError('Unsupported ntpServer') params = {'timeSource': time_source, 'ntpServer' : ntp_server, 'dateFormat': date_format, 'timeFormat': time_format, 'timeZone' : time_zone, 'isDst' : is_dst, 'dst' : dst, 'year' : year, 'mon' : mon, 'day' : day, 'hour' : hour, 'minute' : minute, 'sec' : sec } return self.execute_command('setSystemTime', params, callback=callback)
[ "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...
Set systeim time
[ "Set", "systeim", "time" ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L385-L413
train
47,702
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.set_dev_name
def set_dev_name(self, devname, callback=None): ''' Set camera name ''' params = {'devName': devname.encode('gbk')} return self.execute_command('setDevName', params, callback=callback)
python
def set_dev_name(self, devname, callback=None): ''' Set camera name ''' params = {'devName': devname.encode('gbk')} return self.execute_command('setDevName', params, callback=callback)
[ "def", "set_dev_name", "(", "self", ",", "devname", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'devName'", ":", "devname", ".", "encode", "(", "'gbk'", ")", "}", "return", "self", ".", "execute_command", "(", "'setDevName'", ",", "param...
Set camera name
[ "Set", "camera", "name" ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L427-L432
train
47,703
viswa-swami/python-foscam
libpyfoscam/foscam.py
FoscamCamera.ptz_goto_preset
def ptz_goto_preset(self, name, callback=None): ''' Move to preset. ''' params = {'name': name} return self.execute_command('ptzGotoPresetPoint', params, callback=callback)
python
def ptz_goto_preset(self, name, callback=None): ''' Move to preset. ''' params = {'name': name} return self.execute_command('ptzGotoPresetPoint', params, callback=callback)
[ "def", "ptz_goto_preset", "(", "self", ",", "name", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'name'", ":", "name", "}", "return", "self", ".", "execute_command", "(", "'ptzGotoPresetPoint'", ",", "params", ",", "callback", "=", "callbac...
Move to preset.
[ "Move", "to", "preset", "." ]
d76f2f7016959b7b758751637fad103c9032e488
https://github.com/viswa-swami/python-foscam/blob/d76f2f7016959b7b758751637fad103c9032e488/libpyfoscam/foscam.py#L560-L565
train
47,704
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_apcor
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: """ 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()]
python
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: """ 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", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "ext", "=", "APCOR_EXT", ",", "version", "=", "version", ",", "prefix", "=", "pr...
retrieve the aperture correction for this exposure @param expnum: @param ccd: @param version: @param prefix: @return:
[ "retrieve", "the", "aperture", "correction", "for", "this", "exposure" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L108-L121
train
47,705
OSSOS/MOP
src/ossos/core/ossos/storage.py
populate
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. """ 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 else: raise e header_dest = get_uri(dataset_name, version='o', ext='head') header_source = "%s/%so.fits.fz?cutout=[0]" % ( data_web_service_url, dataset_name) try: client.link(header_source, header_dest) except IOError as e: if e.errno == errno.EEXIST: pass else: raise e header_dest = get_uri(dataset_name, version='p', ext='head') header_source = "%s/%s/%sp.head" % ( 'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub', 'CFHTSG', dataset_name) try: client.link(header_source, header_dest) except IOError as e: if e.errno == errno.EEXIST: pass else: raise e return True
python
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. """ 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 else: raise e header_dest = get_uri(dataset_name, version='o', ext='head') header_source = "%s/%so.fits.fz?cutout=[0]" % ( data_web_service_url, dataset_name) try: client.link(header_source, header_dest) except IOError as e: if e.errno == errno.EEXIST: pass else: raise e header_dest = get_uri(dataset_name, version='p', ext='head') header_source = "%s/%s/%sp.head" % ( 'http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub', 'CFHTSG', dataset_name) try: client.link(header_source, header_dest) except IOError as e: if e.errno == errno.EEXIST: pass else: raise e return True
[ "def", "populate", "(", "dataset_name", ",", "data_web_service_url", "=", "DATA_WEB_SERVICE", "+", "\"CFHT\"", ")", ":", "data_dest", "=", "get_uri", "(", "dataset_name", ",", "version", "=", "'o'", ",", "ext", "=", "FITS_EXT", ")", "data_source", "=", "\"%s/%...
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.
[ "Given", "a", "dataset_name", "created", "the", "desired", "dbimages", "directories", "and", "links", "to", "the", "raw", "data", "files", "stored", "at", "CADC", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L215-L257
train
47,706
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_cands_uri
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' @param block: Which BLOCK of the field are we looking at? eg. 15BS+1+1 @return: """ 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_dir + "/{}".format(block) return "{}/{}{}{}{}{}".format(measure3_dir, prefix, field, version, ccd, ext)
python
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' @param block: Which BLOCK of the field are we looking at? eg. 15BS+1+1 @return: """ 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_dir + "/{}".format(block) return "{}/{}{}{}{}{}".format(measure3_dir, prefix, field, version, ccd, ext)
[ "def", "get_cands_uri", "(", "field", ",", "ccd", ",", "version", "=", "'p'", ",", "ext", "=", "'measure3.cands.astrom'", ",", "prefix", "=", "None", ",", "block", "=", "None", ")", ":", "if", "prefix", "is", "None", ":", "prefix", "=", "\"\"", "if", ...
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' @param block: Which BLOCK of the field are we looking at? eg. 15BS+1+1 @return:
[ "return", "the", "nominal", "URI", "for", "a", "candidate", "file", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L260-L289
train
47,707
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_uri
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: @param ext: @param subdir: @param prefix: """ 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: uri = os.path.join(uri, '%s%s%s%s' % (prefix, str(expnum), version, ext)) else: ccd = str(ccd).zfill(2) uri = os.path.join(uri, 'ccd{}'.format(ccd), '%s%s%s%s%s' % (prefix, str(expnum), version, ccd, ext)) return uri
python
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: @param ext: @param subdir: @param prefix: """ 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: uri = os.path.join(uri, '%s%s%s%s' % (prefix, str(expnum), version, ext)) else: ccd = str(ccd).zfill(2) uri = os.path.join(uri, 'ccd{}'.format(ccd), '%s%s%s%s%s' % (prefix, str(expnum), version, ccd, ext)) return uri
[ "def", "get_uri", "(", "expnum", ",", "ccd", "=", "None", ",", "version", "=", "'p'", ",", "ext", "=", "FITS_EXT", ",", "subdir", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "subdir", "is", "None", ":", "subdir", "=", "str", "(", "ex...
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: @param ext: @param subdir: @param prefix:
[ "Build", "the", "uri", "for", "an", "OSSOS", "image", "stored", "in", "the", "dbimages", "containerNode", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L292-L340
train
47,708
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_tag
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 """ uri = tag_uri(key) force = uri not in get_tags(expnum) value = get_tags(expnum, force=force).get(uri, None) return value
python
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 """ 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", ")", ":", "uri", "=", "tag_uri", "(", "key", ")", "force", "=", "uri", "not", "in", "get_tags", "(", "expnum", ")", "value", "=", "get_tags", "(", "expnum", ",", "force", "=", "force", ")", ".", "get", ...
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
[ "given", "a", "key", "return", "the", "vospace", "tag", "value", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L413-L425
train
47,709
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_process_tag
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 processing tag. """ return "%s_%s%s" % (program, str(version), str(ccd).zfill(2))
python
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 processing tag. """ return "%s_%s%s" % (program, str(version), str(ccd).zfill(2))
[ "def", "get_process_tag", "(", "program", ",", "ccd", ",", "version", "=", "'p'", ")", ":", "return", "\"%s_%s%s\"", "%", "(", "program", ",", "str", "(", "version", ")", ",", "str", "(", "ccd", ")", ".", "zfill", "(", "2", ")", ")" ]
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 processing tag.
[ "make", "a", "process", "tag", "have", "a", "suffix", "indicating", "which", "ccd", "its", "for", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L428-L436
train
47,710
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_status
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 version of that exposure (p, s, o) @param ccd: which CCD within the exposure. @param return_message: Return what did the TAG said or just /True/False/ for Success/Failure? @return: the status of the processing based on the annotation value. """ 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
python
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 version of that exposure (p, s, o) @param ccd: which CCD within the exposure. @param return_message: Return what did the TAG said or just /True/False/ for Success/Failure? @return: the status of the processing based on the annotation value. """ 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", ")", ":", "key", "=", "get_process_tag", "(", "prefix", "+", "task", ",", "ccd", ",", "version", ")", "status", "=", "get_t...
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 version of that exposure (p, s, o) @param ccd: which CCD within the exposure. @param return_message: Return what did the TAG said or just /True/False/ for Success/Failure? @return: the status of the processing based on the annotation value.
[ "Report", "back", "status", "of", "the", "given", "program", "by", "looking", "up", "the", "associated", "VOSpace", "annotation", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L571-L589
train
47,711
OSSOS/MOP
src/ossos/core/ossos/storage.py
set_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. @param status: What status to record: "SUCCESS" we hope. @return: Success? """ return set_tag(expnum, get_process_tag(prefix+task, ccd, version), status)
python
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. @param status: What status to record: "SUCCESS" we hope. @return: Success? """ return set_tag(expnum, get_process_tag(prefix+task, ccd, version), status)
[ "def", "set_status", "(", "task", ",", "prefix", ",", "expnum", ",", "version", ",", "ccd", ",", "status", ")", ":", "return", "set_tag", "(", "expnum", ",", "get_process_tag", "(", "prefix", "+", "task", ",", "ccd", ",", "version", ")", ",", "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. @param status: What status to record: "SUCCESS" we hope. @return: Success?
[ "set", "the", "processing", "status", "of", "the", "given", "program", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L592-L603
train
47,712
OSSOS/MOP
src/ossos/core/ossos/storage.py
frame2expnum
def frame2expnum(frameid): """Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary.""" 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
python
def frame2expnum(frameid): """Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary.""" 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", ")", ":", "result", "=", "{", "}", "parts", "=", "re", ".", "search", "(", "'(?P<expnum>\\d{7})(?P<type>\\S)(?P<ccd>\\d\\d)'", ",", "frameid", ")", "assert", "parts", "is", "not", "None", "result", "[", "'expnum'", "]", ...
Given a standard OSSOS frameid return the expnum, version and ccdnum as a dictionary.
[ "Given", "a", "standard", "OSSOS", "frameid", "return", "the", "expnum", "version", "and", "ccdnum", "as", "a", "dictionary", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L806-L814
train
47,713
OSSOS/MOP
src/ossos/core/ossos/storage.py
reset_datasec
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: """ 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)) cutout = cutout.replace(",-*]", ",{}:1]".format(naxis2)) cutout = cutout.replace("[*,", "[1:{},".format(naxis1)) cutout = cutout.replace(",*]", ",1:{}]".format(naxis1)) try: cutout = [int(x) for x in re.findall(r"([-+]?[*\d]+?)[:,\]]+", cutout)] except: logger.debug("Failed to processes the cutout pattern: {}".format(cutout)) return datasec if len(cutout) == 5: # cutout likely starts with extension, remove cutout = cutout[1:] # -ve integer offsets indicate offset from the end of array. for idx in [0, 1]: if cutout[idx] < 0: cutout[idx] = naxis1 - cutout[idx] + 1 for idx in [2, 3]: if cutout[idx] < 0: cutout[idx] = naxis2 - cutout[idx] + 1 flip = cutout[0] > cutout[1] flop = cutout[2] > cutout[3] logger.debug("Working with cutout: {}".format(cutout)) if flip: cutout = [naxis1 - cutout[0] + 1, naxis1 - cutout[1] + 1, cutout[2], cutout[3]] datasec = [naxis1 - datasec[1] + 1, naxis1 - datasec[0] + 1, datasec[2], datasec[3]] if flop: cutout = [cutout[0], cutout[1], naxis2 - cutout[2] + 1, naxis2 - cutout[3] + 1] datasec = [datasec[0], datasec[1], naxis2 - datasec[3] + 1, naxis2 - datasec[2] + 1] datasec = [max(datasec[0] - cutout[0] + 1, 1), min(datasec[1] - cutout[0] + 1, naxis1), max(datasec[2] - cutout[2] + 1, 1), min(datasec[3] - cutout[2] + 1, naxis2)] return "[{}:{},{}:{}]".format(datasec[0], datasec[1], datasec[2], datasec[3])
python
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: """ 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)) cutout = cutout.replace(",-*]", ",{}:1]".format(naxis2)) cutout = cutout.replace("[*,", "[1:{},".format(naxis1)) cutout = cutout.replace(",*]", ",1:{}]".format(naxis1)) try: cutout = [int(x) for x in re.findall(r"([-+]?[*\d]+?)[:,\]]+", cutout)] except: logger.debug("Failed to processes the cutout pattern: {}".format(cutout)) return datasec if len(cutout) == 5: # cutout likely starts with extension, remove cutout = cutout[1:] # -ve integer offsets indicate offset from the end of array. for idx in [0, 1]: if cutout[idx] < 0: cutout[idx] = naxis1 - cutout[idx] + 1 for idx in [2, 3]: if cutout[idx] < 0: cutout[idx] = naxis2 - cutout[idx] + 1 flip = cutout[0] > cutout[1] flop = cutout[2] > cutout[3] logger.debug("Working with cutout: {}".format(cutout)) if flip: cutout = [naxis1 - cutout[0] + 1, naxis1 - cutout[1] + 1, cutout[2], cutout[3]] datasec = [naxis1 - datasec[1] + 1, naxis1 - datasec[0] + 1, datasec[2], datasec[3]] if flop: cutout = [cutout[0], cutout[1], naxis2 - cutout[2] + 1, naxis2 - cutout[3] + 1] datasec = [datasec[0], datasec[1], naxis2 - datasec[3] + 1, naxis2 - datasec[2] + 1] datasec = [max(datasec[0] - cutout[0] + 1, 1), min(datasec[1] - cutout[0] + 1, naxis1), max(datasec[2] - cutout[2] + 1, 1), min(datasec[3] - cutout[2] + 1, naxis2)] return "[{}:{},{}:{}]".format(datasec[0], datasec[1], datasec[2], datasec[3])
[ "def", "reset_datasec", "(", "cutout", ",", "datasec", ",", "naxis1", ",", "naxis2", ")", ":", "if", "cutout", "is", "None", "or", "cutout", "==", "\"[*,*]\"", ":", "return", "datasec", "try", ":", "datasec", "=", "datasec_to_list", "(", "datasec", ")", ...
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:
[ "reset", "the", "datasec", "to", "account", "for", "a", "possible", "cutout", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L956-L1017
train
47,714
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_hdu
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 data service CUTOUT paramter to be used when retrieving the observation. @return: fits.HDU """ 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) hdu_list.verify('silentfix+ignore') else: logger.debug("Pulling: {}{} from VOSpace".format(uri, cutout)) fpt = tempfile.NamedTemporaryFile(suffix='.fits') cutout = cutout is not None and cutout or "" copy(uri+cutout, fpt.name) fpt.seek(0, 2) fpt.seek(0) logger.debug("Read from vospace completed. Building fits object.") hdu_list = fits.open(fpt, scale_back=False) hdu_list.verify('silentfix+ignore') logger.debug("Got image from vospace") try: hdu_list[0].header['DATASEC'] = reset_datasec(cutout, hdu_list[0].header['DATASEC'], hdu_list[0].header['NAXIS1'], hdu_list[0].header['NAXIS2']) except Exception as e: logging.debug("error converting datasec: {}".format(str(e))) for hdu in hdu_list: logging.debug("Adding converter to {}".format(hdu)) hdu.converter = CoordinateConverter(0, 0) try: hdu.wcs = WCS(hdu.header) except Exception as ex: logger.error("Failed trying to initialize the WCS: {}".format(ex)) except Exception as ex: raise ex return hdu_list
python
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 data service CUTOUT paramter to be used when retrieving the observation. @return: fits.HDU """ 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) hdu_list.verify('silentfix+ignore') else: logger.debug("Pulling: {}{} from VOSpace".format(uri, cutout)) fpt = tempfile.NamedTemporaryFile(suffix='.fits') cutout = cutout is not None and cutout or "" copy(uri+cutout, fpt.name) fpt.seek(0, 2) fpt.seek(0) logger.debug("Read from vospace completed. Building fits object.") hdu_list = fits.open(fpt, scale_back=False) hdu_list.verify('silentfix+ignore') logger.debug("Got image from vospace") try: hdu_list[0].header['DATASEC'] = reset_datasec(cutout, hdu_list[0].header['DATASEC'], hdu_list[0].header['NAXIS1'], hdu_list[0].header['NAXIS2']) except Exception as e: logging.debug("error converting datasec: {}".format(str(e))) for hdu in hdu_list: logging.debug("Adding converter to {}".format(hdu)) hdu.converter = CoordinateConverter(0, 0) try: hdu.wcs = WCS(hdu.header) except Exception as ex: logger.error("Failed trying to initialize the WCS: {}".format(ex)) except Exception as ex: raise ex return hdu_list
[ "def", "get_hdu", "(", "uri", ",", "cutout", "=", "None", ")", ":", "try", ":", "# the filename is based on the Simple FITS images file.", "filename", "=", "os", ".", "path", ".", "basename", "(", "uri", ")", "if", "os", ".", "access", "(", "filename", ",", ...
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 data service CUTOUT paramter to be used when retrieving the observation. @return: fits.HDU
[ "Get", "a", "at", "the", "given", "uri", "from", "VOSpace", "possibly", "doing", "a", "cutout", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1020-L1066
train
47,715
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_fwhm_tag
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: """ 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]
python
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: """ 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'", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", "=", "'fwhm'", ",", "prefix", "=", "prefix", ")", "if"...
Get the FWHM from the VOSpace annotation. @param expnum: @param ccd: @param prefix: @param version: @return:
[ "Get", "the", "FWHM", "from", "the", "VOSpace", "annotation", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1093-L1107
train
47,716
OSSOS/MOP
src/ossos/core/ossos/storage.py
_get_zeropoint
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 """ 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)
python
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 """ 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'", ")", ":", "if", "prefix", "is", "not", "None", ":", "DeprecationWarning", "(", "\"Prefix is no longer used here as the 'fk' and 's' have the same zeropoint.\"",...
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
[ "Retrieve", "the", "zeropoint", "stored", "in", "the", "tags", "associated", "with", "this", "image", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1143-L1156
train
47,717
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_zeropoint
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 prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint """ 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]
python
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 prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint """ 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'", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", "=", "'zeropoint.used'", ",", "prefix", "=", "prefix", ...
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 prefix: possible string prefixed to expsoure number. @param version: one of [spo] as in #######p## @return: zeropoint
[ "Get", "the", "zeropoint", "for", "this", "exposure", "using", "the", "zeropoint", ".", "used", "file", "created", "during", "source", "planting", ".." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1159-L1183
train
47,718
OSSOS/MOP
src/ossos/core/ossos/storage.py
mkdir
def mkdir(dirname): """make directory tree in vospace. @param dirname: name of the directory to make """ 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: if e.errno == errno.EEXIST: pass else: raise e
python
def mkdir(dirname): """make directory tree in vospace. @param dirname: name of the directory to make """ 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: if e.errno == errno.EEXIST: pass else: raise e
[ "def", "mkdir", "(", "dirname", ")", ":", "dir_list", "=", "[", "]", "while", "not", "client", ".", "isdir", "(", "dirname", ")", ":", "dir_list", ".", "append", "(", "dirname", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "dirname", ...
make directory tree in vospace. @param dirname: name of the directory to make
[ "make", "directory", "tree", "in", "vospace", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1186-L1204
train
47,719
OSSOS/MOP
src/ossos/core/ossos/storage.py
vofile
def vofile(filename, **kwargs): """ Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return: """ 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)
python
def vofile(filename, **kwargs): """ Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return: """ 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", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "if", "os", ".", "access", "(", "basename", ",", "os", ".", "R_OK", ")", ":", "return", "open", "(", "...
Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return:
[ "Open", "and", "return", "a", "handle", "on", "a", "VOSpace", "data", "connection" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1207-L1218
train
47,720
OSSOS/MOP
src/ossos/core/ossos/storage.py
open_vos_or_local
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: """ 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 elif primary_mode == "a": vofile_mode = os.O_APPEND else: raise ValueError("Can't open with mode %s" % mode) return vofile(path, mode=vofile_mode) else: return open(path, mode)
python
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: """ 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 elif primary_mode == "a": vofile_mode = os.O_APPEND else: raise ValueError("Can't open with mode %s" % mode) return vofile(path, mode=vofile_mode) else: return open(path, mode)
[ "def", "open_vos_or_local", "(", "path", ",", "mode", "=", "\"rb\"", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "os", ".", "access", "(", "filename", ",", "os", ".", "F_OK", ")", ":", "return", "open", "(...
Opens a file which can either be in VOSpace or the local filesystem. @param path: @param mode: @return:
[ "Opens", "a", "file", "which", "can", "either", "be", "in", "VOSpace", "or", "the", "local", "filesystem", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1221-L1245
train
47,721
OSSOS/MOP
src/ossos/core/ossos/storage.py
copy
def copy(source, dest): """ use the vospace service to get a file. @param source: @param dest: @return: """ logger.info("copying {} -> {}".format(source, dest)) return client.copy(source, dest)
python
def copy(source, dest): """ use the vospace service to get a file. @param source: @param dest: @return: """ logger.info("copying {} -> {}".format(source, dest)) return client.copy(source, dest)
[ "def", "copy", "(", "source", ",", "dest", ")", ":", "logger", ".", "info", "(", "\"copying {} -> {}\"", ".", "format", "(", "source", ",", "dest", ")", ")", "return", "client", ".", "copy", "(", "source", ",", "dest", ")" ]
use the vospace service to get a file. @param source: @param dest: @return:
[ "use", "the", "vospace", "service", "to", "get", "a", "file", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1248-L1258
train
47,722
OSSOS/MOP
src/ossos/core/ossos/storage.py
vlink
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: """ 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)
python
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: """ 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", ")", ":", "source_uri", "=", "get_uri", "(", "s_ex...
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:
[ "make", "a", "link", "between", "two", "version", "of", "a", "file", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1261-L1280
train
47,723
OSSOS/MOP
src/ossos/core/ossos/storage.py
delete
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: """ uri = get_uri(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix) remove(uri)
python
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: """ uri = get_uri(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix) remove(uri)
[ "def", "delete", "(", "expnum", ",", "ccd", ",", "version", ",", "ext", ",", "prefix", "=", "None", ")", ":", "uri", "=", "get_uri", "(", "expnum", ",", "ccd", "=", "ccd", ",", "version", "=", "version", ",", "ext", "=", "ext", ",", "prefix", "="...
delete a file, no error on does not exist @param expnum: @param ccd: @param version: @param ext: @param prefix: @return:
[ "delete", "a", "file", "no", "error", "on", "does", "not", "exist" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1290-L1302
train
47,724
OSSOS/MOP
src/ossos/core/ossos/storage.py
my_glob
def my_glob(pattern): """ get a listing matching pattern @param pattern: @return: """ 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(pattern) return result
python
def my_glob(pattern): """ get a listing matching pattern @param pattern: @return: """ 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(pattern) return result
[ "def", "my_glob", "(", "pattern", ")", ":", "result", "=", "[", "]", "if", "pattern", "[", "0", ":", "4", "]", "==", "'vos:'", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "pattern", ")", "flist", "=", "listdir", "(", "dirname", "...
get a listing matching pattern @param pattern: @return:
[ "get", "a", "listing", "matching", "pattern" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1305-L1322
train
47,725
OSSOS/MOP
src/ossos/core/ossos/storage.py
has_property
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: """ if get_property(node_uri, property_name, ossos_base) is None: return False else: return True
python
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: """ 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", ")", ":", "if", "get_property", "(", "node_uri", ",", "property_name", ",", "ossos_base", ")", "is", "None", ":", "return", "False", "else", ":", "return", "True" ]
Checks if a node in VOSpace has the specified property. @param node_uri: @param property_name: @param ossos_base: @return:
[ "Checks", "if", "a", "node", "in", "VOSpace", "has", "the", "specified", "property", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1351-L1363
train
47,726
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_property
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: """ # 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 return node.props[property_uri]
python
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: """ # 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 return node.props[property_uri]
[ "def", "get_property", "(", "node_uri", ",", "property_name", ",", "ossos_base", "=", "True", ")", ":", "# 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_...
Retrieves the value associated with a property on a node in VOSpace. @param node_uri: @param property_name: @param ossos_base: @return:
[ "Retrieves", "the", "value", "associated", "with", "a", "property", "on", "a", "node", "in", "VOSpace", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1366-L1383
train
47,727
OSSOS/MOP
src/ossos/core/ossos/storage.py
set_property
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: """ 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_value client.add_props(node)
python
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: """ 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_value client.add_props(node)
[ "def", "set_property", "(", "node_uri", ",", "property_name", ",", "property_value", ",", "ossos_base", "=", "True", ")", ":", "node", "=", "client", ".", "get_node", "(", "node_uri", ")", "property_uri", "=", "tag_uri", "(", "property_name", ")", "if", "oss...
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:
[ "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", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1386-L1406
train
47,728
OSSOS/MOP
src/ossos/core/ossos/storage.py
increment_object_counter
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. """ 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, build_counter_tag(epoch_field, dry_run=dry_run), new_count, ossos_base=True) return new_count
python
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. """ 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, build_counter_tag(epoch_field, dry_run=dry_run), new_count, ossos_base=True) return new_count
[ "def", "increment_object_counter", "(", "node_uri", ",", "epoch_field", ",", "dry_run", "=", "False", ")", ":", "current_count", "=", "read_object_counter", "(", "node_uri", ",", "epoch_field", ",", "dry_run", "=", "dry_run", ")", "if", "current_count", "is", "N...
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.
[ "Increment", "the", "object", "counter", "used", "to", "create", "unique", "object", "identifiers", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1439-L1462
train
47,729
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_mopheader
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 """ 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 mopheaders: return mopheaders[mopheader_uri] filename = os.path.basename(mopheader_uri) if os.access(filename, os.F_OK): logger.debug("File already on disk: {}".format(filename)) mopheader_fpt = StringIO(open(filename, 'r').read()) else: mopheader_fpt = StringIO(open_vos_or_local(mopheader_uri).read()) with warnings.catch_warnings(): warnings.simplefilter('ignore', AstropyUserWarning) mopheader = fits.open(mopheader_fpt) # add some values to the mopheader so it can be an astrom header too. header = mopheader[0].header try: header['FWHM'] = get_fwhm(expnum, ccd) except IOError: header['FWHM'] = 10 header['SCALE'] = mopheader[0].header['PIXSCALE'] header['NAX1'] = header['NAXIS1'] header['NAX2'] = header['NAXIS2'] header['MOPversion'] = header['MOP_VER'] header['MJD_OBS_CENTER'] = str(Time(header['MJD-OBSC'], format='mjd', scale='utc', precision=5).replicate(format='mpc')) header['MAXCOUNT'] = MAXCOUNT mopheaders[mopheader_uri] = header mopheader.close() return mopheaders[mopheader_uri]
python
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 """ 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 mopheaders: return mopheaders[mopheader_uri] filename = os.path.basename(mopheader_uri) if os.access(filename, os.F_OK): logger.debug("File already on disk: {}".format(filename)) mopheader_fpt = StringIO(open(filename, 'r').read()) else: mopheader_fpt = StringIO(open_vos_or_local(mopheader_uri).read()) with warnings.catch_warnings(): warnings.simplefilter('ignore', AstropyUserWarning) mopheader = fits.open(mopheader_fpt) # add some values to the mopheader so it can be an astrom header too. header = mopheader[0].header try: header['FWHM'] = get_fwhm(expnum, ccd) except IOError: header['FWHM'] = 10 header['SCALE'] = mopheader[0].header['PIXSCALE'] header['NAX1'] = header['NAXIS1'] header['NAX2'] = header['NAXIS2'] header['MOPversion'] = header['MOP_VER'] header['MJD_OBS_CENTER'] = str(Time(header['MJD-OBSC'], format='mjd', scale='utc', precision=5).replicate(format='mpc')) header['MAXCOUNT'] = MAXCOUNT mopheaders[mopheader_uri] = header mopheader.close() return mopheaders[mopheader_uri]
[ "def", "get_mopheader", "(", "expnum", ",", "ccd", ",", "version", "=", "'p'", ",", "prefix", "=", "None", ")", ":", "prefix", "=", "prefix", "is", "None", "and", "\"\"", "or", "prefix", "mopheader_uri", "=", "dbimages_uri", "(", "expnum", "=", "expnum",...
Retrieve the mopheader, either from cache or from vospace @param expnum: @param ccd: @param version: @param prefix: @return: Header
[ "Retrieve", "the", "mopheader", "either", "from", "cache", "or", "from", "vospace" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1465-L1512
train
47,730
OSSOS/MOP
src/ossos/core/ossos/storage.py
_get_sghead
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. """ 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 retrieve {}".format(url)) resp = requests.get(url) if resp.status_code != 200: raise IOError(errno.ENOENT, "Could not get {}".format(url)) header_str_list = re.split('END \n', resp.content) # # make the first entry in the list a Null headers = [None] for header_str in header_str_list: headers.append(fits.Header.fromstring(header_str, sep='\n')) logging.debug(headers[-1].get('EXTVER', -1)) sgheaders[key] = headers return sgheaders[key]
python
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. """ 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 retrieve {}".format(url)) resp = requests.get(url) if resp.status_code != 200: raise IOError(errno.ENOENT, "Could not get {}".format(url)) header_str_list = re.split('END \n', resp.content) # # make the first entry in the list a Null headers = [None] for header_str in header_str_list: headers.append(fits.Header.fromstring(header_str, sep='\n')) logging.debug(headers[-1].get('EXTVER', -1)) sgheaders[key] = headers return sgheaders[key]
[ "def", "_get_sghead", "(", "expnum", ")", ":", "version", "=", "'p'", "key", "=", "\"{}{}\"", ".", "format", "(", "expnum", ",", "version", ")", "if", "key", "in", "sgheaders", ":", "return", "sgheaders", "[", "key", "]", "url", "=", "\"http://www.cadc-c...
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.
[ "Use", "the", "data", "web", "service", "to", "retrieve", "the", "stephen", "s", "astrometric", "header", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1515-L1543
train
47,731
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_header
def get_header(uri): """ Pull a FITS header from observation at the given URI @param uri: The URI of the image in VOSpace. """ if uri not in astheaders: astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header return astheaders[uri]
python
def get_header(uri): """ Pull a FITS header from observation at the given URI @param uri: The URI of the image in VOSpace. """ if uri not in astheaders: astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header return astheaders[uri]
[ "def", "get_header", "(", "uri", ")", ":", "if", "uri", "not", "in", "astheaders", ":", "astheaders", "[", "uri", "]", "=", "get_hdu", "(", "uri", ",", "cutout", "=", "\"[1:1,1:1]\"", ")", "[", "0", "]", ".", "header", "return", "astheaders", "[", "u...
Pull a FITS header from observation at the given URI @param uri: The URI of the image in VOSpace.
[ "Pull", "a", "FITS", "header", "from", "observation", "at", "the", "given", "URI" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1546-L1554
train
47,732
OSSOS/MOP
src/ossos/core/ossos/storage.py
get_astheader
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: """ 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: for header in sgheaders[sg_key]: if header.get('EXTVER', -1) == int(ccd): return header except: pass try: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header except: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits.fz') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits.fz') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header return astheaders[ast_uri]
python
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: """ 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: for header in sgheaders[sg_key]: if header.get('EXTVER', -1) == int(ccd): return header except: pass try: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header except: ast_uri = dbimages_uri(expnum, ccd, version=version, ext='.fits.fz') if ast_uri not in astheaders: hdulist = get_image(expnum, ccd=ccd, version=version, prefix=prefix, cutout="[1:1,1:1]", return_file=False, ext='.fits.fz') assert isinstance(hdulist, fits.HDUList) astheaders[ast_uri] = hdulist[0].header return astheaders[ast_uri]
[ "def", "get_astheader", "(", "expnum", ",", "ccd", ",", "version", "=", "'p'", ",", "prefix", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Getting ast header for {}\"", ".", "format", "(", "expnum", ")", ")", "if", "version", "==", "'p'", ":", ...
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:
[ "Retrieve", "the", "header", "for", "a", "given", "dbimages", "file", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1557-L1595
train
47,733
OSSOS/MOP
src/ossos/core/ossos/storage.py
Task.tag
def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: str """ return "{}{}_{}{:02d}".format(self.target.prefix, self, self.target.version, self.target.ccd)
python
def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: str """ return "{}{}_{}{:02d}".format(self.target.prefix, self, self.target.version, self.target.ccd)
[ "def", "tag", "(", "self", ")", ":", "return", "\"{}{}_{}{:02d}\"", ".", "format", "(", "self", ".", "target", ".", "prefix", ",", "self", ",", "self", ".", "target", ".", "version", ",", "self", ".", "target", ".", "ccd", ")" ]
Get the string representation of the tag used to annotate the status in VOSpace. @return: str
[ "Get", "the", "string", "representation", "of", "the", "tag", "used", "to", "annotate", "the", "status", "in", "VOSpace", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L468-L476
train
47,734
OSSOS/MOP
src/ossos/core/scripts/scramble.py
scramble
def scramble(expnums, ccd, version='p', dry_run=False): """run the plant script on this combination of exposures""" 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].header['MJD-OBS']) order = [0, 2, 1] for idx in range(len(fobjs)): logging.info("Flipping %d to %d" % (fobjs[idx][0].header['EXPNUM'], expnums[order[idx]])) fobjs[idx][0].header['EXPNUM'] = expnums[order[idx]] fobjs[idx][0].header['MJD-OBS'] = mjds[order[idx]] uri = storage.get_uri(expnums[order[idx]], ccd=ccd, version='s', ext='fits') fname = os.path.basename(uri) if os.access(fname, os.F_OK): os.unlink(fname) fobjs[idx].writeto(fname) if dry_run: continue storage.copy(fname, uri) return
python
def scramble(expnums, ccd, version='p', dry_run=False): """run the plant script on this combination of exposures""" 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].header['MJD-OBS']) order = [0, 2, 1] for idx in range(len(fobjs)): logging.info("Flipping %d to %d" % (fobjs[idx][0].header['EXPNUM'], expnums[order[idx]])) fobjs[idx][0].header['EXPNUM'] = expnums[order[idx]] fobjs[idx][0].header['MJD-OBS'] = mjds[order[idx]] uri = storage.get_uri(expnums[order[idx]], ccd=ccd, version='s', ext='fits') fname = os.path.basename(uri) if os.access(fname, os.F_OK): os.unlink(fname) fobjs[idx].writeto(fname) if dry_run: continue storage.copy(fname, uri) return
[ "def", "scramble", "(", "expnums", ",", "ccd", ",", "version", "=", "'p'", ",", "dry_run", "=", "False", ")", ":", "mjds", "=", "[", "]", "fobjs", "=", "[", "]", "for", "expnum", "in", "expnums", ":", "filename", "=", "storage", ".", "get_image", "...
run the plant script on this combination of exposures
[ "run", "the", "plant", "script", "on", "this", "combination", "of", "exposures" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/scramble.py#L37-L67
train
47,735
OSSOS/MOP
src/jjk/preproc/t.py
read_cands
def read_cands(filename): """Read in the contents of a cands comb file""" 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: if len(coo)!=0: cands.append(coo) coo=[] continue vals=line.split() cols=['x','y','x_0','y_0','flux','size','max_int','elon'] values={} for j in range(len(cols)): col=cols.pop().strip() val=vals.pop().strip() values[col]=float(val) coo.append(values) cands.append(coo) return {'fileId': exps, 'cands': cands}
python
def read_cands(filename): """Read in the contents of a cands comb file""" 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: if len(coo)!=0: cands.append(coo) coo=[] continue vals=line.split() cols=['x','y','x_0','y_0','flux','size','max_int','elon'] values={} for j in range(len(cols)): col=cols.pop().strip() val=vals.pop().strip() values[col]=float(val) coo.append(values) cands.append(coo) return {'fileId': exps, 'cands': cands}
[ "def", "read_cands", "(", "filename", ")", ":", "import", "sre", "lines", "=", "file", "(", "filename", ")", ".", "readlines", "(", ")", "exps", "=", "[", "]", "cands", "=", "[", "]", "coo", "=", "[", "]", "for", "line", "in", "lines", ":", "if",...
Read in the contents of a cands comb file
[ "Read", "in", "the", "contents", "of", "a", "cands", "comb", "file" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/t.py#L4-L34
train
47,736
OSSOS/MOP
src/ossos/core/ossos/planning/ObsStatus.py
query_for_observations
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') """ 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_exposure AS ExposureTime, " "Observation.instrument_name AS Instrument, " "Plane.energy_bandpassName AS Filter, " "Observation.observationID AS dataset_name, " "Observation.proposal_id AS ProposalID, " "Observation.proposal_pi AS PI " "FROM caom2.Observation AS Observation " "JOIN caom2.Plane AS Plane ON " "Observation.obsID = Plane.obsID " "WHERE ( Observation.collection = 'CFHT' ) " "AND Plane.time_bounds_lower > %d " "AND Plane.calibrationLevel=%s " "AND Observation.proposal_id IN %s ") % (mjd, observable, str(runid_list)), "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} result = requests.get(storage.TAP_WEB_SERVICE, params=data, verify=False) assert isinstance(result, requests.Response) logging.debug("Doing TAP Query using url: %s" % (str(result.url))) temp_file = tempfile.NamedTemporaryFile() with open(temp_file.name, 'w') as outfile: outfile.write(result.text) try: vot = parse(temp_file.name).get_first_table() except Exception as ex: logging.error(str(ex)) logging.error(result.text) raise ex vot.array.sort(order='StartDate') t = vot.array temp_file.close() logging.debug("Got {} lines from tap query".format(len(t))) return t
python
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') """ 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_exposure AS ExposureTime, " "Observation.instrument_name AS Instrument, " "Plane.energy_bandpassName AS Filter, " "Observation.observationID AS dataset_name, " "Observation.proposal_id AS ProposalID, " "Observation.proposal_pi AS PI " "FROM caom2.Observation AS Observation " "JOIN caom2.Plane AS Plane ON " "Observation.obsID = Plane.obsID " "WHERE ( Observation.collection = 'CFHT' ) " "AND Plane.time_bounds_lower > %d " "AND Plane.calibrationLevel=%s " "AND Observation.proposal_id IN %s ") % (mjd, observable, str(runid_list)), "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} result = requests.get(storage.TAP_WEB_SERVICE, params=data, verify=False) assert isinstance(result, requests.Response) logging.debug("Doing TAP Query using url: %s" % (str(result.url))) temp_file = tempfile.NamedTemporaryFile() with open(temp_file.name, 'w') as outfile: outfile.write(result.text) try: vot = parse(temp_file.name).get_first_table() except Exception as ex: logging.error(str(ex)) logging.error(result.text) raise ex vot.array.sort(order='StartDate') t = vot.array temp_file.close() logging.debug("Got {} lines from tap query".format(len(t))) return t
[ "def", "query_for_observations", "(", "mjd", ",", "observable", ",", "runid_list", ")", ":", "data", "=", "{", "\"QUERY\"", ":", "(", "\"SELECT Observation.target_name as TargetName, \"", "\"COORD1(CENTROID(Plane.position_bounds)) AS RA,\"", "\"COORD2(CENTROID(Plane.position_boun...
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')
[ "Do", "a", "QUERY", "on", "the", "TAP", "service", "for", "all", "observations", "that", "are", "part", "of", "runid", "where", "taken", "after", "mjd", "and", "have", "calibration", "observable", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/ObsStatus.py#L22-L74
train
47,737
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.crpix
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 """ 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_pixel_bounds_from_datasec_keyword(self['DETSEC']) dx = float(self['NAXIS1']) dy = float(self['NAXIS2']) except KeyError as ke: raise KeyError("Header missing keyword: {}, required for CRPIX[12] computation".format(ke.args[0])) crpix1 = self._DET_X_CEN - (x1 + x2) / 2. + dx / 2. crpix2 = self._DET_Y_CEN - (y1 + y2) / 2. + dy / 2. return crpix1, crpix2
python
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 """ 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_pixel_bounds_from_datasec_keyword(self['DETSEC']) dx = float(self['NAXIS1']) dy = float(self['NAXIS2']) except KeyError as ke: raise KeyError("Header missing keyword: {}, required for CRPIX[12] computation".format(ke.args[0])) crpix1 = self._DET_X_CEN - (x1 + x2) / 2. + dx / 2. crpix2 = self._DET_Y_CEN - (y1 + y2) / 2. + dy / 2. return crpix1, crpix2
[ "def", "crpix", "(", "self", ")", ":", "try", ":", "return", "self", ".", "wcs", ".", "crpix1", ",", "self", ".", "wcs", ".", "crpix2", "except", "Exception", "as", "ex", ":", "logging", ".", "debug", "(", "\"Couldn't get CRPIX from WCS: {}\"", ".", "for...
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
[ "The", "location", "of", "the", "reference", "coordinate", "in", "the", "pixel", "frame", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L99-L122
train
47,738
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.mjd_obsc
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.hawaii.edu> Looks like the midpoint of the exposure is now UTCEND - 0.73 sec - (exposure time / 2 ) Wobble on the 0.73 sec is +/- 0.15 sec. @rtype : float """ # 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: {}, required for MJD-OBSC computation".format(ke.args[0])) utc_end = Time(date_obs + "T" + utc_end) utc_cen = utc_end - TimeDelta(0.73, format='sec') - TimeDelta(exposure_time / 2.0, format='sec') return round(utc_cen.mjd, 7)
python
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.hawaii.edu> Looks like the midpoint of the exposure is now UTCEND - 0.73 sec - (exposure time / 2 ) Wobble on the 0.73 sec is +/- 0.15 sec. @rtype : float """ # 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: {}, required for MJD-OBSC computation".format(ke.args[0])) utc_end = Time(date_obs + "T" + utc_end) utc_cen = utc_end - TimeDelta(0.73, format='sec') - TimeDelta(exposure_time / 2.0, format='sec') return round(utc_cen.mjd, 7)
[ "def", "mjd_obsc", "(", "self", ")", ":", "# TODO Check if this exposure was taken afer or before correction needed.", "try", ":", "utc_end", "=", "self", "[", "'UTCEND'", "]", "exposure_time", "=", "float", "(", "self", "[", "'EXPTIME'", "]", ")", "date_obs", "=", ...
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.hawaii.edu> Looks like the midpoint of the exposure is now UTCEND - 0.73 sec - (exposure time / 2 ) Wobble on the 0.73 sec is +/- 0.15 sec. @rtype : float
[ "Given", "a", "CFHT", "Megaprime", "image", "header", "compute", "the", "center", "of", "exposure", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L125-L151
train
47,739
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.crval
def crval(self): """ Get the world coordinate of the reference pixel. @rtype: float, float """ 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-DEG'])) except KeyError as ke: KeyError("Can't build CRVAL1/2 missing keyword: {}".format(ke.args[0]))
python
def crval(self): """ Get the world coordinate of the reference pixel. @rtype: float, float """ 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-DEG'])) except KeyError as ke: KeyError("Can't build CRVAL1/2 missing keyword: {}".format(ke.args[0]))
[ "def", "crval", "(", "self", ")", ":", "try", ":", "return", "self", ".", "wcs", ".", "crval1", ",", "self", ".", "wcs", ".", "crval2", "except", "Exception", "as", "ex", ":", "logging", ".", "debug", "(", "\"Couldn't get CRVAL from WCS: {}\"", ".", "for...
Get the world coordinate of the reference pixel. @rtype: float, float
[ "Get", "the", "world", "coordinate", "of", "the", "reference", "pixel", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L154-L170
train
47,740
OSSOS/MOP
src/ossos/core/ossos/mopheader.py
MOPHeader.pixscale
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 """ 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) except Exception as ex: logging.debug("Failed to compute PIXSCALE using WCS: {}".format(ex)) return float(self['PIXSCAL'])
python
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 """ 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) except Exception as ex: logging.debug("Failed to compute PIXSCALE using WCS: {}".format(ex)) return float(self['PIXSCAL'])
[ "def", "pixscale", "(", "self", ")", ":", "try", ":", "(", "x", ",", "y", ")", "=", "self", "[", "'NAXIS1'", "]", "/", "2.0", ",", "self", "[", "'NAXIS2'", "]", "/", "2.0", "p1", "=", "SkyCoord", "(", "*", "self", ".", "wcs", ".", "xy2sky", "...
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
[ "Return", "the", "pixel", "scale", "of", "the", "detector", "in", "arcseconds", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L173-L189
train
47,741
OSSOS/MOP
src/jjk/preproc/rate.py
get_rates
def get_rates(file,au_min=25,au_max=150): """ Use the rates program to determine the minimum and maximum bounds for planting""" 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.popen(rate_command) line=rate.readline() rate.close() (max_rate, max_ang, max_aw, max_rmin, max_rmax)=string.split(line) rmin=float(min(max_rmin, min_rmin)) rmax=float(max(max_rmax, min_rmax)) aw=float(max(max_aw,min_aw)) angle=(float(max_ang)+float(min_ang))/2.0 rates={'rmin': rmin, 'rmax': rmax, 'angle': angle, 'aw': aw} return rates
python
def get_rates(file,au_min=25,au_max=150): """ Use the rates program to determine the minimum and maximum bounds for planting""" 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.popen(rate_command) line=rate.readline() rate.close() (max_rate, max_ang, max_aw, max_rmin, max_rmax)=string.split(line) rmin=float(min(max_rmin, min_rmin)) rmax=float(max(max_rmax, min_rmax)) aw=float(max(max_aw,min_aw)) angle=(float(max_ang)+float(min_ang))/2.0 rates={'rmin': rmin, 'rmax': rmax, 'angle': angle, 'aw': aw} return rates
[ "def", "get_rates", "(", "file", ",", "au_min", "=", "25", ",", "au_max", "=", "150", ")", ":", "import", "os", ",", "string", "rate_command", "=", "'rate.pl --file %s %d '", "%", "(", "file", ",", "au_min", ")", "rate", "=", "os", ".", "popen", "(", ...
Use the rates program to determine the minimum and maximum bounds for planting
[ "Use", "the", "rates", "program", "to", "determine", "the", "minimum", "and", "maximum", "bounds", "for", "planting" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/rate.py#L7-L27
train
47,742
OSSOS/MOP
src/jjk/preproc/rate.py
kbo_gen
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""" 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('NAXIS2',4096) header['pixscale']=hdulist[0].header.get('PIXSCALE',0.185) header['rmax']=round(float(header['rmax'])/float(header['pixscale']),2) header['rmin']=round(float(header['rmin'])/float(header['pixscale']),2) header['mmin']=mmin header['mmax']=mmax header['expnum']=hdulist[0].header.get('EXPNUM',1000000) header['chipnum']=hdulist[0].header.get('CHIPNUM') import random number = 250 cdata={'x': [], 'y': [], 'mag': [], 'pix_rate': [], 'angle': [], 'id':[]} order=['x','y','mag','pix_rate','angle','arc_rate','id'] for i in range(number): cdata['x'].append( random.uniform(header['xmin'],header['xmax'])) cdata['y'].append( random.uniform(header['ymin'],header['ymax'])) cdata['pix_rate'].append( random.uniform(header['rmin'],header['rmax'])) cdata['angle'].append(random.uniform(header['angle']-header['aw'], header['angle']+header['aw'])) cdata['mag'].append(random.uniform(header['mmin'],header['mmax'])) cdata['id'].append(i) hdu={'data': cdata, 'header': header} return hdu
python
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""" 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('NAXIS2',4096) header['pixscale']=hdulist[0].header.get('PIXSCALE',0.185) header['rmax']=round(float(header['rmax'])/float(header['pixscale']),2) header['rmin']=round(float(header['rmin'])/float(header['pixscale']),2) header['mmin']=mmin header['mmax']=mmax header['expnum']=hdulist[0].header.get('EXPNUM',1000000) header['chipnum']=hdulist[0].header.get('CHIPNUM') import random number = 250 cdata={'x': [], 'y': [], 'mag': [], 'pix_rate': [], 'angle': [], 'id':[]} order=['x','y','mag','pix_rate','angle','arc_rate','id'] for i in range(number): cdata['x'].append( random.uniform(header['xmin'],header['xmax'])) cdata['y'].append( random.uniform(header['ymin'],header['ymax'])) cdata['pix_rate'].append( random.uniform(header['rmin'],header['rmax'])) cdata['angle'].append(random.uniform(header['angle']-header['aw'], header['angle']+header['aw'])) cdata['mag'].append(random.uniform(header['mmin'],header['mmax'])) cdata['id'].append(i) hdu={'data': cdata, 'header': header} return hdu
[ "def", "kbo_gen", "(", "file", ",", "outfile", "=", "'objects.list'", ",", "mmin", "=", "22.5", ",", "mmax", "=", "24.5", ")", ":", "header", "=", "get_rates", "(", "file", ")", "print", "header", "import", "pyfits", "hdulist", "=", "pyfits", ".", "ope...
Generate a file with object moving at a range of rates and angles
[ "Generate", "a", "file", "with", "object", "moving", "at", "a", "range", "of", "rates", "and", "angles" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/rate.py#L29-L64
train
47,743
OSSOS/MOP
src/ossos/utils/get_image_lists.py
main
def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ 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'], help="Passband: default is r.") parser.add_argument("--family", '-f', action="store", default=None, help='List of objects to query.') parser.add_argument("--member", '-m', action="store", default=None, help='Member object of family to query.') args = parser.parse_args() if args.family != None and args.member == None: get_family_info(str(args.family), args.filter) elif args.family == None and args.member != None: get_member_info(str(args.member), args.filter) else: print "Please input either a family or single member name"
python
def main(): """ Input asteroid family, filter type, and image type to query SSOIS """ 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'], help="Passband: default is r.") parser.add_argument("--family", '-f', action="store", default=None, help='List of objects to query.') parser.add_argument("--member", '-m', action="store", default=None, help='Member object of family to query.') args = parser.parse_args() if args.family != None and args.member == None: get_family_info(str(args.family), args.filter) elif args.family == None and args.member != None: get_member_info(str(args.member), args.filter) else: print "Please input either a family or single member name"
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Run SSOIS and return the available images in a particular filter.'", ")", "parser", ".", "add_argument", "(", "\"--filter\"", ",", "action", "=", "\"store\"", ",...
Input asteroid family, filter type, and image type to query SSOIS
[ "Input", "asteroid", "family", "filter", "type", "and", "image", "type", "to", "query", "SSOIS" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L17-L46
train
47,744
OSSOS/MOP
src/ossos/utils/get_image_lists.py
get_family_info
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 """ # 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': object_list = find_family.get_all_families_list() else: object_list = find_family.find_family_members(familyname) for obj in object_list[0:len(object_list) - 1]: # skip header lines get_member_info(obj, filtertype)
python
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 """ # 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': object_list = find_family.get_all_families_list() else: object_list = find_family.find_family_members(familyname) for obj in object_list[0:len(object_list) - 1]: # skip header lines get_member_info(obj, filtertype)
[ "def", "get_family_info", "(", "familyname", ",", "filtertype", "=", "'r'", ",", "imagetype", "=", "'p'", ")", ":", "# establish input", "family_list", "=", "'{}/{}_family.txt'", ".", "format", "(", "_FAMILY_LISTS", ",", "familyname", ")", "if", "os", ".", "pa...
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
[ "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" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L49-L68
train
47,745
OSSOS/MOP
src/ossos/utils/get_image_lists.py
get_member_info
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 """ # 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.MP9301' # Define time period of image search, basically while MegaCam in operation search_start_date = Time('2013-01-01', scale='utc') # epoch1=2013+01+01 search_end_date = Time('2017-01-01', scale='utc') # epoch2=2017+1+1 print("----- Searching for images of object {}".format(object_name)) image_list = [] expnum_list = [] ra_list = [] dec_list = [] query = Query(object_name, search_start_date=search_start_date, search_end_date=search_end_date) result = query.get() print(result) try: objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) except IOError: print("Sleeping 30 seconds") time.sleep(30) objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) print(objects) # Setup output, label columns if len(objects)>0: output = '{}/{}_object_images.txt'.format(_OUTPUT_DIR, object_name) with open(output, 'w') as outfile: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( "Object", "Image", "Exp_time", "RA (deg)", "Dec (deg)", "time", "filter", "RA rate (\"/hr)", "Dec rate (\"/hr)")) for line in objects: with open(output, 'a') as outfile: image_list.append(object_name) expnum_list.append(line['Exptime']) t_start = Time(line['MJD'], format='mjd', scale='utc') - 1.0 * units.minute t_stop = t_start + 2 * units.minute hq = horizons.Query(object_name) hq.start_time = t_start hq.stop_time = t_stop hq.step_size = 1 * units.minute p_ra = hq.table[1]['R.A._(ICRF/J2000.0'] p_dec = hq.table[1]['DEC_(ICRF/J2000.0'] ra_dot = hq.table[1]['dRA*cosD'] dec_dot = hq.table[1]['dDEC/dt'] try: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( object_name, line['Image'], line['Exptime'], p_ra, p_dec, Time(line['MJD'], format='mjd', scale='utc'), line['Filter'], ra_dot, dec_dot)) except Exception as e: print("Error writing to outfile: {}".format(e)) return image_list, expnum_list, ra_list, dec_list
python
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 """ # 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.MP9301' # Define time period of image search, basically while MegaCam in operation search_start_date = Time('2013-01-01', scale='utc') # epoch1=2013+01+01 search_end_date = Time('2017-01-01', scale='utc') # epoch2=2017+1+1 print("----- Searching for images of object {}".format(object_name)) image_list = [] expnum_list = [] ra_list = [] dec_list = [] query = Query(object_name, search_start_date=search_start_date, search_end_date=search_end_date) result = query.get() print(result) try: objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) except IOError: print("Sleeping 30 seconds") time.sleep(30) objects = parse_ssois_return(query.get(), object_name, imagetype, camera_filter=filtertype) print(objects) # Setup output, label columns if len(objects)>0: output = '{}/{}_object_images.txt'.format(_OUTPUT_DIR, object_name) with open(output, 'w') as outfile: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( "Object", "Image", "Exp_time", "RA (deg)", "Dec (deg)", "time", "filter", "RA rate (\"/hr)", "Dec rate (\"/hr)")) for line in objects: with open(output, 'a') as outfile: image_list.append(object_name) expnum_list.append(line['Exptime']) t_start = Time(line['MJD'], format='mjd', scale='utc') - 1.0 * units.minute t_stop = t_start + 2 * units.minute hq = horizons.Query(object_name) hq.start_time = t_start hq.stop_time = t_stop hq.step_size = 1 * units.minute p_ra = hq.table[1]['R.A._(ICRF/J2000.0'] p_dec = hq.table[1]['DEC_(ICRF/J2000.0'] ra_dot = hq.table[1]['dRA*cosD'] dec_dot = hq.table[1]['dDEC/dt'] try: outfile.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( object_name, line['Image'], line['Exptime'], p_ra, p_dec, Time(line['MJD'], format='mjd', scale='utc'), line['Filter'], ra_dot, dec_dot)) except Exception as e: print("Error writing to outfile: {}".format(e)) return image_list, expnum_list, ra_list, dec_list
[ "def", "get_member_info", "(", "object_name", ",", "filtertype", "=", "'r'", ",", "imagetype", "=", "'p'", ")", ":", "# From the given input, identify the desired filter and rename appropriately Replace this?", "if", "filtertype", ".", "lower", "(", ")", ...
Query the ssois table for images of a given object. Then parse through for desired image type, filter, exposure time, and telescope instrument
[ "Query", "the", "ssois", "table", "for", "images", "of", "a", "given", "object", ".", "Then", "parse", "through", "for", "desired", "image", "type", "filter", "exposure", "time", "and", "telescope", "instrument" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L71-L133
train
47,746
OSSOS/MOP
src/ossos/utils/get_image_lists.py
parse_ssois_return
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 """ 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' table = table_reader.read(ssois_return) for row in table: # Excludes the OSSOS wallpaper. # note: 'Telescope_Insturment' is a typo in SSOIS's return format if not 'MegaCam' in row['Telescope_Insturment']: continue # Check if image of object exists in OSSOS observations if not storage.exists(storage.get_uri(row['Image'][:-1])): continue if not str(row['Image_target']).startswith('WP'): good_table += 1 ret_table.append(row) if good_table > 0: print(" %d images found" % good_table) return ret_table
python
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 """ 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' table = table_reader.read(ssois_return) for row in table: # Excludes the OSSOS wallpaper. # note: 'Telescope_Insturment' is a typo in SSOIS's return format if not 'MegaCam' in row['Telescope_Insturment']: continue # Check if image of object exists in OSSOS observations if not storage.exists(storage.get_uri(row['Image'][:-1])): continue if not str(row['Image_target']).startswith('WP'): good_table += 1 ret_table.append(row) if good_table > 0: print(" %d images found" % good_table) return ret_table
[ "def", "parse_ssois_return", "(", "ssois_return", ",", "object_name", ",", "imagetype", ",", "camera_filter", "=", "'r.MP9601'", ",", "telescope_instrument", "=", "'CFHT/MegaCam'", ")", ":", "assert", "camera_filter", "in", "[", "'r.MP9601'", ",", "'u.MP9301'", "]",...
Parse through objects in ssois query and filter out images of desired filter, type, exposure time, and instrument
[ "Parse", "through", "objects", "in", "ssois", "query", "and", "filter", "out", "images", "of", "desired", "filter", "type", "exposure", "time", "and", "instrument" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/get_image_lists.py#L136-L168
train
47,747
OSSOS/MOP
src/ossos/core/ossos/match.py
match_mopfiles
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 """ 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: X_COL = "X_{}".format(mopfile2.header.file_ids[0]) Y_COL = "Y_{}".format(mopfile2.header.file_ids[0]) pos2 = numpy.array([mopfile2.data[X_COL].data, mopfile2.data[Y_COL].data]).transpose() # match_idx is an order list. The list is in the order of the first list of positions and each entry # is the index of the matching position from the second list. match_idx1, match_idx2 = util.match_lists(pos1, pos2) mopfile1.data.add_column(Column(data=match_idx1.filled(-1), name="real", length=len(mopfile1.data))) idx = 0 for file_id in mopfile1.header.file_ids: idx += 1 mopfile1.data.add_column(Column(data=[file_id]*len(mopfile1.data), name="ID_{}".format(idx))) return mopfile1
python
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 """ 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: X_COL = "X_{}".format(mopfile2.header.file_ids[0]) Y_COL = "Y_{}".format(mopfile2.header.file_ids[0]) pos2 = numpy.array([mopfile2.data[X_COL].data, mopfile2.data[Y_COL].data]).transpose() # match_idx is an order list. The list is in the order of the first list of positions and each entry # is the index of the matching position from the second list. match_idx1, match_idx2 = util.match_lists(pos1, pos2) mopfile1.data.add_column(Column(data=match_idx1.filled(-1), name="real", length=len(mopfile1.data))) idx = 0 for file_id in mopfile1.header.file_ids: idx += 1 mopfile1.data.add_column(Column(data=[file_id]*len(mopfile1.data), name="ID_{}".format(idx))) return mopfile1
[ "def", "match_mopfiles", "(", "mopfile1", ",", "mopfile2", ")", ":", "pos1", "=", "pos2", "=", "numpy", ".", "array", "(", "[", "]", ")", "if", "len", "(", "mopfile1", ".", "data", ")", ">", "0", ":", "X_COL", "=", "\"X_{}\"", ".", "format", "(", ...
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
[ "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", ...
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/match.py#L18-L45
train
47,748
OSSOS/MOP
src/ossos/core/ossos/match.py
measure_mags
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 """ 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': [], 'source': image_downloader.download(reading, needs_apcor=True)} assert isinstance(reading.obs, Observation) observations[reading.obs]['x'].append(reading.x) observations[reading.obs]['y'].append(reading.y) for observation in observations: source = observations[observation]['source'] assert isinstance(source, SourceCutout) source.update_pixel_location(observations[observation]['x'], observations[observation]['y']) hdulist_index = source.get_hdulist_idx(observation.ccdnum) observations[observation]['mags'] = daophot.phot(source._hdu_on_disk(hdulist_index), observations[observation]['x'], observations[observation]['y'], aperture=source.apcor.aperture, sky=source.apcor.sky, swidth=source.apcor.swidth, apcor=source.apcor.apcor, zmag=source.zmag, maxcount=30000, extno=0) return observations
python
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 """ 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': [], 'source': image_downloader.download(reading, needs_apcor=True)} assert isinstance(reading.obs, Observation) observations[reading.obs]['x'].append(reading.x) observations[reading.obs]['y'].append(reading.y) for observation in observations: source = observations[observation]['source'] assert isinstance(source, SourceCutout) source.update_pixel_location(observations[observation]['x'], observations[observation]['y']) hdulist_index = source.get_hdulist_idx(observation.ccdnum) observations[observation]['mags'] = daophot.phot(source._hdu_on_disk(hdulist_index), observations[observation]['x'], observations[observation]['y'], aperture=source.apcor.aperture, sky=source.apcor.sky, swidth=source.apcor.swidth, apcor=source.apcor.apcor, zmag=source.zmag, maxcount=30000, extno=0) return observations
[ "def", "measure_mags", "(", "measures", ")", ":", "import", "daophot", "image_downloader", "=", "ImageDownloader", "(", ")", "observations", "=", "{", "}", "for", "measure", "in", "measures", ":", "for", "reading", "in", "measure", ":", "if", "reading", ".",...
Given a list of readings compute the magnitudes for all sources in each reading. @param measures: list of readings @return: None
[ "Given", "a", "list", "of", "readings", "compute", "the", "magnitudes", "for", "all", "sources", "in", "each", "reading", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/match.py#L48-L87
train
47,749
OSSOS/MOP
src/ossos/core/ossos/gui/models/collections.py
StatefulCollection.append
def append(self, item): """Adds a new item to the end of the collection.""" if len(self) == 0: # Special case, we make this the current item self.index = 0 self.items.append(item)
python
def append(self, item): """Adds a new item to the end of the collection.""" if len(self) == 0: # Special case, we make this the current item self.index = 0 self.items.append(item)
[ "def", "append", "(", "self", ",", "item", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "# Special case, we make this the current item", "self", ".", "index", "=", "0", "self", ".", "items", ".", "append", "(", "item", ")" ]
Adds a new item to the end of the collection.
[ "Adds", "a", "new", "item", "to", "the", "end", "of", "the", "collection", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/collections.py#L27-L33
train
47,750
OSSOS/MOP
src/ossos/utils/vtag_cleanup.py
fix_tags_on_cands_missing_reals
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." 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.startswith('fk'): user = storage.get_property(con.get_full_path(filename), property) if (user is not None): # and (user == user_id): # modify 'and' to generalise to all users with work in this directory #realsfile = filename.replace('cands', 'reals') #if not con.exists(realsfile): # print filename, 'no reals file', realsfile # go through the listing of .mpc files and see if any match this reals.astrom is_present = False for mpcfile in [f for f in mpc_listing if not f.startswith('fk')]: if mpcfile.startswith(filename): print filename, user, 'exists!', mpcfile is_present = True if not is_present: user_progress.append(filename) print filename, user, 'no mpc file' storage.set_property(con.get_full_path(filename), property, None) print 'Fixed files:', len(user_progress) return
python
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." 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.startswith('fk'): user = storage.get_property(con.get_full_path(filename), property) if (user is not None): # and (user == user_id): # modify 'and' to generalise to all users with work in this directory #realsfile = filename.replace('cands', 'reals') #if not con.exists(realsfile): # print filename, 'no reals file', realsfile # go through the listing of .mpc files and see if any match this reals.astrom is_present = False for mpcfile in [f for f in mpc_listing if not f.startswith('fk')]: if mpcfile.startswith(filename): print filename, user, 'exists!', mpcfile is_present = True if not is_present: user_progress.append(filename) print filename, user, 'no mpc file' storage.set_property(con.get_full_path(filename), property, None) print 'Fixed files:', len(user_progress) return
[ "def", "fix_tags_on_cands_missing_reals", "(", "user_id", ",", "vos_dir", ",", "property", ")", ":", "con", "=", "context", ".", "get_context", "(", "vos_dir", ")", "user_progress", "=", "[", "]", "listing", "=", "con", ".", "get_listing", "(", "tasks", ".",...
At the moment this just checks for a single user's missing reals. Easy to generalise it to all users.
[ "At", "the", "moment", "this", "just", "checks", "for", "a", "single", "user", "s", "missing", "reals", ".", "Easy", "to", "generalise", "it", "to", "all", "users", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/utils/vtag_cleanup.py#L64-L93
train
47,751
playpauseandstop/rororo
rororo/schemas/schema.py
Schema.make_error
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://stackoverflow.com/q/42942867 error_class: Any = None) -> Exception: """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. """ if error_class is None: error_class = self.error_class if self.error_class else Error return error_class(message)
python
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://stackoverflow.com/q/42942867 error_class: Any = None) -> Exception: """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. """ 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://stackov...
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.
[ "Return", "error", "instantiated", "from", "given", "message", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L74-L92
train
47,752
playpauseandstop/rororo
rororo/schemas/schema.py
Schema.make_response
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. """ 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: logger.error('Response data omit, but no response factory is used') raise self.make_error('Response data could be omitted only when ' 'response factory is used') response_schema = getattr(self.module, 'response', None) if response_schema is not None: self._validate(data, response_schema) if self.response_factory is not None: return self.response_factory( *([data] if data is not None else []), **kwargs) return data
python
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. """ 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: logger.error('Response data omit, but no response factory is used') raise self.make_error('Response data could be omitted only when ' 'response factory is used') response_schema = getattr(self.module, 'response', None) if response_schema is not None: self._validate(data, response_schema) if self.response_factory is not None: return self.response_factory( *([data] if data is not None else []), **kwargs) return data
[ "def", "make_response", "(", "self", ",", "data", ":", "Any", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Any", ":", "if", "not", "self", ".", "_valid_request", ":", "logger", ".", "error", "(", "'Request not validated, cannot make respon...
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.
[ "r", "Validate", "response", "data", "and", "wrap", "it", "inside", "response", "factory", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L94-L120
train
47,753
playpauseandstop/rororo
rororo/schemas/schema.py
Schema.validate_request
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 merged **dict** with all data, but you can customize things to use read-only dict or any other additional class or callable. """ 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)}) raise self.make_error('Request schema should be defined') # Merge base and additional data dicts, but only if additional data # dicts have been supplied if isinstance(data, dict) and additional: data = merged_class(self._merge_data(data, *additional)) try: self._validate(data, request_schema) finally: self._valid_request = False self._valid_request = True processor = getattr(self.module, 'request_processor', None) return processor(data) if processor else data
python
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 merged **dict** with all data, but you can customize things to use read-only dict or any other additional class or callable. """ 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)}) raise self.make_error('Request schema should be defined') # Merge base and additional data dicts, but only if additional data # dicts have been supplied if isinstance(data, dict) and additional: data = merged_class(self._merge_data(data, *additional)) try: self._validate(data, request_schema) finally: self._valid_request = False self._valid_request = True processor = getattr(self.module, 'request_processor', None) return processor(data) if processor else data
[ "def", "validate_request", "(", "self", ",", "data", ":", "Any", ",", "*", "additional", ":", "AnyMapping", ",", "merged_class", ":", "Type", "[", "dict", "]", "=", "dict", ")", "->", "Any", ":", "request_schema", "=", "getattr", "(", "self", ".", "mod...
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 merged **dict** with all data, but you can customize things to use read-only dict or any other additional class or callable.
[ "r", "Validate", "request", "data", "against", "request", "schema", "from", "module", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L122-L157
train
47,754
playpauseandstop/rororo
rororo/schemas/schema.py
Schema._merge_data
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. """ return defaults( dict(data) if not isinstance(data, dict) else data, *(dict(item) for item in additional))
python
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. """ 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", ":", "return", "defaults", "(", "dict", "(", "data", ")", "if", "not", "isinstance", "(", "data", ",", "dict", ")", "else",...
r"""Merge base data and additional dicts. :param data: Base data. :param \*additional: Additional data dicts to be merged into base dict.
[ "r", "Merge", "base", "data", "and", "additional", "dicts", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L159-L167
train
47,755
playpauseandstop/rororo
rororo/schemas/schema.py
Schema._pure_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. """ if not isinstance(data, dict) and not isinstance(data, list): try: return dict(data) except TypeError: ... return data
python
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. """ 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", "not", "isinstance", "(", "data", ",", "dict", ")", "and", "not", "isinstance", "(", "data", ",", "list", ")", ":", "try", ":", "return", "dict", "(", "data", ...
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.
[ "If", "data", "is", "dict", "-", "like", "object", "convert", "it", "to", "pure", "dict", "instance", "so", "it", "will", "be", "possible", "to", "pass", "to", "default", "jsonschema", ".", "validate", "func", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L169-L181
train
47,756
playpauseandstop/rororo
rororo/schemas/schema.py
Schema._validate
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. """ 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}) if self.error_class is None: raise raise self.make_error('Validation Error', error=err) from err
python
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. """ 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}) if self.error_class is None: raise raise self.make_error('Validation Error', error=err) from err
[ "def", "_validate", "(", "self", ",", "data", ":", "Any", ",", "schema", ":", "AnyMapping", ")", "->", "Any", ":", "try", ":", "return", "self", ".", "validate_func", "(", "schema", ",", "self", ".", "_pure_data", "(", "data", ")", ")", "except", "se...
Validate data against given schema. :param data: Data to validate. :param schema: Schema to use for validation.
[ "Validate", "data", "against", "given", "schema", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/schema.py#L183-L198
train
47,757
OSSOS/MOP
src/ossos/canfar/cadc_certificates.py
getCert
def getCert(certHost=vos.vos.SERVER, certfile=None, certQuery="/cred/proxyCert?daysValid=",daysValid=2): """Access the cadc certificate server""" 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: sys.stderr.write(str(e)+": %s \n" % dirname) sys.stderr.write("Expected %s to be a directory.\n" % ( dirname)) sys.exit(e.errno) else: raise e # Example taken from voidspace.org.uk # create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() (username, passwd) = getUserPassword(host=certHost) # Add the username and password. # If we knew the realm, we could use it instead of ``None``. top_level_url = "http://"+certHost password_mgr.add_password(None, top_level_url, username, passwd) handler = urllib2.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # Now all calls to urllib2.urlopen use our opener. url="http://"+certHost+certQuery+str(daysValid) r= urllib2.urlopen(url) w= file(certfile,'w') while True: buf=r.read() if not buf: break w.write(buf) w.close() r.close() return
python
def getCert(certHost=vos.vos.SERVER, certfile=None, certQuery="/cred/proxyCert?daysValid=",daysValid=2): """Access the cadc certificate server""" 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: sys.stderr.write(str(e)+": %s \n" % dirname) sys.stderr.write("Expected %s to be a directory.\n" % ( dirname)) sys.exit(e.errno) else: raise e # Example taken from voidspace.org.uk # create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() (username, passwd) = getUserPassword(host=certHost) # Add the username and password. # If we knew the realm, we could use it instead of ``None``. top_level_url = "http://"+certHost password_mgr.add_password(None, top_level_url, username, passwd) handler = urllib2.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # Now all calls to urllib2.urlopen use our opener. url="http://"+certHost+certQuery+str(daysValid) r= urllib2.urlopen(url) w= file(certfile,'w') while True: buf=r.read() if not buf: break w.write(buf) w.close() r.close() return
[ "def", "getCert", "(", "certHost", "=", "vos", ".", "vos", ".", "SERVER", ",", "certfile", "=", "None", ",", "certQuery", "=", "\"/cred/proxyCert?daysValid=\"", ",", "daysValid", "=", "2", ")", ":", "if", "certfile", "is", "None", ":", "certfile", "=", "...
Access the cadc certificate server
[ "Access", "the", "cadc", "certificate", "server" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/canfar/cadc_certificates.py#L10-L60
train
47,758
playpauseandstop/rororo
rororo/utils.py
to_bool
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 as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value. """ return bool(strtobool(value) if isinstance(value, str) else value)
python
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 as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value. """ return bool(strtobool(value) if isinstance(value, str) else value)
[ "def", "to_bool", "(", "value", ":", "Any", ")", "->", "bool", ":", "return", "bool", "(", "strtobool", "(", "value", ")", "if", "isinstance", "(", "value", ",", "str", ")", "else", "value", ")" ]
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 as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value.
[ "Convert", "string", "or", "other", "Python", "object", "to", "boolean", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L17-L32
train
47,759
playpauseandstop/rororo
rororo/utils.py
to_int
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. """ try: return int(value) except (TypeError, ValueError): return default
python
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. """ try: return int(value) except (TypeError, ValueError): return default
[ "def", "to_int", "(", "value", ":", "str", ",", "default", ":", "T", "=", "None", ")", "->", "Union", "[", "int", ",", "Optional", "[", "T", "]", "]", ":", "try", ":", "return", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueErr...
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.
[ "Convert", "given", "value", "to", "int", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L35-L46
train
47,760
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
mk_dict
def mk_dict(results,description): """Given a result list and descrition sequence, return a list of dictionaries""" 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
python
def mk_dict(results,description): """Given a result list and descrition sequence, return a list of dictionaries""" 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", ")", ":", "rows", "=", "[", "]", "for", "row", "in", "results", ":", "row_dict", "=", "{", "}", "for", "idx", "in", "range", "(", "len", "(", "row", ")", ")", ":", "col", "=", "description", "...
Given a result list and descrition sequence, return a list of dictionaries
[ "Given", "a", "result", "list", "and", "descrition", "sequence", "return", "a", "list", "of", "dictionaries" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L16-L27
train
47,761
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
get_orbits
def get_orbits(official='%'): """Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned """ sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(),cfeps.description)
python
def get_orbits(official='%'): """Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned """ sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(),cfeps.description)
[ "def", "get_orbits", "(", "official", "=", "'%'", ")", ":", "sql", "=", "\"SELECT * FROM orbits WHERE official LIKE '%s' \"", "%", "(", "official", ",", ")", "cfeps", ".", "execute", "(", "sql", ")", "return", "mk_dict", "(", "cfeps", ".", "fetchall", "(", "...
Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned
[ "Query", "the", "orbit", "table", "for", "the", "object", "whose", "official", "desingation", "matches", "parameter", "official", ".", "By", "default", "all", "entries", "are", "returned" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L30-L37
train
47,762
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
get_astrom
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""" 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.execute(sql) return mk_dict(cfeps.fetchall(), cfeps.description)
python
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""" 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.execute(sql) return mk_dict(cfeps.fetchall(), cfeps.description)
[ "def", "get_astrom", "(", "official", "=", "'%'", ",", "provisional", "=", "'%'", ")", ":", "sql", "=", "\"SELECT m.* FROM measure m \"", "sql", "+=", "\"LEFT JOIN object o ON m.provisional LIKE o.provisional \"", "if", "not", "official", ":", "sql", "+=", "\"WHERE o...
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
[ "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" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L40-L54
train
47,763
OSSOS/MOP
src/jjk/preproc/cfeps_object.py
getData
def getData(file_id,ra,dec): """Create a link that connects to a getData URL""" 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 NOT WORKING YET.... URL=BASE+"?dataset_name="+file_id+"&cutout=circle("+str(ra*57.3)+"," URL+=str(dec*57.3)+","+str(5.0/60.0)+")" return URL
python
def getData(file_id,ra,dec): """Create a link that connects to a getData URL""" 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 NOT WORKING YET.... URL=BASE+"?dataset_name="+file_id+"&cutout=circle("+str(ra*57.3)+"," URL+=str(dec*57.3)+","+str(5.0/60.0)+")" return URL
[ "def", "getData", "(", "file_id", ",", "ra", ",", "dec", ")", ":", "DATA", "=", "\"www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca\"", "BASE", "=", "\"http://\"", "+", "DATA", "+", "\"/authProxy/getData\"", "archive", "=", "\"CFHT\"", "wcs", "=", "\"corrected\"", "import", ...
Create a link that connects to a getData URL
[ "Create", "a", "link", "that", "connects", "to", "a", "getData", "URL" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/cfeps_object.py#L57-L75
train
47,764
etesync/pyetesync
example_crud.py
EtesyncCRUD.delete_event
def delete_event(self, uid): """Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted """ ev_for_deletion = self.calendar.get(uid) ev_for_deletion.delete()
python
def delete_event(self, uid): """Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted """ ev_for_deletion = self.calendar.get(uid) ev_for_deletion.delete()
[ "def", "delete_event", "(", "self", ",", "uid", ")", ":", "ev_for_deletion", "=", "self", ".", "calendar", ".", "get", "(", "uid", ")", "ev_for_deletion", ".", "delete", "(", ")" ]
Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted
[ "Delete", "event", "and", "sync", "calendar" ]
6b185925b1489912c971e99d6a115583021873bd
https://github.com/etesync/pyetesync/blob/6b185925b1489912c971e99d6a115583021873bd/example_crud.py#L100-L108
train
47,765
JohnVinyard/zounds
zounds/util/persistence.py
simple_lmdb_settings
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 """ 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('|') database = ff.LmdbDatabase( path, key_builder=key_builder, map_size=map_size) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model return decorator
python
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 """ 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('|') database = ff.LmdbDatabase( path, key_builder=key_builder, map_size=map_size) class Model(cls, Settings): pass Model.__name__ = cls.__name__ Model.__module__ = cls.__module__ return Model return decorator
[ "def", "simple_lmdb_settings", "(", "path", ",", "map_size", "=", "1e9", ",", "user_supplied_id", "=", "False", ")", ":", "def", "decorator", "(", "cls", ")", ":", "provider", "=", "ff", ".", "UserSpecifiedIdProvider", "(", "key", "=", "'_id'", ")", "if", ...
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
[ "Creates", "a", "decorator", "that", "can", "be", "used", "to", "configure", "sane", "default", "LMDB", "persistence", "settings", "for", "a", "model" ]
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/util/persistence.py#L4-L32
train
47,766
OSSOS/MOP
src/ossos/core/ossos/cameras.py
Camera.offset
def offset(self, index=0): """Offset the camera pointing to be centred on a particular CCD.""" 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)
python
def offset(self, index=0): """Offset the camera pointing to be centred on a particular CCD.""" 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", ")", ":", "eta", "=", "self", ".", "_geometry", "[", "self", ".", "camera", "]", "[", "index", "]", "[", "\"ra\"", "]", "xi", "=", "self", ".", "_geometry", "[", "self", ".", "camera", "]", ...
Offset the camera pointing to be centred on a particular CCD.
[ "Offset", "the", "camera", "pointing", "to", "be", "centred", "on", "a", "particular", "CCD", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cameras.py#L213-L219
train
47,767
OSSOS/MOP
src/ossos/core/ossos/cameras.py
Camera.coord
def coord(self): """The center of the camera pointing in sky coordinates""" if self._coordinate is None: self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec) return self._coordinate
python
def coord(self): """The center of the camera pointing in sky coordinates""" if self._coordinate is None: self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec) return self._coordinate
[ "def", "coord", "(", "self", ")", ":", "if", "self", ".", "_coordinate", "is", "None", ":", "self", ".", "_coordinate", "=", "SkyCoord", "(", "self", ".", "origin", ".", "ra", ",", "self", ".", "origin", ".", "dec", "+", "45", "*", "units", ".", ...
The center of the camera pointing in sky coordinates
[ "The", "center", "of", "the", "camera", "pointing", "in", "sky", "coordinates" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/cameras.py#L226-L230
train
47,768
OSSOS/MOP
src/ossos/core/ossos/gui/progress.py
requires_lock
def requires_lock(function): """ Decorator to check if the user owns the required lock. The first argument must be the filename. """ 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
python
def requires_lock(function): """ Decorator to check if the user owns the required lock. The first argument must be the filename. """ 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", ")", ":", "def", "new_lock_requiring_function", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "owns_lock", "(", "filename", ")", ":", "return", "function", "...
Decorator to check if the user owns the required lock. The first argument must be the filename.
[ "Decorator", "to", "check", "if", "the", "user", "owns", "the", "required", "lock", ".", "The", "first", "argument", "must", "be", "the", "filename", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/progress.py#L29-L41
train
47,769
OSSOS/MOP
src/ossos/core/ossos/gui/progress.py
LocalProgressManager.clean
def clean(self, suffixes=None): """ Remove all persistence-related files from the directory. """ 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)
python
def clean(self, suffixes=None): """ Remove all persistence-related files from the directory. """ 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", ")", ":", "if", "suffixes", "is", "None", ":", "suffixes", "=", "[", "DONE_SUFFIX", ",", "LOCK_SUFFIX", ",", "PART_SUFFIX", "]", "for", "suffix", "in", "suffixes", ":", "listing", "=", "self", ...
Remove all persistence-related files from the directory.
[ "Remove", "all", "persistence", "-", "related", "files", "from", "the", "directory", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/progress.py#L359-L369
train
47,770
OSSOS/MOP
src/ossos/core/ossos/figures.py
setFigForm
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ fig_width_pt = 245.26*2 inches_per_pt = 1.0/72.27 golden_mean = (math.sqrt(5.)-1.0)/2.0 fig_width = fig_width_pt*inches_per_pt fig_height = fig_width*golden_mean fig_size = [1.5*fig_width, fig_height] params = {'backend': 'ps', 'axes.labelsize': 12, 'text.fontsize': 12, 'legend.fontsize': 7, 'xtick.labelsize': 11, 'ytick.labelsize': 11, 'text.usetex': True, 'font.family': 'serif', 'font.serif': 'Times', 'image.aspect': 'auto', 'figure.subplot.left': 0.1, 'figure.subplot.bottom': 0.1, 'figure.subplot.hspace': 0.25, 'figure.figsize': fig_size} rcParams.update(params)
python
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ fig_width_pt = 245.26*2 inches_per_pt = 1.0/72.27 golden_mean = (math.sqrt(5.)-1.0)/2.0 fig_width = fig_width_pt*inches_per_pt fig_height = fig_width*golden_mean fig_size = [1.5*fig_width, fig_height] params = {'backend': 'ps', 'axes.labelsize': 12, 'text.fontsize': 12, 'legend.fontsize': 7, 'xtick.labelsize': 11, 'ytick.labelsize': 11, 'text.usetex': True, 'font.family': 'serif', 'font.serif': 'Times', 'image.aspect': 'auto', 'figure.subplot.left': 0.1, 'figure.subplot.bottom': 0.1, 'figure.subplot.hspace': 0.25, 'figure.figsize': fig_size} rcParams.update(params)
[ "def", "setFigForm", "(", ")", ":", "fig_width_pt", "=", "245.26", "*", "2", "inches_per_pt", "=", "1.0", "/", "72.27", "golden_mean", "=", "(", "math", ".", "sqrt", "(", "5.", ")", "-", "1.0", ")", "/", "2.0", "fig_width", "=", "fig_width_pt", "*", ...
set the rcparams to EmulateApJ columnwidth=245.26 pts
[ "set", "the", "rcparams", "to", "EmulateApJ", "columnwidth", "=", "245", ".", "26", "pts" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/figures.py#L5-L30
train
47,771
OSSOS/MOP
src/ossos/web/web/auth/gms.py
getCert
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): """Access the cadc certificate server.""" if certfile is None: certfile = tempfile.NamedTemporaryFile() # Add the username and password. # If we knew the realm, we could use it instead of ``None``. password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() top_level_url = "http://" + certHost logging.debug(top_level_url) password_mgr.add_password(None, top_level_url, username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) logging.debug(str(handler)) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # buuld the url that with 'GET' a certificat using user_id/password info url = "http://" + certHost + certQuery logging.debug(url) r = None try: r = opener.open(url) except urllib2.HTTPError as e: logging.debug(url) logging.debug(str(e)) return False logging.debug(str(r)) if r is not None: while True: buf = r.read() logging.debug(buf) if not buf: break certfile.write(buf) r.close() return certfile
python
def getCert(username, password, certHost=_SERVER, certfile=None, certQuery=_PROXY): """Access the cadc certificate server.""" if certfile is None: certfile = tempfile.NamedTemporaryFile() # Add the username and password. # If we knew the realm, we could use it instead of ``None``. password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() top_level_url = "http://" + certHost logging.debug(top_level_url) password_mgr.add_password(None, top_level_url, username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) logging.debug(str(handler)) # create "opener" (OpenerDirector instance) opener = urllib2.build_opener(handler) # Install the opener. urllib2.install_opener(opener) # buuld the url that with 'GET' a certificat using user_id/password info url = "http://" + certHost + certQuery logging.debug(url) r = None try: r = opener.open(url) except urllib2.HTTPError as e: logging.debug(url) logging.debug(str(e)) return False logging.debug(str(r)) if r is not None: while True: buf = r.read() logging.debug(buf) if not buf: break certfile.write(buf) r.close() return certfile
[ "def", "getCert", "(", "username", ",", "password", ",", "certHost", "=", "_SERVER", ",", "certfile", "=", "None", ",", "certQuery", "=", "_PROXY", ")", ":", "if", "certfile", "is", "None", ":", "certfile", "=", "tempfile", ".", "NamedTemporaryFile", "(", ...
Access the cadc certificate server.
[ "Access", "the", "cadc", "certificate", "server", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L51-L97
train
47,772
OSSOS/MOP
src/ossos/web/web/auth/gms.py
getGroupsURL
def getGroupsURL(certfile, group): """given a certfile load a list of groups that user is a member of""" GMS = "https://" + _SERVER + _GMS certfile.seek(0) buf = certfile.read() x509 = crypto.load_certificate(crypto.FILETYPE_PEM, buf) sep = "" dn = "" parts = [] for i in x509.get_issuer().get_components(): #print i if i[0] in parts: continue parts.append(i[0]) dn = i[0] + "=" + i[1] + sep + dn sep = "," return GMS + "/" + group + "/" + urllib.quote(dn)
python
def getGroupsURL(certfile, group): """given a certfile load a list of groups that user is a member of""" GMS = "https://" + _SERVER + _GMS certfile.seek(0) buf = certfile.read() x509 = crypto.load_certificate(crypto.FILETYPE_PEM, buf) sep = "" dn = "" parts = [] for i in x509.get_issuer().get_components(): #print i if i[0] in parts: continue parts.append(i[0]) dn = i[0] + "=" + i[1] + sep + dn sep = "," return GMS + "/" + group + "/" + urllib.quote(dn)
[ "def", "getGroupsURL", "(", "certfile", ",", "group", ")", ":", "GMS", "=", "\"https://\"", "+", "_SERVER", "+", "_GMS", "certfile", ".", "seek", "(", "0", ")", "buf", "=", "certfile", ".", "read", "(", ")", "x509", "=", "crypto", ".", "load_certificat...
given a certfile load a list of groups that user is a member of
[ "given", "a", "certfile", "load", "a", "list", "of", "groups", "that", "user", "is", "a", "member", "of" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L100-L120
train
47,773
OSSOS/MOP
src/ossos/web/web/auth/gms.py
stub
def stub(): """Just some left over code""" form = cgi.FieldStorage() userid = form['userid'].value password = form['passwd'].value group = form['group'].value
python
def stub(): """Just some left over code""" form = cgi.FieldStorage() userid = form['userid'].value password = form['passwd'].value group = form['group'].value
[ "def", "stub", "(", ")", ":", "form", "=", "cgi", ".", "FieldStorage", "(", ")", "userid", "=", "form", "[", "'userid'", "]", ".", "value", "password", "=", "form", "[", "'passwd'", "]", ".", "value", "group", "=", "form", "[", "'group'", "]", ".",...
Just some left over code
[ "Just", "some", "left", "over", "code" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/gms.py#L156-L161
train
47,774
OSSOS/MOP
src/ossos/core/ossos/wcs.py
parse_pv
def parse_pv(header): """ Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N depends on the order of the fit. For example, an order 3 fit goes up to PV?_10. """ order_fit = parse_order_fit(header) def parse_with_base(i): key_base = "PV%d_" % i pvi_x = [header[key_base + "0"]] def parse_range(lower, upper): for j in range(lower, upper + 1): pvi_x.append(header[key_base + str(j)]) if order_fit >= 1: parse_range(1, 3) if order_fit >= 2: parse_range(4, 6) if order_fit >= 3: parse_range(7, 10) return pvi_x return [parse_with_base(1), parse_with_base(2)]
python
def parse_pv(header): """ Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N depends on the order of the fit. For example, an order 3 fit goes up to PV?_10. """ order_fit = parse_order_fit(header) def parse_with_base(i): key_base = "PV%d_" % i pvi_x = [header[key_base + "0"]] def parse_range(lower, upper): for j in range(lower, upper + 1): pvi_x.append(header[key_base + str(j)]) if order_fit >= 1: parse_range(1, 3) if order_fit >= 2: parse_range(4, 6) if order_fit >= 3: parse_range(7, 10) return pvi_x return [parse_with_base(1), parse_with_base(2)]
[ "def", "parse_pv", "(", "header", ")", ":", "order_fit", "=", "parse_order_fit", "(", "header", ")", "def", "parse_with_base", "(", "i", ")", ":", "key_base", "=", "\"PV%d_\"", "%", "i", "pvi_x", "=", "[", "header", "[", "key_base", "+", "\"0\"", "]", ...
Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N depends on the order of the fit. For example, an order 3 fit goes up to PV?_10.
[ "Parses", "the", "PV", "array", "from", "an", "astropy", "FITS", "header", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/wcs.py#L389-L425
train
47,775
JohnVinyard/zounds
zounds/nputil/npx.py
safe_unit_norm
def safe_unit_norm(a): """ Ensure that the vector or vectors have unit norm """ if 1 == len(a.shape): n = np.linalg.norm(a) if n: return a / n return a norm = np.sum(np.abs(a) ** 2, axis=-1) ** (1. / 2) # Dividing by a norm of zero will cause a warning to be issued. Set those # values to another number. It doesn't matter what, since we'll be dividing # a vector of zeros by the number, and 0 / N always equals 0. norm[norm == 0] = -1e12 return a / norm[:, np.newaxis]
python
def safe_unit_norm(a): """ Ensure that the vector or vectors have unit norm """ if 1 == len(a.shape): n = np.linalg.norm(a) if n: return a / n return a norm = np.sum(np.abs(a) ** 2, axis=-1) ** (1. / 2) # Dividing by a norm of zero will cause a warning to be issued. Set those # values to another number. It doesn't matter what, since we'll be dividing # a vector of zeros by the number, and 0 / N always equals 0. norm[norm == 0] = -1e12 return a / norm[:, np.newaxis]
[ "def", "safe_unit_norm", "(", "a", ")", ":", "if", "1", "==", "len", "(", "a", ".", "shape", ")", ":", "n", "=", "np", ".", "linalg", ".", "norm", "(", "a", ")", "if", "n", ":", "return", "a", "/", "n", "return", "a", "norm", "=", "np", "."...
Ensure that the vector or vectors have unit norm
[ "Ensure", "that", "the", "vector", "or", "vectors", "have", "unit", "norm" ]
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L47-L63
train
47,776
JohnVinyard/zounds
zounds/nputil/npx.py
pad
def pad(a, desiredlength): """ Pad an n-dimensional numpy array with zeros along the zero-th dimension so that it is the desired length. Return it unchanged if it is greater than or equal to the desired length """ if len(a) >= desiredlength: return a islist = isinstance(a, list) a = np.array(a) diff = desiredlength - len(a) shape = list(a.shape) shape[0] = diff padded = np.concatenate([a, np.zeros(shape, dtype=a.dtype)]) return padded.tolist() if islist else padded
python
def pad(a, desiredlength): """ Pad an n-dimensional numpy array with zeros along the zero-th dimension so that it is the desired length. Return it unchanged if it is greater than or equal to the desired length """ if len(a) >= desiredlength: return a islist = isinstance(a, list) a = np.array(a) diff = desiredlength - len(a) shape = list(a.shape) shape[0] = diff padded = np.concatenate([a, np.zeros(shape, dtype=a.dtype)]) return padded.tolist() if islist else padded
[ "def", "pad", "(", "a", ",", "desiredlength", ")", ":", "if", "len", "(", "a", ")", ">=", "desiredlength", ":", "return", "a", "islist", "=", "isinstance", "(", "a", ",", "list", ")", "a", "=", "np", ".", "array", "(", "a", ")", "diff", "=", "d...
Pad an n-dimensional numpy array with zeros along the zero-th dimension so that it is the desired length. Return it unchanged if it is greater than or equal to the desired length
[ "Pad", "an", "n", "-", "dimensional", "numpy", "array", "with", "zeros", "along", "the", "zero", "-", "th", "dimension", "so", "that", "it", "is", "the", "desired", "length", ".", "Return", "it", "unchanged", "if", "it", "is", "greater", "than", "or", ...
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L66-L83
train
47,777
JohnVinyard/zounds
zounds/nputil/npx.py
Growable.append
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._position += 1 return self
python
def append(self, item): """ append a single item to the array, growing the wrapped numpy array if necessary """ try: self._data[self._position] = item except IndexError: self._grow() self._data[self._position] = item self._position += 1 return self
[ "def", "append", "(", "self", ",", "item", ")", ":", "try", ":", "self", ".", "_data", "[", "self", ".", "_position", "]", "=", "item", "except", "IndexError", ":", "self", ".", "_grow", "(", ")", "self", ".", "_data", "[", "self", ".", "_position"...
append a single item to the array, growing the wrapped numpy array if necessary
[ "append", "a", "single", "item", "to", "the", "array", "growing", "the", "wrapped", "numpy", "array", "if", "necessary" ]
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L332-L343
train
47,778
JohnVinyard/zounds
zounds/nputil/npx.py
Growable.extend
def extend(self, items): """ extend the numpy array with multiple items, growing the wrapped array if necessary """ items = np.array(items) pos = items.shape[0] + self.logical_size if pos > self.physical_size: # more physical memory is needed than has been allocated so far amt = self._tmp_size() if self.physical_size + amt < pos: # growing the memory by the prescribed amount still won't # make enough room. Allocate exactly as much memory as is needed # to accommodate items amt = pos - self.physical_size # actually grow the array self._grow(amt=amt) stop = self._position + items.shape[0] self._data[self._position: stop] = items self._position += items.shape[0] return self
python
def extend(self, items): """ extend the numpy array with multiple items, growing the wrapped array if necessary """ items = np.array(items) pos = items.shape[0] + self.logical_size if pos > self.physical_size: # more physical memory is needed than has been allocated so far amt = self._tmp_size() if self.physical_size + amt < pos: # growing the memory by the prescribed amount still won't # make enough room. Allocate exactly as much memory as is needed # to accommodate items amt = pos - self.physical_size # actually grow the array self._grow(amt=amt) stop = self._position + items.shape[0] self._data[self._position: stop] = items self._position += items.shape[0] return self
[ "def", "extend", "(", "self", ",", "items", ")", ":", "items", "=", "np", ".", "array", "(", "items", ")", "pos", "=", "items", ".", "shape", "[", "0", "]", "+", "self", ".", "logical_size", "if", "pos", ">", "self", ".", "physical_size", ":", "#...
extend the numpy array with multiple items, growing the wrapped array if necessary
[ "extend", "the", "numpy", "array", "with", "multiple", "items", "growing", "the", "wrapped", "array", "if", "necessary" ]
337b3f98753d09eaab1c72dcd37bb852a3fa5ac6
https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L345-L367
train
47,779
OSSOS/MOP
src/ossos/core/ossos/fitsviewer/baseviewer.py
WxMPLFitsViewer.align
def align(self, cutout, reading, source): """ Set the display center to the reference point. @param cutout: The cutout to align on @type cutout: SourceCutout @param reading: The reading this cutout is from @type reading: SourceReading @param source: The source the reading is from @type source: Source @return: """ if not self.current_displayable: return if not self.current_displayable.aligned: focus_sky_coord = reading.reference_sky_coord #focus_calculator = SingletFocusCalculator(source) #logger.debug("Got focus calculator {} for source {}".format(focus_calculator, source)) #focus = cutout.flip_flip(focus_calculator.calculate_focus(reading)) #focus = cutout.get_pixel_coordinates(focus) #focus = cutout.pix2world(focus[0], focus[1], usepv=False) #focus_sky_coord = SkyCoord(focus[0], focus[1]) self.current_displayable.pan_to(focus_sky_coord)
python
def align(self, cutout, reading, source): """ Set the display center to the reference point. @param cutout: The cutout to align on @type cutout: SourceCutout @param reading: The reading this cutout is from @type reading: SourceReading @param source: The source the reading is from @type source: Source @return: """ if not self.current_displayable: return if not self.current_displayable.aligned: focus_sky_coord = reading.reference_sky_coord #focus_calculator = SingletFocusCalculator(source) #logger.debug("Got focus calculator {} for source {}".format(focus_calculator, source)) #focus = cutout.flip_flip(focus_calculator.calculate_focus(reading)) #focus = cutout.get_pixel_coordinates(focus) #focus = cutout.pix2world(focus[0], focus[1], usepv=False) #focus_sky_coord = SkyCoord(focus[0], focus[1]) self.current_displayable.pan_to(focus_sky_coord)
[ "def", "align", "(", "self", ",", "cutout", ",", "reading", ",", "source", ")", ":", "if", "not", "self", ".", "current_displayable", ":", "return", "if", "not", "self", ".", "current_displayable", ".", "aligned", ":", "focus_sky_coord", "=", "reading", "....
Set the display center to the reference point. @param cutout: The cutout to align on @type cutout: SourceCutout @param reading: The reading this cutout is from @type reading: SourceReading @param source: The source the reading is from @type source: Source @return:
[ "Set", "the", "display", "center", "to", "the", "reference", "point", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/baseviewer.py#L141-L163
train
47,780
OSSOS/MOP
src/ossos/core/ossos/daophot.py
phot_mag
def phot_mag(*args, **kwargs): """Wrapper around phot which only returns the computed magnitude directly.""" try: return phot(*args, **kwargs) except IndexError: raise TaskError("No photometric records returned for {0}".format(kwargs))
python
def phot_mag(*args, **kwargs): """Wrapper around phot which only returns the computed magnitude directly.""" try: return phot(*args, **kwargs) except IndexError: raise TaskError("No photometric records returned for {0}".format(kwargs))
[ "def", "phot_mag", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "phot", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "IndexError", ":", "raise", "TaskError", "(", "\"No photometric records returned for {0}\"", "."...
Wrapper around phot which only returns the computed magnitude directly.
[ "Wrapper", "around", "phot", "which", "only", "returns", "the", "computed", "magnitude", "directly", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/daophot.py#L161-L166
train
47,781
playpauseandstop/rororo
rororo/settings.py
from_env
def from_env(key: str, default: T = None) -> Union[str, Optional[T]]: """Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None`` """ return os.getenv(key, default)
python
def from_env(key: str, default: T = None) -> Union[str, Optional[T]]: """Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None`` """ return os.getenv(key, default)
[ "def", "from_env", "(", "key", ":", "str", ",", "default", ":", "T", "=", "None", ")", "->", "Union", "[", "str", ",", "Optional", "[", "T", "]", "]", ":", "return", "os", ".", "getenv", "(", "key", ",", "default", ")" ]
Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None``
[ "Shortcut", "for", "safely", "reading", "environment", "variable", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L26-L34
train
47,782
playpauseandstop/rororo
rororo/settings.py
immutable_settings
def immutable_settings(defaults: Settings, **optionals: Any) -> types.MappingProxyType: r"""Initialize and return immutable Settings dictionary. Settings dictionary allows you to setup settings values from multiple sources and make sure that values cannot be changed, updated by anyone else after initialization. This helps keep things clear and not worry about hidden settings change somewhere around your web application. :param defaults: Read settings values from module or dict-like instance. :param \*\*optionals: Update base settings with optional values. In common additional values shouldn't be passed, if settings values already populated from local settings or environment. But in case of using application factories this makes sense:: from . import settings def create_app(**options): app = ... app.settings = immutable_settings(settings, **options) return app And yes each additional key overwrite default setting value. """ settings = {key: value for key, value in iter_settings(defaults)} for key, value in iter_settings(optionals): settings[key] = value return types.MappingProxyType(settings)
python
def immutable_settings(defaults: Settings, **optionals: Any) -> types.MappingProxyType: r"""Initialize and return immutable Settings dictionary. Settings dictionary allows you to setup settings values from multiple sources and make sure that values cannot be changed, updated by anyone else after initialization. This helps keep things clear and not worry about hidden settings change somewhere around your web application. :param defaults: Read settings values from module or dict-like instance. :param \*\*optionals: Update base settings with optional values. In common additional values shouldn't be passed, if settings values already populated from local settings or environment. But in case of using application factories this makes sense:: from . import settings def create_app(**options): app = ... app.settings = immutable_settings(settings, **options) return app And yes each additional key overwrite default setting value. """ settings = {key: value for key, value in iter_settings(defaults)} for key, value in iter_settings(optionals): settings[key] = value return types.MappingProxyType(settings)
[ "def", "immutable_settings", "(", "defaults", ":", "Settings", ",", "*", "*", "optionals", ":", "Any", ")", "->", "types", ".", "MappingProxyType", ":", "settings", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "iter_settings", "(", "d...
r"""Initialize and return immutable Settings dictionary. Settings dictionary allows you to setup settings values from multiple sources and make sure that values cannot be changed, updated by anyone else after initialization. This helps keep things clear and not worry about hidden settings change somewhere around your web application. :param defaults: Read settings values from module or dict-like instance. :param \*\*optionals: Update base settings with optional values. In common additional values shouldn't be passed, if settings values already populated from local settings or environment. But in case of using application factories this makes sense:: from . import settings def create_app(**options): app = ... app.settings = immutable_settings(settings, **options) return app And yes each additional key overwrite default setting value.
[ "r", "Initialize", "and", "return", "immutable", "Settings", "dictionary", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L37-L67
train
47,783
playpauseandstop/rororo
rororo/settings.py
inject_settings
def inject_settings(mixed: Union[str, Settings], context: MutableMapping[str, Any], fail_silently: bool = False) -> None: """Inject settings values to given context. :param mixed: Settings can be a string (that it will be read from Python path), Python module or dict-like instance. :param context: Context to assign settings key values. It should support dict-like item assingment. :param fail_silently: When enabled and reading settings from Python path ignore errors if given Python path couldn't be loaded. """ if isinstance(mixed, str): try: mixed = import_module(mixed) except Exception: if fail_silently: return raise for key, value in iter_settings(mixed): context[key] = value
python
def inject_settings(mixed: Union[str, Settings], context: MutableMapping[str, Any], fail_silently: bool = False) -> None: """Inject settings values to given context. :param mixed: Settings can be a string (that it will be read from Python path), Python module or dict-like instance. :param context: Context to assign settings key values. It should support dict-like item assingment. :param fail_silently: When enabled and reading settings from Python path ignore errors if given Python path couldn't be loaded. """ if isinstance(mixed, str): try: mixed = import_module(mixed) except Exception: if fail_silently: return raise for key, value in iter_settings(mixed): context[key] = value
[ "def", "inject_settings", "(", "mixed", ":", "Union", "[", "str", ",", "Settings", "]", ",", "context", ":", "MutableMapping", "[", "str", ",", "Any", "]", ",", "fail_silently", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "isinstance", "("...
Inject settings values to given context. :param mixed: Settings can be a string (that it will be read from Python path), Python module or dict-like instance. :param context: Context to assign settings key values. It should support dict-like item assingment. :param fail_silently: When enabled and reading settings from Python path ignore errors if given Python path couldn't be loaded.
[ "Inject", "settings", "values", "to", "given", "context", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L70-L94
train
47,784
playpauseandstop/rororo
rororo/settings.py
iter_settings
def iter_settings(mixed: Settings) -> Iterator[Tuple[str, Any]]: """Iterate over settings values from settings module or dict-like instance. :param mixed: Settings instance to iterate. """ if isinstance(mixed, types.ModuleType): for attr in dir(mixed): if not is_setting_key(attr): continue yield (attr, getattr(mixed, attr)) else: yield from filter(lambda item: is_setting_key(item[0]), mixed.items())
python
def iter_settings(mixed: Settings) -> Iterator[Tuple[str, Any]]: """Iterate over settings values from settings module or dict-like instance. :param mixed: Settings instance to iterate. """ if isinstance(mixed, types.ModuleType): for attr in dir(mixed): if not is_setting_key(attr): continue yield (attr, getattr(mixed, attr)) else: yield from filter(lambda item: is_setting_key(item[0]), mixed.items())
[ "def", "iter_settings", "(", "mixed", ":", "Settings", ")", "->", "Iterator", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ":", "if", "isinstance", "(", "mixed", ",", "types", ".", "ModuleType", ")", ":", "for", "attr", "in", "dir", "(", "mixed", ...
Iterate over settings values from settings module or dict-like instance. :param mixed: Settings instance to iterate.
[ "Iterate", "over", "settings", "values", "from", "settings", "module", "or", "dict", "-", "like", "instance", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L124-L135
train
47,785
playpauseandstop/rororo
rororo/settings.py
setup_locale
def setup_locale(lc_all: str, first_weekday: int = None, *, lc_collate: str = None, lc_ctype: str = None, lc_messages: str = None, lc_monetary: str = None, lc_numeric: str = None, lc_time: str = None) -> str: """Shortcut helper to setup locale for backend application. :param lc_all: Locale to use. :param first_weekday: Weekday for start week. 0 for Monday, 6 for Sunday. By default: None :param lc_collate: Collate locale to use. By default: ``<lc_all>`` :param lc_ctype: Ctype locale to use. By default: ``<lc_all>`` :param lc_messages: Messages locale to use. By default: ``<lc_all>`` :param lc_monetary: Monetary locale to use. By default: ``<lc_all>`` :param lc_numeric: Numeric locale to use. By default: ``<lc_all>`` :param lc_time: Time locale to use. By default: ``<lc_all>`` """ if first_weekday is not None: calendar.setfirstweekday(first_weekday) locale.setlocale(locale.LC_COLLATE, lc_collate or lc_all) locale.setlocale(locale.LC_CTYPE, lc_ctype or lc_all) locale.setlocale(locale.LC_MESSAGES, lc_messages or lc_all) locale.setlocale(locale.LC_MONETARY, lc_monetary or lc_all) locale.setlocale(locale.LC_NUMERIC, lc_numeric or lc_all) locale.setlocale(locale.LC_TIME, lc_time or lc_all) return locale.setlocale(locale.LC_ALL, lc_all)
python
def setup_locale(lc_all: str, first_weekday: int = None, *, lc_collate: str = None, lc_ctype: str = None, lc_messages: str = None, lc_monetary: str = None, lc_numeric: str = None, lc_time: str = None) -> str: """Shortcut helper to setup locale for backend application. :param lc_all: Locale to use. :param first_weekday: Weekday for start week. 0 for Monday, 6 for Sunday. By default: None :param lc_collate: Collate locale to use. By default: ``<lc_all>`` :param lc_ctype: Ctype locale to use. By default: ``<lc_all>`` :param lc_messages: Messages locale to use. By default: ``<lc_all>`` :param lc_monetary: Monetary locale to use. By default: ``<lc_all>`` :param lc_numeric: Numeric locale to use. By default: ``<lc_all>`` :param lc_time: Time locale to use. By default: ``<lc_all>`` """ if first_weekday is not None: calendar.setfirstweekday(first_weekday) locale.setlocale(locale.LC_COLLATE, lc_collate or lc_all) locale.setlocale(locale.LC_CTYPE, lc_ctype or lc_all) locale.setlocale(locale.LC_MESSAGES, lc_messages or lc_all) locale.setlocale(locale.LC_MONETARY, lc_monetary or lc_all) locale.setlocale(locale.LC_NUMERIC, lc_numeric or lc_all) locale.setlocale(locale.LC_TIME, lc_time or lc_all) return locale.setlocale(locale.LC_ALL, lc_all)
[ "def", "setup_locale", "(", "lc_all", ":", "str", ",", "first_weekday", ":", "int", "=", "None", ",", "*", ",", "lc_collate", ":", "str", "=", "None", ",", "lc_ctype", ":", "str", "=", "None", ",", "lc_messages", ":", "str", "=", "None", ",", "lc_mon...
Shortcut helper to setup locale for backend application. :param lc_all: Locale to use. :param first_weekday: Weekday for start week. 0 for Monday, 6 for Sunday. By default: None :param lc_collate: Collate locale to use. By default: ``<lc_all>`` :param lc_ctype: Ctype locale to use. By default: ``<lc_all>`` :param lc_messages: Messages locale to use. By default: ``<lc_all>`` :param lc_monetary: Monetary locale to use. By default: ``<lc_all>`` :param lc_numeric: Numeric locale to use. By default: ``<lc_all>`` :param lc_time: Time locale to use. By default: ``<lc_all>``
[ "Shortcut", "helper", "to", "setup", "locale", "for", "backend", "application", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L138-L169
train
47,786
playpauseandstop/rororo
rororo/settings.py
setup_timezone
def setup_timezone(timezone: str) -> None: """Shortcut helper to configure timezone for backend application. :param timezone: Timezone to use, e.g. "UTC", "Europe/Kiev". """ if timezone and hasattr(time, 'tzset'): tz_root = '/usr/share/zoneinfo' tz_filename = os.path.join(tz_root, *(timezone.split('/'))) if os.path.exists(tz_root) and not os.path.exists(tz_filename): raise ValueError('Incorrect timezone value: {0}'.format(timezone)) os.environ['TZ'] = timezone time.tzset()
python
def setup_timezone(timezone: str) -> None: """Shortcut helper to configure timezone for backend application. :param timezone: Timezone to use, e.g. "UTC", "Europe/Kiev". """ if timezone and hasattr(time, 'tzset'): tz_root = '/usr/share/zoneinfo' tz_filename = os.path.join(tz_root, *(timezone.split('/'))) if os.path.exists(tz_root) and not os.path.exists(tz_filename): raise ValueError('Incorrect timezone value: {0}'.format(timezone)) os.environ['TZ'] = timezone time.tzset()
[ "def", "setup_timezone", "(", "timezone", ":", "str", ")", "->", "None", ":", "if", "timezone", "and", "hasattr", "(", "time", ",", "'tzset'", ")", ":", "tz_root", "=", "'/usr/share/zoneinfo'", "tz_filename", "=", "os", ".", "path", ".", "join", "(", "tz...
Shortcut helper to configure timezone for backend application. :param timezone: Timezone to use, e.g. "UTC", "Europe/Kiev".
[ "Shortcut", "helper", "to", "configure", "timezone", "for", "backend", "application", "." ]
28a04e8028c29647941e727116335e9d6fd64c27
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/settings.py#L172-L185
train
47,787
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
inputs
def inputs(header): """Read through the HISTORY cards in an image header looking for detrend input lines. Detrend inputs are given on lines like: HISTORY imcombred: file_id We require that the value in file_id be store in the CADC archive before adding to the inputs list. """ import string, re inputs=[] for h in header.ascardlist(): if h.key=="HISTORY": g=h.value result=re.search('imcombred: (\d{6}[bfopd])\d{2} .*',g) if not result: continue file_id=result.group(1) import os status=os.system("adInfo -a CFHT -s "+file_id) if status==0: result=re.search('(\d{6}).*',file_id) if not result: continue expnum=result.group(1) inputs.append(expnum) if len(inputs)==0: ### try using the new FLIPS 2.0 keywords nit = header.get('IMCMB_NI',0) if nit==0: return(inputs) for nin in range(nit): kwd='IMCMB_'+str(nin).zfill(2) file=(header.get(kwd,'')) result=re.search('.*(\d{6}[bfopd]).*',g) if not result: continue file_id=result.group(1) import os status=os.system("adInfo -a CFHT -s "+file_id) if status==0: result=re.search('(\d{6}).*',file_id) if not result: continue expnum=result.group(1) inputs.append(expnum) return inputs
python
def inputs(header): """Read through the HISTORY cards in an image header looking for detrend input lines. Detrend inputs are given on lines like: HISTORY imcombred: file_id We require that the value in file_id be store in the CADC archive before adding to the inputs list. """ import string, re inputs=[] for h in header.ascardlist(): if h.key=="HISTORY": g=h.value result=re.search('imcombred: (\d{6}[bfopd])\d{2} .*',g) if not result: continue file_id=result.group(1) import os status=os.system("adInfo -a CFHT -s "+file_id) if status==0: result=re.search('(\d{6}).*',file_id) if not result: continue expnum=result.group(1) inputs.append(expnum) if len(inputs)==0: ### try using the new FLIPS 2.0 keywords nit = header.get('IMCMB_NI',0) if nit==0: return(inputs) for nin in range(nit): kwd='IMCMB_'+str(nin).zfill(2) file=(header.get(kwd,'')) result=re.search('.*(\d{6}[bfopd]).*',g) if not result: continue file_id=result.group(1) import os status=os.system("adInfo -a CFHT -s "+file_id) if status==0: result=re.search('(\d{6}).*',file_id) if not result: continue expnum=result.group(1) inputs.append(expnum) return inputs
[ "def", "inputs", "(", "header", ")", ":", "import", "string", ",", "re", "inputs", "=", "[", "]", "for", "h", "in", "header", ".", "ascardlist", "(", ")", ":", "if", "h", ".", "key", "==", "\"HISTORY\"", ":", "g", "=", "h", ".", "value", "result"...
Read through the HISTORY cards in an image header looking for detrend input lines. Detrend inputs are given on lines like: HISTORY imcombred: file_id We require that the value in file_id be store in the CADC archive before adding to the inputs list.
[ "Read", "through", "the", "HISTORY", "cards", "in", "an", "image", "header", "looking", "for", "detrend", "input", "lines", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L138-L188
train
47,788
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
elixir_decode
def elixir_decode(elixir_filename): """ Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits """ import re, pyfits parts_RE=re.compile(r'([^\.\s]+)') dataset_name = parts_RE.findall(elixir_filename) ### check that this was a valid elixir_filename if not dataset_name or len(dataset_name)<5 : raise ValueError('String %s does not parse as elixir filename' % elixir_filename ) comments={'exptime': 'Integration time (seconds)', 'filter': 'Name of filter in position ', 'crunid': 'CFHT Q RunID', 'obstype': 'Observation or Exposure type', 'imageid': 'CCD chip number', 'filename': 'file name at creation of this MEF file' } keywords={} keywords['filename']=elixir_filename keywords['runid']=dataset_name[0] keywords['obstype']=dataset_name[1] keywords['exptime']=None keywords['filter']=None ### if the third part of the name is all numbers we assume exposure time if re.match(r'\d+',dataset_name[2]): keyword['exptime']=int(dataset_name[2]) else: keyword['filter']=dataset_name[2] keywords['imageid']=dataset_name[3] keywords['version']=dataset_name[4] header=pyfits.Header() for keyword in keywords.keys(): if keywords[keyword]: header.update(keyword,keywords[keyword],comment=comment[keyword]) return header
python
def elixir_decode(elixir_filename): """ Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits """ import re, pyfits parts_RE=re.compile(r'([^\.\s]+)') dataset_name = parts_RE.findall(elixir_filename) ### check that this was a valid elixir_filename if not dataset_name or len(dataset_name)<5 : raise ValueError('String %s does not parse as elixir filename' % elixir_filename ) comments={'exptime': 'Integration time (seconds)', 'filter': 'Name of filter in position ', 'crunid': 'CFHT Q RunID', 'obstype': 'Observation or Exposure type', 'imageid': 'CCD chip number', 'filename': 'file name at creation of this MEF file' } keywords={} keywords['filename']=elixir_filename keywords['runid']=dataset_name[0] keywords['obstype']=dataset_name[1] keywords['exptime']=None keywords['filter']=None ### if the third part of the name is all numbers we assume exposure time if re.match(r'\d+',dataset_name[2]): keyword['exptime']=int(dataset_name[2]) else: keyword['filter']=dataset_name[2] keywords['imageid']=dataset_name[3] keywords['version']=dataset_name[4] header=pyfits.Header() for keyword in keywords.keys(): if keywords[keyword]: header.update(keyword,keywords[keyword],comment=comment[keyword]) return header
[ "def", "elixir_decode", "(", "elixir_filename", ")", ":", "import", "re", ",", "pyfits", "parts_RE", "=", "re", ".", "compile", "(", "r'([^\\.\\s]+)'", ")", "dataset_name", "=", "parts_RE", ".", "findall", "(", "elixir_filename", ")", "### check that this was a va...
Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits
[ "Takes", "an", "elixir", "style", "file", "name", "and", "decodes", "it", "s", "content", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L211-L257
train
47,789
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
create_mef
def create_mef(filename=None): """ Create a file an MEF fits file called filename. Generate a random filename if None given """ import pyfits, time if not filename: ### here I know what filename is to start with. import tempfile filename=tempfile.mktemp(suffix='.fits') else: import string, re ### filenames gotta be a string and no lead/trailing space filename=string.strip(str(filename)) ### require that the filename ends in .fits suffix=re.match(r'^.*.fits$',filename) if not suffix: filename = filename+'.fits' ### create an HDU list temp = pyfits.HDUList() ### create a primary HDU prihdu = pyfits.PrimaryHDU() ### build the header h=prihdu.header h.update('EXTEND',pyfits.TRUE,after='NAXIS') h.update('NEXTEND',0,after='EXTEND') h.add_comment('MEF created at CADC') h.add_comment('Created using '+__name__+' '+__Version__) h.add_comment('Extensions may not be in CCD order') #h.update('cfh12k',__Version__,comment='split2mef software at CADC') h.add_comment('Use the EXTNAME keyword') h.add_history('Primary HDU created on '+time.asctime()) ### stick the HDU onto the HDU list and write to file temp.append(prihdu) temp.writeto(filename) temp.close() return(filename)
python
def create_mef(filename=None): """ Create a file an MEF fits file called filename. Generate a random filename if None given """ import pyfits, time if not filename: ### here I know what filename is to start with. import tempfile filename=tempfile.mktemp(suffix='.fits') else: import string, re ### filenames gotta be a string and no lead/trailing space filename=string.strip(str(filename)) ### require that the filename ends in .fits suffix=re.match(r'^.*.fits$',filename) if not suffix: filename = filename+'.fits' ### create an HDU list temp = pyfits.HDUList() ### create a primary HDU prihdu = pyfits.PrimaryHDU() ### build the header h=prihdu.header h.update('EXTEND',pyfits.TRUE,after='NAXIS') h.update('NEXTEND',0,after='EXTEND') h.add_comment('MEF created at CADC') h.add_comment('Created using '+__name__+' '+__Version__) h.add_comment('Extensions may not be in CCD order') #h.update('cfh12k',__Version__,comment='split2mef software at CADC') h.add_comment('Use the EXTNAME keyword') h.add_history('Primary HDU created on '+time.asctime()) ### stick the HDU onto the HDU list and write to file temp.append(prihdu) temp.writeto(filename) temp.close() return(filename)
[ "def", "create_mef", "(", "filename", "=", "None", ")", ":", "import", "pyfits", ",", "time", "if", "not", "filename", ":", "### here I know what filename is to start with.", "import", "tempfile", "filename", "=", "tempfile", ".", "mktemp", "(", "suffix", "=", "...
Create a file an MEF fits file called filename. Generate a random filename if None given
[ "Create", "a", "file", "an", "MEF", "fits", "file", "called", "filename", ".", "Generate", "a", "random", "filename", "if", "None", "given" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L277-L319
train
47,790
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
strip_pad
def strip_pad(hdu): """Remove the padding lines that CFHT adds to headers""" l = hdu.header.ascardlist() d = [] for index in range(len(l)): if l[index].key in __comment_keys and str(l[index])==__cfht_padding: d.append(index) d.reverse() for index in d: del l[index] return(0)
python
def strip_pad(hdu): """Remove the padding lines that CFHT adds to headers""" l = hdu.header.ascardlist() d = [] for index in range(len(l)): if l[index].key in __comment_keys and str(l[index])==__cfht_padding: d.append(index) d.reverse() for index in d: del l[index] return(0)
[ "def", "strip_pad", "(", "hdu", ")", ":", "l", "=", "hdu", ".", "header", ".", "ascardlist", "(", ")", "d", "=", "[", "]", "for", "index", "in", "range", "(", "len", "(", "l", ")", ")", ":", "if", "l", "[", "index", "]", ".", "key", "in", "...
Remove the padding lines that CFHT adds to headers
[ "Remove", "the", "padding", "lines", "that", "CFHT", "adds", "to", "headers" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L343-L354
train
47,791
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
stack
def stack(outfile,infiles,verbose=0): """ Stick infiles into outfiles as FITS extensions. outfile willl contain an MEF format file of the single extension FITS files named in the infiles array """ import os, sys, string, tempfile, shutil import pyfits, re, time ### if there is a pre-existing MEF file for output then append to it ### otherwise we need to create a PrimaryHDU if os.access(outfile,os.R_OK)!=1: if verbose: print "Creating new MEF file: ",outfile outfile=create_mef(outfile) ### get a handle for the output image, _open is the local variant of ### pyfits.open and just does some error recovery if pyfits.open raises an ### exception. out = pyfits.open(outfile,'append') hdr = out[0].header count=0 ### append the fits files given on the command line to the ### output file. det_xmin=None det_xmax=None det_ymin=None det_ymax=None for infile in infiles: if verbose: print "Adding ",infile," to ",outfile ### _open tries to handle bad fits format exceptions. file=_open(infile) if not file: raise IOError("Cann't get the HDU for "+infile) for hdu in file: extname=None if hdu.header.has_key('EXTNAME') : extname=hdu.header['EXTNAME'] elif hdu.header.has_key('EXTVER') : extname="ccd"+string.zfill(hdu.header.has_key('EXTVER'),2) if hdu.header.has_key('EPOCH'): if hdu.header.has_key('EQUINOX'): del hdu.header['EPOCH'] else: hdu.header.update('EQUINOX',hdu.header['EQUINOX'].value, comment=hdu.header['EQUINOX'].comment) ahdu=pyfits.ImageHDU(data=hdu.data, header=hdu.header, name=extname) out.append(ahdu) ### build the size of the overall detector if hdu.header.has_key('DETSEC'): values=re.findall(r'(\d+)', hdu.header['DETSEC']) if len(values)==4: xmin=int(values[0]) xmax=int(values[1]) ymin=int(values[2]) ymax=int(values[3]) if xmin>xmax: t=xmin xmin=xmax xmax=t if ymin>ymax: t=ymin ymin=ymax ymax=t if xmin<det_xmin or not det_xmin: det_xmin=xmin if xmax>det_xmax or not det_xmax: det_xmax=xmax if ymin<det_ymin or not det_ymin: det_ymin=ymin if ymax>det_ymax or not det_ymax: det_ymax=ymax file.close() detsize='['+str(det_xmin)+':'+str(det_xmax)+','+str(det_ymin)+':'+str(det_ymax)+']' out[0].header.update('DETSIZE',detsize,comment='Size of Mosaic') out.close() if verbose: print "Done building MEF: ",outfile return 0
python
def stack(outfile,infiles,verbose=0): """ Stick infiles into outfiles as FITS extensions. outfile willl contain an MEF format file of the single extension FITS files named in the infiles array """ import os, sys, string, tempfile, shutil import pyfits, re, time ### if there is a pre-existing MEF file for output then append to it ### otherwise we need to create a PrimaryHDU if os.access(outfile,os.R_OK)!=1: if verbose: print "Creating new MEF file: ",outfile outfile=create_mef(outfile) ### get a handle for the output image, _open is the local variant of ### pyfits.open and just does some error recovery if pyfits.open raises an ### exception. out = pyfits.open(outfile,'append') hdr = out[0].header count=0 ### append the fits files given on the command line to the ### output file. det_xmin=None det_xmax=None det_ymin=None det_ymax=None for infile in infiles: if verbose: print "Adding ",infile," to ",outfile ### _open tries to handle bad fits format exceptions. file=_open(infile) if not file: raise IOError("Cann't get the HDU for "+infile) for hdu in file: extname=None if hdu.header.has_key('EXTNAME') : extname=hdu.header['EXTNAME'] elif hdu.header.has_key('EXTVER') : extname="ccd"+string.zfill(hdu.header.has_key('EXTVER'),2) if hdu.header.has_key('EPOCH'): if hdu.header.has_key('EQUINOX'): del hdu.header['EPOCH'] else: hdu.header.update('EQUINOX',hdu.header['EQUINOX'].value, comment=hdu.header['EQUINOX'].comment) ahdu=pyfits.ImageHDU(data=hdu.data, header=hdu.header, name=extname) out.append(ahdu) ### build the size of the overall detector if hdu.header.has_key('DETSEC'): values=re.findall(r'(\d+)', hdu.header['DETSEC']) if len(values)==4: xmin=int(values[0]) xmax=int(values[1]) ymin=int(values[2]) ymax=int(values[3]) if xmin>xmax: t=xmin xmin=xmax xmax=t if ymin>ymax: t=ymin ymin=ymax ymax=t if xmin<det_xmin or not det_xmin: det_xmin=xmin if xmax>det_xmax or not det_xmax: det_xmax=xmax if ymin<det_ymin or not det_ymin: det_ymin=ymin if ymax>det_ymax or not det_ymax: det_ymax=ymax file.close() detsize='['+str(det_xmin)+':'+str(det_xmax)+','+str(det_ymin)+':'+str(det_ymax)+']' out[0].header.update('DETSIZE',detsize,comment='Size of Mosaic') out.close() if verbose: print "Done building MEF: ",outfile return 0
[ "def", "stack", "(", "outfile", ",", "infiles", ",", "verbose", "=", "0", ")", ":", "import", "os", ",", "sys", ",", "string", ",", "tempfile", ",", "shutil", "import", "pyfits", ",", "re", ",", "time", "### if there is a pre-existing MEF file for output then ...
Stick infiles into outfiles as FITS extensions. outfile willl contain an MEF format file of the single extension FITS files named in the infiles array
[ "Stick", "infiles", "into", "outfiles", "as", "FITS", "extensions", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L380-L474
train
47,792
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
adGet
def adGet(file_id, archive="CFHT", extno=None, cutout=None ): """Use get a fits image from the CADC.""" import os, string, re,urllib #proxy="http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" if file_id is None: return(-1) if extno is None: filename=file_id+".fits" else: filename="%s%s.fits" % (file_id, string.zfill(extno,2)) print filename if os.access(filename,os.R_OK): return filename args={ "file_id": file_id, "archive": archive } if extno is not None: args['cutout']="["+str(extno+1)+"]" else: args['cutout']='' if cutout is not None: args['cutout']=args['cutout']+cutout argline="" sep="" import sys ### get the directory that may contain the data mop_data_path=os.curdir if os.environ.has_key('MOP_DATA_PATH'): mop_data_path=os.environ['MOP_DATA_PATH'] suffix="fits" basefile=mop_data_path+"/"+file_id+".fits" print basefile if not os.access(basefile,os.R_OK): argdict={} argline='' sep='' for arg in args: if not args[arg]: continue argline+=sep+"%s=%s" % ( arg, args[arg]) sep='&' url=proxy+"?"+argline command="curl --silent -g --fail --max-time 1800 --user jkavelaars:newone '"+url+"' | gunzip > "+filename else: command="imcopy %s%s %s" % ( basefile,args['cutout'],filename) print command try: status=os.system(command) except: sys.stderr.write("Failed to execute command: %s\n" % ( command)) raise TaskError, "getData failed" if status!=0: sys.stderr.write("Failed while executing command: %s\n" % ( command)) raise TaskError, "getData failed" return filename
python
def adGet(file_id, archive="CFHT", extno=None, cutout=None ): """Use get a fits image from the CADC.""" import os, string, re,urllib #proxy="http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" if file_id is None: return(-1) if extno is None: filename=file_id+".fits" else: filename="%s%s.fits" % (file_id, string.zfill(extno,2)) print filename if os.access(filename,os.R_OK): return filename args={ "file_id": file_id, "archive": archive } if extno is not None: args['cutout']="["+str(extno+1)+"]" else: args['cutout']='' if cutout is not None: args['cutout']=args['cutout']+cutout argline="" sep="" import sys ### get the directory that may contain the data mop_data_path=os.curdir if os.environ.has_key('MOP_DATA_PATH'): mop_data_path=os.environ['MOP_DATA_PATH'] suffix="fits" basefile=mop_data_path+"/"+file_id+".fits" print basefile if not os.access(basefile,os.R_OK): argdict={} argline='' sep='' for arg in args: if not args[arg]: continue argline+=sep+"%s=%s" % ( arg, args[arg]) sep='&' url=proxy+"?"+argline command="curl --silent -g --fail --max-time 1800 --user jkavelaars:newone '"+url+"' | gunzip > "+filename else: command="imcopy %s%s %s" % ( basefile,args['cutout'],filename) print command try: status=os.system(command) except: sys.stderr.write("Failed to execute command: %s\n" % ( command)) raise TaskError, "getData failed" if status!=0: sys.stderr.write("Failed while executing command: %s\n" % ( command)) raise TaskError, "getData failed" return filename
[ "def", "adGet", "(", "file_id", ",", "archive", "=", "\"CFHT\"", ",", "extno", "=", "None", ",", "cutout", "=", "None", ")", ":", "import", "os", ",", "string", ",", "re", ",", "urllib", "#proxy=\"http://www1.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData\"", ...
Use get a fits image from the CADC.
[ "Use", "get", "a", "fits", "image", "from", "the", "CADC", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L495-L568
train
47,793
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
_open
def _open(file,mode='copyonwrite'): """Opens a FITS format file and calls _open_fix if header doesn't verify correctly. """ import pyfits try: infits=pyfits.open(file,mode) hdu=infits except (ValueError,pyfits.VerifyError,pyfits.FITS_SevereError): import sys #### I really only know how to deal with one error right now. #if str(sys.exc_info()[1])=='mandatory keywords are not fixed format': hdu=_open_fix(file) #else: # print sys.exc_info()[1] # print " Failed trying to repair ", file # raise for f in hdu: strip_pad(f) return hdu
python
def _open(file,mode='copyonwrite'): """Opens a FITS format file and calls _open_fix if header doesn't verify correctly. """ import pyfits try: infits=pyfits.open(file,mode) hdu=infits except (ValueError,pyfits.VerifyError,pyfits.FITS_SevereError): import sys #### I really only know how to deal with one error right now. #if str(sys.exc_info()[1])=='mandatory keywords are not fixed format': hdu=_open_fix(file) #else: # print sys.exc_info()[1] # print " Failed trying to repair ", file # raise for f in hdu: strip_pad(f) return hdu
[ "def", "_open", "(", "file", ",", "mode", "=", "'copyonwrite'", ")", ":", "import", "pyfits", "try", ":", "infits", "=", "pyfits", ".", "open", "(", "file", ",", "mode", ")", "hdu", "=", "infits", "except", "(", "ValueError", ",", "pyfits", ".", "Ver...
Opens a FITS format file and calls _open_fix if header doesn't verify correctly.
[ "Opens", "a", "FITS", "format", "file", "and", "calls", "_open_fix", "if", "header", "doesn", "t", "verify", "correctly", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L590-L611
train
47,794
OSSOS/MOP
src/jjk/preproc/MOPfits_old.py
find_proc_date
def find_proc_date(header): """Search the HISTORY fields of a header looking for the FLIPS processing date. """ import string, re for h in header.ascardlist(): if h.key=="HISTORY": g=h.value if ( string.find(g,'FLIPS 1.0 -:') ): result=re.search('imred: FLIPS 1.0 - \S{3} (.*) - ([\s\d]\d:\d\d:\d\d)\s*$',g) if result: date=result.group(1) time=result.group(2) datetime=date+" "+time return datetime return None
python
def find_proc_date(header): """Search the HISTORY fields of a header looking for the FLIPS processing date. """ import string, re for h in header.ascardlist(): if h.key=="HISTORY": g=h.value if ( string.find(g,'FLIPS 1.0 -:') ): result=re.search('imred: FLIPS 1.0 - \S{3} (.*) - ([\s\d]\d:\d\d:\d\d)\s*$',g) if result: date=result.group(1) time=result.group(2) datetime=date+" "+time return datetime return None
[ "def", "find_proc_date", "(", "header", ")", ":", "import", "string", ",", "re", "for", "h", "in", "header", ".", "ascardlist", "(", ")", ":", "if", "h", ".", "key", "==", "\"HISTORY\"", ":", "g", "=", "h", ".", "value", "if", "(", "string", ".", ...
Search the HISTORY fields of a header looking for the FLIPS processing date.
[ "Search", "the", "HISTORY", "fields", "of", "a", "header", "looking", "for", "the", "FLIPS", "processing", "date", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L631-L646
train
47,795
OSSOS/MOP
src/ossos/core/ossos/ssos.py
SSOSParser.build_source_reading
def build_source_reading(expnum, ccd=None, ftype='p'): """ Build an astrom.Observation object for a SourceReading :param expnum: (str) Name or CFHT Exposure number of the observation. :param ccd: (str) CCD is this observation associated with. (can be None) :param ftype: (str) exposure time (specific to CFHT imaging) :return: An astrom.Observation object for the observation. :rtype: astrom.Observation """ logger.debug("Building source reading for expnum:{} ccd:{} ftype:{}".format(expnum, ccd, ftype)) return astrom.Observation(expnum=str(expnum), ftype=ftype, ccdnum=ccd)
python
def build_source_reading(expnum, ccd=None, ftype='p'): """ Build an astrom.Observation object for a SourceReading :param expnum: (str) Name or CFHT Exposure number of the observation. :param ccd: (str) CCD is this observation associated with. (can be None) :param ftype: (str) exposure time (specific to CFHT imaging) :return: An astrom.Observation object for the observation. :rtype: astrom.Observation """ logger.debug("Building source reading for expnum:{} ccd:{} ftype:{}".format(expnum, ccd, ftype)) return astrom.Observation(expnum=str(expnum), ftype=ftype, ccdnum=ccd)
[ "def", "build_source_reading", "(", "expnum", ",", "ccd", "=", "None", ",", "ftype", "=", "'p'", ")", ":", "logger", ".", "debug", "(", "\"Building source reading for expnum:{} ccd:{} ftype:{}\"", ".", "format", "(", "expnum", ",", "ccd", ",", "ftype", ")", ")...
Build an astrom.Observation object for a SourceReading :param expnum: (str) Name or CFHT Exposure number of the observation. :param ccd: (str) CCD is this observation associated with. (can be None) :param ftype: (str) exposure time (specific to CFHT imaging) :return: An astrom.Observation object for the observation. :rtype: astrom.Observation
[ "Build", "an", "astrom", ".", "Observation", "object", "for", "a", "SourceReading" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/ssos.py#L280-L296
train
47,796
OSSOS/MOP
src/jjk/preproc/wcsutil.py
WCSObject.recenter
def recenter(self): """ Reset the reference position values to correspond to the center of the reference frame. Algorithm used here developed by Colin Cox - 27-Jan-2004. """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: print 'WCS.recenter() only supported for TAN projections.' raise TypeError # Check to see if WCS is already centered... if self.crpix1 == self.naxis1/2. and self.crpix2 == self.naxis2/2.: # No recentering necessary... return without changing WCS. return # This offset aligns the WCS to the center of the pixel, in accordance # with the 'align=center' option used by 'drizzle'. #_drz_off = -0.5 _drz_off = 0. _cen = (self.naxis1/2.+ _drz_off,self.naxis2/2. + _drz_off) # Compute the RA and Dec for center pixel _cenrd = self.xy2rd(_cen) _cd = N.array([[self.cd11,self.cd12],[self.cd21,self.cd22]],type=N.Float64) _ra0 = DEGTORAD(self.crval1) _dec0 = DEGTORAD(self.crval2) _ra = DEGTORAD(_cenrd[0]) _dec = DEGTORAD(_cenrd[1]) # Set up some terms for use in the final result _dx = self.naxis1/2. - self.crpix1 _dy = self.naxis2/2. - self.crpix2 _dE,_dN = DEGTORAD(N.dot(_cd,(_dx,_dy))) _dE_dN = 1 + N.power(_dE,2) + N.power(_dN,2) _cosdec = N.cos(_dec) _sindec = N.sin(_dec) _cosdec0 = N.cos(_dec0) _sindec0 = N.sin(_dec0) _n1 = N.power(_cosdec,2) + _dE*_dE + _dN*_dN*N.power(_sindec,2) _dra_dE = (_cosdec0 - _dN*_sindec0)/_n1 _dra_dN = _dE*_sindec0 /_n1 _ddec_dE = -_dE*N.tan(_dec) / _dE_dN _ddec_dN = (1/_cosdec) * ((_cosdec0 / N.sqrt(_dE_dN)) - (_dN*N.sin(_dec) / _dE_dN)) # Compute new CD matrix values now... _cd11n = _cosdec * (self.cd11*_dra_dE + self.cd21 * _dra_dN) _cd12n = _cosdec * (self.cd12*_dra_dE + self.cd22 * _dra_dN) _cd21n = self.cd11 * _ddec_dE + self.cd21 * _ddec_dN _cd22n = self.cd12 * _ddec_dE + self.cd22 * _ddec_dN _new_orient = RADTODEG(N.arctan2(_cd12n,_cd22n)) # Update the values now... self.crpix1 = _cen[0] self.crpix2 = _cen[1] self.crval1 = RADTODEG(_ra) self.crval2 = RADTODEG(_dec) # Keep the same plate scale, only change the orientation self.rotateCD(_new_orient) # These would update the CD matrix with the new rotation # ALONG with the new plate scale which we do not want. self.cd11 = _cd11n self.cd12 = _cd12n self.cd21 = _cd21n self.cd22 = _cd22n
python
def recenter(self): """ Reset the reference position values to correspond to the center of the reference frame. Algorithm used here developed by Colin Cox - 27-Jan-2004. """ if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: print 'WCS.recenter() only supported for TAN projections.' raise TypeError # Check to see if WCS is already centered... if self.crpix1 == self.naxis1/2. and self.crpix2 == self.naxis2/2.: # No recentering necessary... return without changing WCS. return # This offset aligns the WCS to the center of the pixel, in accordance # with the 'align=center' option used by 'drizzle'. #_drz_off = -0.5 _drz_off = 0. _cen = (self.naxis1/2.+ _drz_off,self.naxis2/2. + _drz_off) # Compute the RA and Dec for center pixel _cenrd = self.xy2rd(_cen) _cd = N.array([[self.cd11,self.cd12],[self.cd21,self.cd22]],type=N.Float64) _ra0 = DEGTORAD(self.crval1) _dec0 = DEGTORAD(self.crval2) _ra = DEGTORAD(_cenrd[0]) _dec = DEGTORAD(_cenrd[1]) # Set up some terms for use in the final result _dx = self.naxis1/2. - self.crpix1 _dy = self.naxis2/2. - self.crpix2 _dE,_dN = DEGTORAD(N.dot(_cd,(_dx,_dy))) _dE_dN = 1 + N.power(_dE,2) + N.power(_dN,2) _cosdec = N.cos(_dec) _sindec = N.sin(_dec) _cosdec0 = N.cos(_dec0) _sindec0 = N.sin(_dec0) _n1 = N.power(_cosdec,2) + _dE*_dE + _dN*_dN*N.power(_sindec,2) _dra_dE = (_cosdec0 - _dN*_sindec0)/_n1 _dra_dN = _dE*_sindec0 /_n1 _ddec_dE = -_dE*N.tan(_dec) / _dE_dN _ddec_dN = (1/_cosdec) * ((_cosdec0 / N.sqrt(_dE_dN)) - (_dN*N.sin(_dec) / _dE_dN)) # Compute new CD matrix values now... _cd11n = _cosdec * (self.cd11*_dra_dE + self.cd21 * _dra_dN) _cd12n = _cosdec * (self.cd12*_dra_dE + self.cd22 * _dra_dN) _cd21n = self.cd11 * _ddec_dE + self.cd21 * _ddec_dN _cd22n = self.cd12 * _ddec_dE + self.cd22 * _ddec_dN _new_orient = RADTODEG(N.arctan2(_cd12n,_cd22n)) # Update the values now... self.crpix1 = _cen[0] self.crpix2 = _cen[1] self.crval1 = RADTODEG(_ra) self.crval2 = RADTODEG(_dec) # Keep the same plate scale, only change the orientation self.rotateCD(_new_orient) # These would update the CD matrix with the new rotation # ALONG with the new plate scale which we do not want. self.cd11 = _cd11n self.cd12 = _cd12n self.cd21 = _cd21n self.cd22 = _cd22n
[ "def", "recenter", "(", "self", ")", ":", "if", "self", ".", "ctype1", ".", "find", "(", "'TAN'", ")", "<", "0", "or", "self", ".", "ctype2", ".", "find", "(", "'TAN'", ")", "<", "0", ":", "print", "'WCS.recenter() only supported for TAN projections.'", ...
Reset the reference position values to correspond to the center of the reference frame. Algorithm used here developed by Colin Cox - 27-Jan-2004.
[ "Reset", "the", "reference", "position", "values", "to", "correspond", "to", "the", "center", "of", "the", "reference", "frame", ".", "Algorithm", "used", "here", "developed", "by", "Colin", "Cox", "-", "27", "-", "Jan", "-", "2004", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/wcsutil.py#L262-L331
train
47,797
OSSOS/MOP
src/jjk/preproc/wcsutil.py
WCSObject._buildNewKeyname
def _buildNewKeyname(self,key,prepend): """ Builds a new keyword based on original keyword name and a prepend string. """ if len(prepend+key) <= 8: _new_key = prepend+key else: _new_key = str(prepend+key)[:8] return _new_key
python
def _buildNewKeyname(self,key,prepend): """ Builds a new keyword based on original keyword name and a prepend string. """ if len(prepend+key) <= 8: _new_key = prepend+key else: _new_key = str(prepend+key)[:8] return _new_key
[ "def", "_buildNewKeyname", "(", "self", ",", "key", ",", "prepend", ")", ":", "if", "len", "(", "prepend", "+", "key", ")", "<=", "8", ":", "_new_key", "=", "prepend", "+", "key", "else", ":", "_new_key", "=", "str", "(", "prepend", "+", "key", ")"...
Builds a new keyword based on original keyword name and a prepend string.
[ "Builds", "a", "new", "keyword", "based", "on", "original", "keyword", "name", "and", "a", "prepend", "string", "." ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/wcsutil.py#L333-L341
train
47,798
OSSOS/MOP
src/jjk/preproc/scrample.py
ushort
def ushort(filename): """Ushort a the pixels""" import pyfits f=pyfits.open(filename,mode='update') f[0].scale('int16','',bzero=32768) f.flush() f.close()
python
def ushort(filename): """Ushort a the pixels""" import pyfits f=pyfits.open(filename,mode='update') f[0].scale('int16','',bzero=32768) f.flush() f.close()
[ "def", "ushort", "(", "filename", ")", ":", "import", "pyfits", "f", "=", "pyfits", ".", "open", "(", "filename", ",", "mode", "=", "'update'", ")", "f", "[", "0", "]", ".", "scale", "(", "'int16'", ",", "''", ",", "bzero", "=", "32768", ")", "f"...
Ushort a the pixels
[ "Ushort", "a", "the", "pixels" ]
94f91d32ad5ec081d5a1ebd67604a838003465af
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/scrample.py#L268-L274
train
47,799