text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_map_data(self, data: numpy.ndarray) -> None: """Set the data and mark the canvas item for updating. Data should be an ndarray of shape (256, 3) with typ...
self.__color_map_data = data self.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_params(self): "Parameters used to initialize the class" import inspect a = inspect.getargspec(self.__init__)[0] out = dict() for key in a[1:]: value = getattr(self, "_%s" % key, None) out[key] = value return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def signature(self): "Instance file name" kw = self.get_params() keys = sorted(kw.keys()) l = [] for k in keys: n = k[0] + k[-1] v = kw[k] if k == 'function_set': v = "_".join([x.__name__[0] + x.__n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def population(self): "Class containing the population and all the individuals generated" try: return self._p except AttributeError: self._p = self._population_class(base=self, tournament_size=self._tournament_size, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def random_leaf(self): "Returns a random variable with the associated weight" for i in range(self._number_tries_feasible_ind): var = np.random.randint(self.nvar) v = self._random_leaf(var) if v is None: continue return v raise Runti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stopping_criteria(self): "Test whether the stopping criteria has been achieved." if self.stopping_criteria_tl(): return True if self.generations < np.inf: inds = self.popsize * self.generations flag = inds <= len(self.population.hist) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nclasses(self, v): "Number of classes of v, also sets the labes" if not self.classifier: return 0 if isinstance(v, list): self._labels = np.arange(len(v)) return if not isinstance(v, np.ndarray): v = tonparray(v) self._labels = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, v=None, X=None): """In classification this returns the classes, in regression it is equivalent to the decision function"""
if X is None: X = v v = None m = self.model(v=v) return m.predict(X)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve(application, host='127.0.0.1', port=8080): """Gevent-based WSGI-HTTP server."""
# Instantiate the server with a host/port configuration and our application. WSGIServer((host, int(port)), application).serve_forever()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_subscribers(obj): """ Returns the subscribers for a given object. :param obj: Any object. """
ctype = ContentType.objects.get_for_model(obj) return Subscription.objects.filter(content_type=ctype, object_id=obj.pk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_subscribed(user, obj): """ Returns ``True`` if the user is subscribed to the given object. :param user: A ``User`` instance. :param obj: Any object. """
if not user.is_authenticated(): return False ctype = ContentType.objects.get_for_model(obj) try: Subscription.objects.get( user=user, content_type=ctype, object_id=obj.pk) except Subscription.DoesNotExist: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _promote(self, name, instantiate=True): """Create a new subclass of Context which incorporates instance attributes and new descriptors. This promotes ...
metaclass = type(self.__class__) contents = self.__dict__.copy() cls = metaclass(str(name), (self.__class__, ), contents) if instantiate: return cls() return cls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self,candidates,parameters): """ Run simulation for each candidate This run method will loop through each candidate and run the simulation corresponding ...
traces = [] start_time = time.time() if self.num_parallel_evaluations == 1: for candidate_i in range(len(candidates)): candidate = candidates[candidate_i] sim_var = dict(zip(parameters,candidate)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, context): """Executed prior to processing a request."""
if __debug__: log.debug("Assigning thread local request context.") self.local.context = context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple(application, host='127.0.0.1', port=8080): """Python-standard WSGI-HTTP server for testing purposes. The additional work performed here is to matc...
# Try to be handy as many terminals allow clicking links. print("serving on http://{0}:{1}".format(host, port)) # Bind and launch the server; this is a blocking operation. make_server(host, int(port), application).serve_forever()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iiscgi(application): """A specialized version of the reference WSGI-CGI server to adapt to Microsoft IIS quirks. This is not a production quality interfa...
try: from wsgiref.handlers import IISCGIHandler except ImportError: print("Python 3.2 or newer is required.") if not __debug__: warnings.warn("Interactive debugging and other persistence-based processes will not work.") IISCGIHandler().run(application)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via flup. This web server has many, many options. Pleas...
# Allow either on-disk socket (recommended) or TCP/IP socket use. if not socket: bindAddress = (host, int(port)) else: bindAddress = socket # Bind and start the blocking web server interface. WSGIServer(application, bindAddress=bindAddress, **options).run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_method_kwargs(self): """ Helper method. Returns kwargs needed to filter the correct object. Can also be used to create the correct object. """
method_kwargs = { 'user': self.user, 'content_type': self.ctype, 'object_id': self.content_object.pk, } return method_kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """Adds a subscription for the given user to the given object."""
method_kwargs = self._get_method_kwargs() try: subscription = Subscription.objects.get(**method_kwargs) except Subscription.DoesNotExist: subscription = Subscription.objects.create(**method_kwargs) return subscription
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, context): """Add the usual suspects to the context. This adds `request`, `response`, and `path` to the `RequestContext` instance. """
if __debug__: log.debug("Preparing request context.", extra=dict(request=id(context))) # Bridge in WebOb `Request` and `Response` objects. # Extensions shouldn't rely on these, using `environ` where possible instead. context.request = Request(context.environ) context.response = Response(request=cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, context, consumed, handler, is_endpoint): """Called as dispatch descends into a tier. The base extension uses this to maintain the "cur...
request = context.request if __debug__: log.debug("Handling dispatch event.", extra=dict( request = id(context), consumed = consumed, handler = safe_name(handler), endpoint = is_endpoint )) # The leading path element (leading slash) requires special treatment. if not consume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_none(self, context, result): """Render empty responses."""
context.response.body = b'' del context.response.content_length return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_binary(self, context, result): """Return binary responses unmodified."""
context.response.app_iter = iter((result, )) # This wraps the binary string in a WSGI body iterable. return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_file(self, context, result): """Perform appropriate metadata wrangling for returned open file handles."""
if __debug__: log.debug("Processing file-like object.", extra=dict(request=id(context), result=repr(result))) response = context.response response.conditional_response = True modified = mktime(gmtime(getmtime(result.name))) response.last_modified = datetime.fromtimestamp(modified) ct, ce = gues...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_generator(self, context, result): """Attempt to serve generator responses through stream encoding. This allows for direct use of cinje template...
context.response.encoding = 'utf8' context.response.app_iter = ( (i.encode('utf8') if isinstance(i, unicode) else i) # Stream encode unicode chunks. for i in result if i is not None # Skip None values. ) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve(application, host='127.0.0.1', port=8080): """CherryPy-based WSGI-HTTP server."""
# Instantiate the server with our configuration and application. server = CherryPyWSGIServer((host, int(port)), application, server_name=host) # Try to be handy as many terminals allow clicking links. print("serving on http://{0}:{1}".format(host, port)) # Bind and launch the server; this is a blocking oper...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None): '''Returns the colored string''' if not isinstance(string, str): string = str(string) if rgb is None and ansi is None: raise TerminalColorMapException( 'colorize: must specify one name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_serialization(self, context, result): """Render serialized responses."""
resp = context.response serial = context.serialize match = context.request.accept.best_match(serial.types, default_match=self.default) result = serial[match](result) if isinstance(result, str): result = result.decode('utf-8') resp.charset = 'utf-8' resp.content_type = match resp.text = resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs): """A single IV curve"""
grid = plt_kwargs.pop('grid',True) same_fig = plt_kwargs.pop('same_fig',False) if not len(plt_args): plt_args = ('ko-',) if 'label' not in plt_kwargs: plt_kwargs['label'] = 'Current' if not same_fig: make_iv_curve_fig(a, grid=grid) if type(i) is dict: i = [i[v]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generic_insert_with_folder(folder_name, file_name, template_name, args): """ In general if we need to put a file on a folder, we use this method """
# First we make sure views are a package instead a file if not os.path.isdir( os.path.join( args['django_application_folder'], folder_name ) ): os.mkdir(os.path.join(args['django_application_folder'], folder_name)) codecs.open( os.path.joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve(application, host='127.0.0.1', port=8080, threads=4, **kw): """The recommended development HTTP server. Note that this server performs additional b...
# Bind and start the server; this is a blocking process. serve_(application, host=host, port=int(port), threads=int(threads), **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self): """ Plot the result of the simulation once it's been intialized """
from matplotlib import pyplot as plt if self.already_run: for ref in self.volts.keys(): plt.plot(self.t, self.volts[ref], label=ref) plt.title("Simulation voltage vs time") plt.legend() plt.xlabel("Time [ms]") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def colorize(string, rgb=None, ansi=None, bg=None, ansi_bg=None, fd=1): '''Returns the colored string to print on the terminal. This function detects the terminal type and if it is supported and the output is not going to a pipe or a file, then it will return the colored string, otherwise it will retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutate(self, context, handler, args, kw): """Inspect and potentially mutate the given handler's arguments. The args list and kw dictionary may be free...
def cast(arg, val): if arg not in annotations: return cast = annotations[key] try: val = cast(val) except (ValueError, TypeError) as e: parts = list(e.args) parts[0] = parts[0] + " processing argument '{}'".format(arg) e.args = tuple(parts) raise return val an...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, context, handler, result): """Transform the value returned by the controller endpoint. This extension transforms returned values if th...
handler = handler.__func__ if hasattr(handler, '__func__') else handler annotation = getattr(handler, '__annotations__', {}).get('return', None) if annotation: return (annotation, result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'], prefix="Output: ", env=None): """Execute a command in specific working directory"""
if os.name == 'nt': directory = os.path.normpath(directory) print_comment("Executing: (%s) in directory: %s" % (command, directory), verbose) if env is not None: print_comment("Extra env variables %s" % (env), verbose) try: if os.name == 'nt'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def after(self, context, exc=None): """Executed after dispatch has returned and the response populated, prior to anything being sent to the client."""
duration = context._duration = round((time.time() - context._start_time) * 1000) # Convert to ms. delta = unicode(duration) # Default response augmentation. if self.header: context.response.headers[self.header] = delta if self.log: self.log("Response generated in " + delta + " seconds.", extr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure(self, config): """Prepare the incoming configuration and ensure certain expected values are present. For example, this ensures BaseExtensio...
config = config or dict() # We really need this to be there. if 'extensions' not in config: config['extensions'] = list() if not any(isinstance(ext, BaseExtension) for ext in config['extensions']): # Always make sure the BaseExtension is present since request/response objects are handy. config['ext...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _swap(self): '''Swaps the alignment so that the reference becomes the query and vice-versa. Swaps their names, coordinates etc. The frame is not changed''' self.ref_start, self.qry_start = self.qry_start, self.ref_start self.ref_end, self.qry_end = self.qry_end, self.ref_end self.hit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def qry_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the query sequence''' return pyfastaq.intervals.Interval(min(self.qry_start, self.qry_end), max(self.qry_start, self.qry_end))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ref_coords(self): '''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence''' return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def on_same_strand(self): '''Returns true iff the direction of the alignment is the same in the reference and the query''' return (self.ref_start < self.ref_end) == (self.qry_start < self.qry_end)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reverse_query(self): '''Changes the coordinates as if the query sequence has been reverse complemented''' self.qry_start = self.qry_length - self.qry_start - 1 self.qry_end = self.qry_length - self.qry_end - 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reverse_reference(self): '''Changes the coordinates as if the reference sequence has been reverse complemented''' self.ref_start = self.ref_length - self.ref_start - 1 self.ref_end = self.ref_length - self.ref_end - 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _nucmer_command(self, ref, qry, outprefix): '''Construct the nucmer command''' if self.use_promer: command = 'promer' else: command = 'nucmer' command += ' -p ' + outprefix if self.breaklen is not None: command += ' -b ' + str(self.breakl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _delta_filter_command(self, infile, outfile): '''Construct delta-filter command''' command = 'delta-filter' if self.min_id is not None: command += ' -i ' + str(self.min_id) if self.min_length is not None: command += ' -l ' + str(self.min_length) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _show_coords_command(self, infile, outfile): '''Construct show-coords command''' command = 'show-coords -dTlro' if not self.coords_header: command += ' -H' return command + ' ' + infile + ' > ' + outfile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _write_script(self, script_name, ref, qry, outfile): '''Write commands into a bash script''' f = pyfastaq.utils.open_file_write(script_name) print(self._nucmer_command(ref, qry, 'p'), file=f) print(self._delta_filter_command('p.delta', 'p.delta.filter'), file=f) print(self._s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self): ''' Change to a temp directory Run bash script containing commands Place results in specified output file Clean up temp directory ''' qry = os.path.abspath(self.qry) ref = os.path.abspath(self.ref) outfile = os.path.abspath(self.outf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_indel(self, nucmer_snp): '''Indels are reported over multiple lines, 1 base insertion or deletion per line. This method extends the current variant by 1 base if it's an indel and adjacent to the new SNP and returns True. If the current variant is a SNP, does nothing and returns False''' new_v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request(self, method, url, params=None, headers=None, data=None): """Common handler for all the HTTP requests."""
if not params: params = {} # set default headers if not headers: headers = { 'accept': '*/*' } if method == 'POST' or method == 'PUT': headers.update({'Content-Type': 'application/json'}) try: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a user profile. Defaults to linking to Github prof...
options = options or {} content = content or [] has_explicit_title, title, target = split_explicit_title(text) target = utils.unescape(target).strip() title = utils.unescape(title).strip() config = inliner.document.settings.env.app.config if config.issues_user_uri: ref = config.iss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(doc): """ Parse metadata to obtain list of mustache templates, then load those templates. """
doc.mustache_files = doc.get_metadata('mustache') if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string if not doc.mustache_files: doc.mustache_files = None # switch empty string back to None else: doc.mustache_files = [ doc.mustac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def action(elem, doc): """ Apply combined mustache template to all strings in document. """
if type(elem) == Str and doc.mhash is not None: elem.text = doc.mrenderer.render(elem.text, doc.mhash) return elem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_callback(self, renderer_context): """ Determine the name of the callback to wrap around the json output. """
request = renderer_context.get('request', None) params = request and get_query_params(request) or {} return params.get(self.callback_parameter, self.default_callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders into jsonp, wrapping the json output in a callback function. Clients may set...
renderer_context = renderer_context or {} callback = self.get_callback(renderer_context) json = super(JSONPRenderer, self).render(data, accepted_media_type, renderer_context) return callback.encode(self.charset) + b'(' + json + b');'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_jd(year, week, day): '''Return Julian day count of given ISO year, week, and day''' return day + n_weeks(SUN, gregorian.to_jd(year - 1, 12, 28), week)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def weeks_per_year(year): '''Number of ISO weeks in a year''' # 53 weeks: any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday(gregorian.to_jd(year, 1, 1)) if jan1 == THU or (jan1 == WED and isleap(year)): return 53 else: return 52
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_path(f1, f2): """Parse two input arguments and return two lists of file names"""
import glob # if second argument is missing or is a wild card, point it # to the current directory f2 = f2.strip() if f2 == '' or f2 == '*': f2 = './' # if the first argument is a directory, use all GEIS files if os.path.isdir(f1): f1 = os.path.join(f1, '*.??h') list1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkASN(filename): """ Determine if the filename provided to the function belongs to an association. Parameters filename: string Returns ------- validASN : ...
# Extract the file extn type: extnType = filename[filename.rfind('_')+1:filename.rfind('.')] # Determine if this extn name is valid for an assocation file if isValidAssocExtn(extnType): return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def countinputs(inputlist): """ Determine the number of inputfiles provided by the user and the number of those files that are association tables Parameters inpu...
# Initialize return values numInputs = 0 numASNfiles = 0 # User irafglob to count the number of inputfiles files = irafglob(inputlist, atfile=None) # Use the "len" ufunc to count the number of entries in the list numInputs = len(files) # Loop over the list and see if any of the entr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def summary(logfile, time_format): "show a summary of all projects" def output(summary): width = max([len(p[0]) for p in summary]) + 3 print '\n'.join([ "%s%s%s" % (p[0], ' ' * (width - len(p[0])), colored(minutes_to_txt(p[1]), 'red')) for p in summary]) output(server.summarize(read(logfil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def status(logfile, time_format): "show current status" try: r = read(logfile, time_format)[-1] if r[1][1]: return summary(logfile, time_format) else: print "working on %s" % colored(r[0], attrs=['bold']) print " since %s" % colored( server.date_to_txt(r[1][0], time_format...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stop(logfile, time_format): "stop tracking for the active project" def save_and_output(records): records = server.stop(records) write(records, logfile, time_format) def output(r): print "worked on %s" % colored(r[0], attrs=['bold']) print " from %s" % colored( server.date_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse(logfile, time_format): "parses a stream with text formatted as a Timed logfile and shows a summary" records = [server.record_from_txt(line, only_elapsed=True, time_format=time_format) for line in sys.stdin.readlines()] # TODO: make this code better. def output(summary): width = max([len(p[0]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def projects(logfile, time_format): "prints a newline-separated list of all projects" print '\n'.join(server.list_projects(read(logfile, time_format)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getLTime(): """Returns a formatted string with the current local time."""
_ltime = _time.localtime(_time.time()) tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime) return tlm_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDate(): """Returns a formatted string with the current date."""
_ltime = _time.localtime(_time.time()) date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime) return date_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convertDate(date): """Convert DATE string into a decimal year."""
d, t = date.split('T') return decimal_date(d, timeobs=t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpretDQvalue(input): """ Converts an integer 'input' into its component bit values as a list of power of 2 integers. For example, the bit value 1027 woul...
nbits = 16 # We will only support integer values up to 2**128 for iexp in [16, 32, 64, 128]: # Find out whether the input value is less than 2**iexp if (input // (2 ** iexp)) == 0: # when it finally is, we have identified how many bits can be used to # describe this...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verifyWriteMode(files): """ Checks whether files are writable. It is up to the calling routine to raise an Exception, if desired. This function returns True,...
# Start by insuring that input is a list of filenames, # if only a single filename has been given as input, # convert it to a list with len == 1. if not isinstance(files, list): files = [files] # Keep track of the name of each file which is not writable not_writable = [] writable ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildNewRootname(filename, extn=None, extlist=None): """ Build rootname for a new file. Use 'extn' for new filename if given, does NOT append a suffix/extens...
# Search known suffixes to replace ('_crj.fits',...) _extlist = copy.deepcopy(EXTLIST) # Also, add a default where '_dth.fits' replaces # whatever extension was there ('.fits','.c1h',...) #_extlist.append('.') # Also append any user-specified extensions... if extlist: _extlist += e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildRootname(filename, ext=None): """ Build a new rootname for an existing file and given extension. Any user supplied extensions to use for searching for f...
if filename in ['' ,' ', None]: return None fpath, fname = os.path.split(filename) if ext is not None and '_' in ext[0]: froot = os.path.splitext(fname)[0].split('_')[0] else: froot = fname if fpath in ['', ' ', None]: fpath = os.curdir # Get complete list of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getKeyword(filename, keyword, default=None, handle=None): """ General, write-safe method for returning a keyword value from the header of a IRAF recognized i...
# Insure that there is at least 1 extension specified... if filename.find('[') < 0: filename += '[0]' _fname, _extn = parseFilename(filename) if not handle: # Open image whether it is FITS or GEIS _fimg = openImage(_fname) else: # Use what the user provides, after ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildFITSName(geisname): """Build a new FITS filename for a GEIS input image."""
# User wants to make a FITS copy and update it... _indx = geisname.rfind('.') _fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits' return _fitsname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """
# Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = filename[:_indx] _extn = filename[_indx + 1:-1] else: _fname = filename _extn = None return _fname, _extn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def countExtn(fimg, extname='SCI'): """ Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions. """
closefits = False if isinstance(fimg, string_types): fimg = fits.open(fimg) closefits = True n = 0 for e in fimg: if 'extname' in e.header and e.header['extname'] == extname: n += 1 if closefits: fimg.close() return n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getExtn(fimg, extn=None): """ Returns the PyFITS extension corresponding to extension specified in filename. Defaults to returning the first extension with d...
# If no extension is provided, search for first extension # in FITS file with data associated with it. if extn is None: # Set up default to point to PRIMARY extension. _extn = fimg[0] # then look for first extension with data. for _e in fimg: if _e.data is not N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findFile(input): """Search a directory for full filename with optional path."""
# If no input name is provided, default to returning 'no'(FALSE) if not input: return no # We use 'osfn' here to insure that any IRAF variables are # expanded out before splitting out the path... _fdir, _fname = os.path.split(osfn(input)) if _fdir == '': _fdir = os.curdir ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkFileExists(filename, directory=None): """ Checks to see if file specified exists in current or specified directory. Default is current directory. Return...
if directory is not None: fname = os.path.join(directory,filename) else: fname = filename _exist = os.path.exists(fname) return _exist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyFile(input, output, replace=None): """Copy a file whole from input to output."""
_found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeFile(inlist): """ Utility function for deleting a list of files or a single file. This function will automatically delete both files of a GEIS image, j...
if not isinstance(inlist, string_types): # We do have a list, so delete all filenames in list. # Treat like a list of full filenames _ldir = os.listdir('.') for f in inlist: # Now, check to see if there are wildcards which need to be expanded if f.find('*') >= 0 or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findKeywordExtn(ft, keyword, value=None): """ This function will return the index of the extension in a multi-extension FITS file which contains the desired ...
i = 0 extnum = -1 # Search through all the extensions in the FITS object for chip in ft: hdr = chip.header # Check to make sure the extension has the given keyword if keyword in hdr: if value is not None: # If it does, then does the value match the d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findExtname(fimg, extname, extver=None): """ Returns the list number of the extension corresponding to EXTNAME given. """
i = 0 extnum = None for chip in fimg: hdr = chip.header if 'EXTNAME' in hdr: if hdr['EXTNAME'].strip() == extname.upper(): if extver is None or hdr['EXTVER'] == extver: extnum = i break i += 1 return extnum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rAsciiLine(ifile): """Returns the next non-blank line in an ASCII file."""
_line = ifile.readline().strip() while len(_line) == 0: _line = ifile.readline().strip() return _line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listVars(prefix="", equals="\t= ", **kw): """List IRAF variables."""
keylist = getVarList() if len(keylist) == 0: print('No IRAF variables defined') else: keylist.sort() for word in keylist: print("%s%s%s%s" % (prefix, word, equals, envget(word)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def untranslateName(s): """Undo Python conversion of CL parameter or variable name."""
s = s.replace('DOT', '.') s = s.replace('DOLLAR', '$') # delete 'PY' at start of name components if s[:2] == 'PY': s = s[2:] s = s.replace('.PY', '.') return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def envget(var, default=None): """Get value of IRAF or OS environment variable."""
if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf = None try: if iraf: return iraf.envget(var) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def osfn(filename): """Convert IRAF virtual path name to OS pathname."""
# Try to emulate the CL version closely: # # - expands IRAF virtual file names # - strips blanks around path components # - if no slashes or relative paths, return relative pathname # - otherwise return absolute pathname if filename is None: return filename ename = Expand(file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defvar(varname): """Returns true if CL variable is defined."""
if 'pyraf' in sys.modules: #ONLY if pyraf is already loaded, import iraf into the namespace from pyraf import iraf else: # else set iraf to None so it knows to not use iraf's environment iraf = None if iraf: _irafdef = iraf.envget(varname) else: _irafde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(*args, **kw): """Set IRAF environment variables."""
if len(args) == 0: if len(kw) != 0: # normal case is only keyword,value pairs for keyword, value in kw.items(): keyword = untranslateName(keyword) svalue = str(value) _varDict[keyword] = svalue else: # set with no ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(*args, **kw): """Print value of IRAF or OS environment variables."""
if len(kw): raise TypeError('unexpected keyword argument: %r' % list(kw)) if args: for arg in args: print(envget(arg)) else: # print them all listVars(prefix=" ", equals="=")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unset(*args, **kw): """ Unset IRAF environment variables. This is not a standard IRAF task, but it is obviously useful. It makes the resulting variables unde...
if len(kw) != 0: raise SyntaxError("unset requires a list of variable names") for arg in args: if arg in _varDict: del _varDict[arg]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def legal_date(year, month, day): '''Check if this is a legal date in the Julian calendar''' daysinmonth = month_length(year, month) if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't have a day {}".format(month, day)) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_jd(jd): '''Calculate Julian calendar date from Julian day''' jd += 0.5 z = trunc(jd) a = z b = a + 1524 c = trunc((b - 122.1) / 365.25) d = trunc(365.25 * c) e = trunc((b - d) / 30.6001) if trunc(e < 14): month = e - 1 else: month = e - 13 if trun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delay_1(year): '''Test for delay of start of new year and to avoid''' # Sunday, Wednesday, and Friday as start of the new year. months = trunc(((235 * year) - 234) / 19) parts = 12084 + (13753 * months) day = trunc((months * 29) + parts / 25920) if ((3 * (day + 1)) % 7) < 3: day += ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delay_2(year): '''Check for delay in start of new year due to length of adjacent years''' last = delay_1(year - 1) present = delay_1(year) next_ = delay_1(year + 1) if next_ - present == 356: return 2 elif present - last == 382: return 1 else: return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def month_days(year, month): '''How many days are in a given month of a given year''' if month > 13: raise ValueError("Incorrect month index") # First of all, dispose of fixed-length 29 day months if month in (IYYAR, TAMMUZ, ELUL, TEVETH, VEADAR): return 29 # If it's not a leap yea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_datetime(jdc): '''Return a datetime for the input floating point Julian Day Count''' year, month, day = gregorian.from_jd(jdc) # in jdc: 0.0 = noon, 0.5 = midnight # the 0.5 changes it to 0.0 = midnight, 0.5 = noon frac = (jdc + 0.5) % 1 hours = int(24 * frac) mfrac = frac * 24 - h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dbcon(func): """Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created."""
@wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.dbcon is None: # set up connection self.dbcon = sqlite3.connect(self.db) self.dbcur = self.dbcon.cursor() self.dbcur.execute(SQL_SENSOR_TABLE) self.dbcur.execute(SQL_TMP...