output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
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 ...
How would you code a function in Python 3 to get a listing matching pattern @param pattern: @return:
You are a Python code analyst, evaluating scripts for potential improvements.
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: ...
Write a Python 3 function that can check if a node in VOSpace has the specified property.
As a python code expert, you are capable of creating scripts from specifications.
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 # prope...
Write a Python 3 function that can retrieve the value associated with a property on a node in VOSpace.
As a Python code composer, you craft elegant and concise scripts.
Sets the value of a property on a node in VOSpace.
Can you generate the documentation for the following Python 3 function 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 ossos_base else property_name # If there is an existing value, clear it first if p...
You are a Python code architect, reviewing and designing scalable and efficient code
Builds the tag for the counter of a given epoch field.
Can you generate the documentation for the following Python 3 function def build_counter_tag(epoch_field, dry_run=False): logger.info("Epoch Field: {}, OBJECT_COUNT {}".format(str(epoch_field), str(OBJECT_COUNT))) tag = epoch_field[1] + "-" + OBJECT_COUNT if dry_run: tag += "-DRYRUN" return ta...
As a Python code translator, you convert algorithms and pseudocode into Python.
Reads the object counter for the given epoch and field.
Can you tell what is the following Python 3 function doing def read_object_counter(node_uri, epoch_field, dry_run=False): return get_property(node_uri, build_counter_tag(epoch_field, dry_run), ossos_base=True)
As a Python code translator, you convert algorithms and pseudocode into Python.
Increment the object counter for a node.
How would you explain what the following Python 3 function does 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 None: new_count = "01" else: new_count = coding.base36encode(co...
You are a Python code analyst, evaluating scripts for potential improvements.
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=expn...
Can you create a Python 3 function that retrieves the mopheader from cache or local file.
You are a Python code architect, reviewing and designing scalable and efficient code
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: ...
How would you implement a function in Python 3 that gets the astrometric header for a given CFHT exposure number.
You are a Python code analyst, evaluating scripts for potential improvements.
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]
How would you implement a function in Python 3 that gets a FITS header from the given URI.
As a Python code composer, you craft elegant and concise scripts.
Retrieve the header for a given expnum and ccd.
Make a summary of the following Python 3 code def get_astheader(expnum, ccd, version='p', prefix=None): 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 ...
You are a Python code generator, capable of creating scripts from specifications.
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, ...
Write a Python 3 script to return the string representation of the tag used to annotate the status in VOSpace.
You are a Python code generator, capable of creating scripts from specifications.
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 r...
Write a Python 3 function for scrambling the image files for the given set of exposures
As a Python code analyst, you investigate and solve complex coding mysteries
def mk_mopheader(expnum, ccd, version, dry_run=False, prefix=""): """Run the OSSOS mopheader script. """ ## confirm destination directory exists. destdir = os.path.dirname( storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='fits')) if not dry_run: storage.mkdir(d...
Write a Python 3 function that can create an OSSOS mopheader file for the specified image.
As a Python code analyst, you investigate and solve complex coding mysteries
Read in the contents of a cands comb file
How would you explain what the following Python 3 function does def read_cands(filename): 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: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def discands(record): """Display the candidates contained in a candidate record list""" import pyraf, pyfits pyraf.iraf.tv() display = pyraf.iraf.tv.display width=128 cands = record['cands'] exps= record['fileId'] ### load some header info from the mophead file headers=...
Implement a Python 3 function for displaying the candidates contained in a candidate record list
As a python code expert, you are capable of creating scripts from specifications.
Query the TAP service for all observations that are part of runid and have calibration observable.
Can you generate the documentation for the following Python 3 function 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.posi...
As a Python code analyst, you investigate and solve complex coding mysteries
Create an ascii log file for easy parsing.
Can you tell what is the following Python 3 function doing def create_ascii_table(observation_table, outfile): logging.info("writing text log to %s" % outfile) stamp = "#\n# Last Updated: " + time.asctime() + "\n#\n" header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % ( "EXPNUM", "OB...
As a python code expert, you are capable of creating scripts from specifications.
Create a sky coverge plot for the given observation table.
Here you have a function in Python 3, explain what it does def create_sky_plot(observation_table, outfile): # camera dimensions width = 0.98 height = 0.98 ax = None if outfile[0:4] == 'vos:': temp_file = tempfile.NamedTemporaryFile(suffix='.pdf') pdf = PdfPages(temp_file.name) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Load the MPC file and store the observations into the observations dictionary.
Here you have a function in Python 3, explain what it does def load_observations((observations, regex, rename), path, filenames): for filename in filenames: if re.search(regex, filename) is None: logging.warning("Skipping {}".format(filename)) continue print os.path.join(pat...
As a Python code analyst, you investigate and solve complex coding mysteries
def writeto(self, filename, **kwargs): """ Write the header to a fits file. :param filename: :return: """ fits.PrimaryHDU(header=self).writeto(filename, output_verify='ignore', **kwargs)
Can you implement a function in Python 3 that writes the header to a FITS file.
As a Python code analyst, you investigate and solve complex coding mysteries
Return the location of the reference coordinate in the pixel frame.
Make a summary of the following Python 3 code def crpix(self): 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.") ...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the MJD of the Megaprime image header.
How would you explain what the following Python 3 function does 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 = self['DATE-OBS'] exce...
As a Python code translator, you convert algorithms and pseudocode into 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.deb...
Can you create a Python 3 function that gets the world coordinate of the reference pixel.
You are a Python code analyst, evaluating scripts for potential improvements.
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, ...
Write a Python 3 script for returning the pixel scale of the detector in arcseconds.
You are a Python code analyst, evaluating scripts for potential improvements.
def iraf_phot(f,x,y,zmag=26.5,apin=10,skyin=15,skywidth=10): """Compute the magnitude of the star at location x/y""" import pyfits import re infits=pyfits.open(f,'update') f=re.sub(r'.fits$','',f) ### Get my python routines from pyraf import iraf from pyraf.irafpar import IrafParLis...
Create a Python 3 function for computing the magnitude of the star at location x y
You are a Python code architect, reviewing and designing scalable and efficient code
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, mi...
Write a Python 3 function that can use the rates program to determine the minimum and maximum bounds for planting
As a python code expert, you are capable of creating scripts from specifications.
Generate a file with object moving at a range of rates and angles
Can you tell what is the following Python 3 function doing def kbo_gen(file,outfile='objects.list',mmin=22.5,mmax=24.5): 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 head...
You are a Python code architect, reviewing and designing scalable and efficient code
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", de...
Write a Python 3 script for commanding line interface for the get_family_info function.
You are a Python code analyst, evaluating scripts for potential improvements.
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_LIS...
Implement a Python 3 function for querying the ssois table for objects of a given family.
You are a Python code architect, reviewing and designing scalable and efficient code
Query the ssois table for images of a given object and return a list of the image names and the exposure times and telescope instrument objects.
Can you tell what is the following Python 3 function doing 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().__contains__('r'): filtertype = 'r.MP9601' # t...
As a python code expert, you are capable of creating scripts from specifications.
Parse the SSOIS query and return a list of dictionaries.
Can you generate a brief explanation for the following Python 3 code 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, exposur...
As a python code expert, you are capable of creating scripts from specifications.
Given two MOPFiles mopfile1 and mopfile2 provide a result file that contains the measured values from real detections and a flag indicating if they are real or false.
Can you generate the documentation for the following Python 3 function def match_mopfiles(mopfile1, mopfile2): 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...
You are a Python code analyst, evaluating scripts for potential improvements.
Given a list of readings compute the magnitudes for all sources in each reading.
Can you tell what is the following Python 3 function doing def measure_mags(measures): import daophot image_downloader = ImageDownloader() observations = {} for measure in measures: for reading in measure: if reading.obs not in observations: observations[reading.obs...
You are a Python code generator, capable of creating scripts from specifications.
def match_planted(fk_candidate_observations, match_filename, bright_limit=BRIGHT_LIMIT, object_planted=OBJECT_PLANTED, minimum_bright_detections=MINIMUM_BRIGHT_DETECTIONS, bright_fraction=MINIMUM_BRIGHT_FRACTION): """ Using the fk_candidate_observations as input get the Object.planted file fro...
Can you create a Python 3 function that matches the Object. planted file with the given fk_candidate_observations.
As a python code expert, you are capable of creating scripts from specifications.
Adds a new item to the end of the collection.
Given the following Python 3 function, write the documentation def append(self, item): if len(self) == 0: # Special case, we make this the current item self.index = 0 self.items.append(item)
As a python code expert, you are capable of creating scripts from specifications.
def make_error(self, message: str, *, error: Exception = None, # ``error_class: Type[Exception]=None`` doesn't work on # Python 3.5.2, but that is exact version ran by Read the # Docs :( More info: http://s...
Write a Python 3 function for creating an error from a message.
You are a Python code analyst, evaluating scripts for potential improvements.
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. ...
Can you implement a function in Python 3 that validates response data and wrap it inside response factory.
You are a Python code analyst, evaluating scripts for potential improvements.
r Validates the request data against the request schema from module.
Given the following Python 3 function, write the documentation def validate_request(self, data: Any, *additional: AnyMapping, merged_class: Type[dict] = dict) -> Any: r"""Validate request data against request schema from module. ...
You are a Python code analyst, evaluating scripts for potential improvements.
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(...
How would you implement a function in Python 3 that converts data to pure dict instance so that it can be used in jsonschema. validate func.
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate data against given schema.
Can you tell what is the following Python 3 function doing def _validate(self, data: Any, schema: AnyMapping) -> Any: try: return self.validate_func(schema, self._pure_data(data)) except self.validation_error_class as err: logger.error( 'Schema validation error', ...
You are a Python code architect, reviewing and designing scalable and efficient code
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: ...
Implement a function in Python 3 to access the cadc certificate server
You are a Python code generator, capable of creating scripts from specifications.
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'): """"Getting the username/password for host from .netrc filie """ if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK): auth=netrc.netrc().authenticators(host) else: auth=False if not auth: sys.st...
Can you create a Python 3 function that gets the username and password for host from. netrc filie
You are a Python code generator, capable of creating scripts from specifications.
Clear the tags for the given expnum and ccd set.
How would you explain what the following Python 3 function does def clear_tags(my_expnum, ops_set, my_ccds, dry_run=True): for ops in ops_set: for fake in ops[0]: for my_program in ops[1]: for version in ops[2]: props = {} for ccd in my_ccds: ...
As a python code expert, you are capable of creating scripts from specifications.
Convert string or other Python object to boolean.
Can you tell what is the following Python 3 function doing def to_bool(value: Any) -> bool: return bool(strtobool(value) if isinstance(value, str) else value)
You are a Python code analyst, evaluating scripts for potential improvements.
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: ...
Can you implement a function in Python 3 that converts given value to int.
As a Python code analyst, you investigate and solve complex coding mysteries
Given a list of results and a list of description sequences return a list of dictionaries
Given the following Python 3 function, write the documentation def mk_dict(results,description): 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
As a Python code analyst, you investigate and solve complex coding mysteries
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(),cfep...
Can you create a Python 3 function that queries the orbit table for the object whose official desingation matches the specified parameter official.
As a Python code composer, you craft elegant and concise scripts.
Query the measure table for all measurements of a particular object.
Can you tell what is the following Python 3 function doing 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.official IS NULL" else: sql+="WHERE o.official LIKE '...
As a python code expert, you are capable of creating scripts from specifications.
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 No...
Can you create a Python 3 function that creates a link that connects to a getData URL
You are a Python code architect, reviewing and designing scalable and efficient code
Create an event in the local cache
Can you tell what is the following Python 3 function doing def create_event(self, event): ev = api.Event.create(self.journal.collection, event) ev.save()
As a Python code translator, you convert algorithms and pseudocode into Python.
def update_event(self, event, uid): """Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated """ ev_for_change = self.calendar.get(uid) ev_for_change.cont...
Implement a Python 3 function for editing event in calendar with uid
You are a Python code analyst, evaluating scripts for potential improvements.
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()
Create a Python 3 function for deleting event and sync calendar
As a Python code composer, you craft elegant and concise scripts.
A class decorator that can be used to configure sane default LMDB persistence settings for a single model
Can you generate a brief explanation for the following Python 3 code def simple_lmdb_settings(path, map_size=1e9, user_supplied_id=False): def decorator(cls): provider = \ ff.UserSpecifiedIdProvider(key='_id') \ if user_supplied_id else ff.UuidProvider() class Settings(ff.P...
As a python code expert, you are capable of creating scripts from specifications.
Decorator that returns a class that persists data in - memory.
Given the following Python 3 function, write the documentation def simple_in_memory_settings(cls): class Settings(ff.PersistenceSettings): id_provider = ff.UuidProvider() key_builder = ff.StringDelimitedKeyBuilder() database = ff.InMemoryDatabase(key_builder=key_builder) class Model(cl...
As a python code expert, you are capable of creating scripts from specifications.
Offset the camera pointing to be centred on a particular CCD.
Can you tell what is the following Python 3 function doing def offset(self, index=0): 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...
You are a Python code generator, capable of creating scripts from specifications.
The center of the camera pointing in sky coordinates
Make a summary of the following Python 3 code def coord(self): if self._coordinate is None: self._coordinate = SkyCoord(self.origin.ra, self.origin.dec + 45 * units.arcsec) return self._coordinate
You are a Python code generator, capable of creating scripts from specifications.
def geometry(self): """Return an array of rectangles that represent the 'ra,dec' corners of the FOV @rtype: list """ if self.coord is None: return None ra = self.coord.ra.degree dec = self.coord.dec.degree ccds = [] for geo in self._geometry...
Can you implement a function in Python 3 that returns an array of rectangles that represent the ra dec corners of the FOV
You are a Python code generator, capable of creating scripts from specifications.
def separation(self, ra, dec): """Compute the separation between self and (ra,dec)""" if self.coord is None: return None return self.coord.separation(SkyCoord(ra, dec, unit=('degree', 'degree')))
Write a Python 3 script for computing the separation between self and ( ra dec )
As a Python code translator, you convert algorithms and pseudocode into Python.
TRIM a CFHT MEGAPRIME frame using the DATASEC keyword
Explain what the following Python 3 code does def trim(hdu): datasec = re.findall(r'(\d+)', hdu.header.get('DATASEC')) l=int(datasec[0])-1 r=int(datasec[1]) b=int(datasec[2])-1 t=int(datasec[3]) if opt.verbose: print "Trimming [%d:%d,%d:%d]" % ( l,r,b,t) hdu....
As a Python code composer, you craft elegant and concise scripts.
Overscan subtracts a CFHT MEGAPRIME frame from the current AMP section and BIAS section keywords.
Can you generate a brief explanation for the following Python 3 code def overscan(hdu): for amp in (['A','B']): AMPKW= 'ASEC'+amp BIASKW= 'BSEC'+amp dsec=re.findall(r'(\d+)', hdu.header.get(AMPKW)) bias=re.findall(r'(\d+)', hdu.header.g...
You are a Python code analyst, evaluating scripts for potential improvements.
Decorator to check if the user owns the required lock.
Make a summary of the following Python 3 code def requires_lock(function): 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...
You are a Python code generator, capable of creating scripts from specifications.
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) ...
Create a Python 3 function to remove all persistence - related files from the directory.
You are a Python code generator, capable of creating scripts from specifications.
set the rcparams to EmulateApJ columnwidth = 245. 26 pts
Given the following Python 3 function, write the documentation 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*inches_per_pt fig_height = fig_width*golden_mean fig_size = [1.5*fig_width, fig_height] para...
You are a Python code analyst, evaluating scripts for potential improvements.
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 ...
Create a Python 3 function to access the cadc certificate server.
As a Python code composer, you craft elegant and concise scripts.
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_...
Create a Python 3 function to give a certfile load a list of groups that user is a member of
As a Python code translator, you convert algorithms and pseudocode into Python.
Test to see if the given userid / password combo is an authenticated member of group.
Here you have a function in Python 3, explain what it does def isMember(userid, password, group): try: certfile = getCert(userid, password) group_url = getGroupsURL(certfile, group) logging.debug("group url: %s" % ( group_url)) con = httplib.HTTPSConnection(_SERVER, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def sky2xypv(ra, dec, crpix1, crpix2, crval1, crval2, dc, pv, nord, maxiter=300): """ Transforms from celestial coordinates to pixel coordinates to taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see xy2sky. ...
Write a Python 3 function that can transform from celestial coordinates to pixel coordinates to taking non-linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe. For the inverse operation see xy2sky. Reference material: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/megapipe/doc...
As a Python code composer, you craft elegant and concise scripts.
This function takes from pixel coordinates to celestial coordinates taking a non - linear distortion into account with the World Coordinate System FITS keywords as used in MegaPipe.
How would you explain what the following Python 3 function does def xy2skypv(x, y, crpix1, crpix2, crval1, crval2, cd, pv, nord): xp = x - crpix1 yp = y - crpix2 # IMPORTANT NOTE: 0-based indexing in Python means indexing for values # in cd and pv will be shifted from in the paper. x_deg = cd[0][0]...
You are a Python code analyst, evaluating scripts for potential improvements.
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 de...
Write a Python 3 script to parse the PV array from an astropy. io. fits. header. Header object.
You are a Python code analyst, evaluating scripts for potential improvements.
Ensure that the vector or vectors have unit norm
Explain what the following Python 3 code does def safe_unit_norm(a): 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 ...
As a Python code translator, you convert algorithms and pseudocode into 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) ...
Can you write a function in Python 3 where it pads an n - dimensional numpy array with zeros along the zero - th dimension with the desired length. Return the unchanged if the length of the array is greater than or equal to the desired length.
As a Python code composer, you craft elegant and concise scripts.
This function pads the array into a window of size windowsize with the given stepsize.
Can you generate the documentation for the following Python 3 function def _wpad(l, windowsize, stepsize): if l <= windowsize: return windowsize nsteps = ((l // stepsize) * stepsize) overlap = (windowsize - stepsize) if overlap: return nsteps + overlap diff = (l - nsteps) left ...
As a Python code composer, you craft elegant and concise scripts.
def windowed(a, windowsize, stepsize=None, dopad=False): """ Parameters a - the input array to restructure into overlapping windows windowsize - the size of each window of samples stepsize - the number of samples to shift the window each step. If not speci...
Write a Python 3 script for returning a new array with the elements of a that are within a given window.
You are a Python code generator, capable of creating scripts from specifications.
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._posit...
Can you write a function in Python 3 where it appends a single item to the array growing the wrapped numpy array if necessary
You are a Python code generator, capable of creating scripts from specifications.
extend the numpy array with multiple items growing the wrapped array if necessary
Make a summary of the following Python 3 code def extend(self, items): 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....
As a python code expert, you are capable of creating scripts from specifications.
def display(self, cutout, use_pixel_coords=False): """ :param cutout: source cutout object to be display :type cutout: source.SourceCutout """ logging.debug("Current display list contains: {}".format(self._displayables_by_cutout.keys())) logging.debug("Looking for {}".for...
Can you implement a function in Python 3 that displays the source cutout into the display list.
You are a Python code architect, reviewing and designing scalable and efficient code
def draw_uncertainty_ellipse(self, cutout): """ Draws an ErrEllipse with the spcified dimensions. Only one ErrEllipse can be drawn and only once (not movable). """ if not self.mark_prediction: return try: colour = cutout.reading.from_input_file a...
How would you implement a function in Python 3 that draws an ErrEllipse with the spcified dimensions.
As a Python code analyst, you investigate and solve complex coding mysteries
Aligns the display center of the given cutout with the source.
Explain what the following Python 3 code does def align(self, cutout, reading, source): if not self.current_displayable: return if not self.current_displayable.aligned: focus_sky_coord = reading.reference_sky_coord #focus_calculator = SingletFocusCalculator(source) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Compute the centroids and magnitudes of a bunch sources on a fits image.
Given the following Python 3 function, write the documentation def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3, maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True): """ Compute the centroids and magnitudes of a bunch sources on fits image. :rtype : astr...
As a Python code composer, you craft elegant and concise scripts.
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))
Implement a Python 3 function for wrapping around phot which only returns the computed magnitude directly.
As a Python code composer, you craft elegant and concise scripts.
def all_blocks(self): status = OrderedDict.fromkeys(parameters.BLOCKS.keys()) status['13AE'] = ['discovery complete', '50', '24.05'] status['13AO'] = ['discovery complete', '36', '24.40'] status['13BL'] = ['discovery complete', '79', '24.48'] status['14BH'] = ['discovery running...
Can you implement a function in Python 3 that returns a dict of all available blocks.
As a Python code translator, you convert algorithms and pseudocode into Python.
Shortcut for safely reading environment var. By default is None.
Make a summary of the following Python 3 code def from_env(key: str, default: T = None) -> Union[str, Optional[T]]: return os.getenv(key, default)
As a Python code analyst, you investigate and solve complex coding mysteries
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 anyon...
How would you implement a function in Python 3 that initializes and return immutable Settings dictionary.
As a Python code composer, you craft elegant and concise scripts.
Injects settings values to given context.
Can you tell what is the following Python 3 function doing 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...
You are a Python code architect, reviewing and designing scalable and efficient code
Iterate over settings values from settings module or dict - like instance.
Make a summary of the following Python 3 code def iter_settings(mixed: Settings) -> Iterator[Tuple[str, Any]]: if isinstance(mixed, types.ModuleType): for attr in dir(mixed): if not is_setting_key(attr): continue yield (attr, getattr(mixed, attr)) else: yi...
As a Python code composer, you craft elegant and concise scripts.
Shortcut helper to configure timezone for backend application.
Here you have a function in Python 3, explain what it does def setup_timezone(timezone: str) -> None: 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_file...
You are a Python code generator, capable of creating scripts from specifications.
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 st...
Implement a Python 3 function for reading through the HISTORY cards in an image header looking for detrend input lines and return the list of input lines.
You are a Python code analyst, evaluating scripts for potential improvements.
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 =...
How would you implement a function in Python 3 that decodes an elixir style file name and returns a dictionary of the content.
You are a Python code generator, capable of creating scripts from specifications.
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') ...
Write a Python 3 function that can create a MEF file called filename.
As a python code expert, you are capable of creating scripts from specifications.
Remove the padding lines that CFHT adds to headers
Make a summary of the following Python 3 code def strip_pad(hdu): 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...
As a Python code translator, you convert algorithms and pseudocode into 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-e...
Can you write a function in Python 3 where it stacks the infiles into a single MEF file.
You are a Python code generator, capable of creating scripts from specifications.
Use get a fits image from the CADC.
Given the following Python 3 function, write the documentation 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" proxy="http://test.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/authProxy/getData" ...
You are a Python code architect, reviewing and designing scalable and efficient code
Opens a FITS format file and returns a tuple of the first N elements.
Can you tell what is the following Python 3 function doing def _open(file,mode='copyonwrite'): 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 o...
As a python code expert, you are capable of creating scripts from specifications.
Search the HISTORY fields of a header looking for the FLIPS processing date.
Can you generate a brief explanation for the following Python 3 code def find_proc_date(header): 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} (.*) - ...
As a python code expert, you are capable of creating scripts from specifications.
Search through header and find the elixir formated string that match the the input type.
Can you generate a brief explanation for the following Python 3 code def find_detrend_keyword(header, type): import re, string value='NULL' #print type for h in header: g = str(h) if ( string.find(g,'.'+type+'.')!= -1 ): result=re.search('[^\s]*\.'+type+'\.[^\s]*\.\d\d\.\d\d'...
As a python code expert, you are capable of creating scripts from specifications.
def _open_fix(file): """Takes in a fits file name, open the file in binary mode and creates an HDU. Will attempt to fix some of the header keywords to match the standard FITS format. """ import pyfits, re, string temp = pyfits.HDUList() hdu = pyfits.PrimaryHDU() hdu._file=open(file,'rb') ...
How would you implement a function in Python 3 that opens a FITS file and create a HDUList with the header keywords.
You are a Python code analyst, evaluating scripts for potential improvements.
Send a query to the SSOS web service looking for available observations using the given track.
Can you tell what is the following Python 3 function doing def query_ssos(self, mpc_observations, lunation_count=None): # we observe ~ a week either side of new moon # but we don't know when in the dark run the discovery happened # so be generous with the search boundaries, add extra 2 weeks ...
As a Python code composer, you craft elegant and concise scripts.
def query_ssos(self, target_name, lunation_count=None): """Send a query to the SSOS web service, looking for available observations using the given track. :param target_name: name of target to query against SSOIS db :param lunation_count: ignored :rtype: SSOSData """ # ...
Can you implement a function in Python 3 that sends a query to the SSOS web service looking for available observations using the given target name.
You are a Python code architect, reviewing and designing scalable and efficient code
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) ex...
Write a Python 3 script to build an astrom. Observation object for a SourceReading object for the given exposure number.
As a Python code translator, you convert algorithms and pseudocode into Python.