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 increment_title(title): """ Increments a string that ends in a number """
count = re.search('\d+$', title).group(0) new_title = title[:-(len(count))] + str(int(count)+1) return new_title
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_limit(self, limit): """ Checks if the given limit is valid. A limit must be > 0 to be considered valid. Raises ValueError when the *limit* is not > 0. ...
if limit > 0: self.limit = limit else: raise ValueError("Rule limit must be strictly > 0 ({0} given)" .format(limit)) return self
<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_args(): """ request the arguments for running """
ap = argparse.ArgumentParser(description="Create frames for a movie that can be compiled using ffmpeg") ap.add_argument("start", help="date string as start time") ap.add_argument("end", help="date string as end time") ap.add_argument("step", type=float, help="fraction of a day to step by") ap.add_a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ process the main task """
args = get_args() args.start = date_parser.parse(args.start) args.end = date_parser.parse(args.end) args.step = timedelta(args.step) config = Config(args.config) times = [args.start + i * args.step for i in range(int((args.end - args.start) / args.step))] for i, time in enumerate(times): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overall(): """ The overall grammer for pulling apart the main input files. """
return ZeroOrMore(Grammar.comment) + Dict(ZeroOrMore(Group( Grammar._section + ZeroOrMore(Group(Grammar.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 file(): """ Grammar for files found in the overall input files. """
return ( Optional(Word(alphanums).setResultsName('alias') + Suppress(Literal('.'))) + Suppress(White()) + Word(approved_printables).setResultsName('filename') )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen_to_event_updates(): """Subscribe to events."""
def callback(event): print('Event:', event) client.create_event_subscription(instance='simulator', on_data=callback) sleep(5)
<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_current_scene_node(): """Return the name of the jb_sceneNode, that describes the current scene or None if there is no scene node. :returns: the full name...
c = cmds.namespaceInfo(':', listOnlyDependencyNodes=True, absoluteName=True, dagPath=True) l = cmds.ls(c, type='jb_sceneNode', absoluteName=True) if not l: return else: for n in sorted(l): if not cmds.listConnections("%s.reftrack" % n, d=False): 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 updateSpec(self, *args, **kwargs): """Updates the spectrogram. First argument can be a filename, or a data array. If no arguments are given, clears the spect...
if args[0] is None: self.specPlot.clearImg() elif isinstance(args[0], basestring): self.specPlot.fromFile(*args, **kwargs) else: self.specPlot.updateData(*args,**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 showSpec(self, fname): """Draws the spectrogram if it is currently None"""
if not self.specPlot.hasImg() and fname is not None: self.specPlot.fromFile(fname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateSpiketrace(self, xdata, ydata, plotname=None): """Updates the spike trace :param xdata: index values :type xdata: numpy.ndarray :param ydata: values to...
if plotname is None: plotname = self.responsePlots.keys()[0] if len(ydata.shape) == 1: self.responsePlots[plotname].updateData(axeskey='response', x=xdata, y=ydata) else: self.responsePlots[plotname].addTraces(xdata, ydata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateSignal(self, xdata, ydata, plotname=None): """Updates the trace of the outgoing signal :param xdata: time points of recording :param ydata: brain poten...
if plotname is None: plotname = self.responsePlots.keys()[0] self.responsePlots[plotname].updateData(axeskey='stim', x=xdata, y=ydata)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setXlimits(self, lims): """Sets the X axis limits of the trace plot :param lims: (min, max) of x axis, in same units as data :type lims: (float, float) """
# update all "linked", plots self.specPlot.setXlim(lims) for plot in self.responsePlots.values(): plot.setXlim(lims) # ridiculous... sizes = self.splittersw.sizes() if len(sizes) > 1: if self.badbadbad: sizes[0] +=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 setNreps(self, nreps): """Sets the number of reps before the raster plot resets"""
for plot in self.responsePlots.values(): plot.setNreps(nreps)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def specAutoRange(self): """Auto adjusts the visible range of the spectrogram"""
trace_range = self.responsePlots.values()[0].viewRange()[0] vb = self.specPlot.getViewBox() vb.autoRange(padding=0) self.specPlot.setXlim(trace_range)
<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): """ Save as a FITS file and attempt an upload if designated in the configuration file """
out = Outgest(self.output, self.selection_array.astype('uint8'), self.headers, self.config_path) out.save() out.upload()
<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_exit(self): """ When you click to exit, this function is called, prompts whether to save"""
answer = messagebox.askyesnocancel("Exit", "Do you want to save as you quit the application?") if answer: self.save() self.quit() self.destroy() elif answer is None: pass # the cancel action else: self.quit() self.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 make_gui(self): """ Setups the general structure of the gui, the first function called """
self.option_window = Toplevel() self.option_window.protocol("WM_DELETE_WINDOW", self.on_exit) self.canvas_frame = tk.Frame(self, height=500) self.option_frame = tk.Frame(self.option_window, height=300) self.canvas_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_options_frame(self): """ make the frame that allows for configuration and classification"""
self.tab_frame = ttk.Notebook(self.option_frame, width=800) self.tab_configure = tk.Frame(self.tab_frame) self.tab_classify = tk.Frame(self.tab_frame) self.make_configure_tab() self.make_classify_tab() self.tab_frame.add(self.tab_configure, text="Configure") sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_multicolor(self): """ swap from the multicolor image to the single color image """
# disable the multicolor image for color in ['red', 'green', 'blue']: self.multicolorscales[color].config(state=tk.DISABLED, bg='grey') self.multicolorframes[color].config(bg='grey') self.multicolorlabels[color].config(bg='grey') self.multicolordropdowns[...
<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_button_action(self): """ when update button is clicked, refresh the data preview"""
if self.mode.get() == 3: # threecolor self.configure_threecolor_image() elif self.mode.get() == 1: # singlecolor self.configure_singlecolor_image() else: raise ValueError("mode can only be singlecolor or threecolor") self.imageplot.set_data(self.im...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_configure_tab(self): """ initial set up of configure tab"""
# Setup the choice between single and multicolor modeframe = tk.Frame(self.tab_configure) self.mode = tk.IntVar() singlecolor = tk.Radiobutton(modeframe, text="Single color", variable=self.mode, value=1, command=lambda: self.disable_multicolor()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_classify_tab(self): """ initial set up of classification tab"""
self.pick_frame = tk.Frame(self.tab_classify) self.pick_frame2 = tk.Frame(self.tab_classify) self.solar_class_var = tk.IntVar() self.solar_class_var.set(0) # initialize to unlabeled buttonnum = 0 frame = [self.pick_frame, self.pick_frame2] for text, value in se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_singlecolor(self): """ initial setup of single color options and variables"""
self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme) channel_choices = sorted(list(self.data.keys())) self.singlecolorlabel = tk.Label(self.singlecolorframe, text="single", bg=self.single_color_theme, width=10) self.singlecolorvar = tk.StringVar() sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def undobutton_action(self): """ when undo is clicked, revert the thematic map to the previous state"""
if len(self.history) > 1: old = self.history.pop(-1) self.selection_array = old self.mask.set_data(old) self.fig.canvas.draw_idle()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_class(self): """ "on changing the classification label, update the "draw" text """
self.toolbarcenterframe.config(text="Draw: {}".format(self.config.solar_class_name[self.solar_class_var.get()]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def values(self): """Gets the parameter values :returns: dict of inputs: | *'nfft'*: int -- length, in samples, of FFT chunks | *'window'*: str -- name of window...
self.vals['nfft'] = self.ui.nfftSpnbx.value() self.vals['window'] = str(self.ui.windowCmbx.currentText()).lower() self.vals['overlap'] = self.ui.overlapSpnbx.value() return self.vals
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Parses the command-line args, and calls run. """
parser = argparse.ArgumentParser( description='A pipeline that generates analysis pipelines.') parser.add_argument('input', nargs='?', help='A valid metapipe configuration file.') parser.add_argument('-o', '--output', help='An output destination. If none is pro...
<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(config, max_jobs, output=sys.stdout, job_type='local', report_type='text', shell='/bin/bash', temp='.metapipe', run_now=False): """ Create the metapipe b...
if max_jobs == None: max_jobs = cpu_count() parser = Parser(config) try: command_templates = parser.consume() except ValueError as e: raise SyntaxError('Invalid config file. \n%s' % e) options = '\n'.join(parser.global_options) queue_type = QUEUE_TYPES[report_type] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_submit_job(shell, output, job_type): """ Preps the metapipe main job to be submitted. """
run_cmd = [shell, output] submit_command = Command(alias=PIPELINE_ALIAS, cmds=run_cmd) submit_job = get_job(submit_command, job_type) submit_job.make() return submit_job
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaml(modules_to_register: Iterable[Any] = None, classes_to_register: Iterable[Any] = None) -> ruamel.yaml.YAML: """ Create a YAML object for loading a YAML co...
# Defein a round-trip yaml object for us to work with. This object should be imported by other modules # NOTE: "typ" is a not a typo. It stands for "type" yaml = ruamel.yaml.YAML(typ = "rt") # Register representers and constructors # Numpy yaml.representer.add_representer(np.ndarray, numpy_to_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_classes(yaml: ruamel.yaml.YAML, classes: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register externally defined classes. """
# Validation if classes is None: classes = [] # Register the classes for cls in classes: logger.debug(f"Registering class {cls} with YAML") yaml.register_class(cls) return yaml
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_module_classes(yaml: ruamel.yaml.YAML, modules: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """ Register all classes in the given modules wi...
# Validation if modules is None: modules = [] # Extract the classes from the modules classes_to_register = set() for module in modules: module_classes = [member[1] for member in inspect.getmembers(module, inspect.isclass)] classes_to_register.update(module_classes) # 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 numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]: """ Write a numpy array to YAML. It registers the array under the tag ``!numpy_arr...
return representer.represent_sequence( "!numpy_array", data.tolist() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def numpy_from_yaml(constructor: Constructor, data: ruamel.yaml.nodes.SequenceNode) -> np.ndarray: """ Read an array from YAML to numpy. It reads arrays registere...
# Construct the contained values so that we properly construct int, float, etc. # We just leave this to YAML because it already stores this information. values = [constructor.construct_object(n) for n in data.value] logger.debug(f"{data}, {values}") return np.array(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enum_to_yaml(cls: Type[T_EnumToYAML], representer: Representer, data: T_EnumToYAML) -> ruamel.yaml.nodes.ScalarNode: """ Encodes YAML representation. This is ...
return representer.represent_scalar( f"!{cls.__name__}", f"{str(data)}" )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enum_from_yaml(cls: Type[T_EnumFromYAML], constructor: Constructor, node: ruamel.yaml.nodes.ScalarNode) -> T_EnumFromYAML: """ Decode YAML representation. Thi...
# mypy doesn't like indexing to construct the enumeration. return cls[node.value]
<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_current_ids(self, source=True, meta=True, spectra=True, spectra_annotation=True): """Get the current id for each table in the database Args: source (boo...
# get the cursor for the database connection c = self.c # Get the last uid for the spectra_info table if source: c.execute('SELECT max(id) FROM library_spectra_source') last_id_origin = c.fetchone()[0] if last_id_origin: self.current_i...
<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_libdata(self, line): """Update the library meta data from the current line being parsed Args: line (str): The current line of the of the file being ...
#################################################### # parse MONA Comments line #################################################### # The mona msp files contain a "comments" line that contains lots of other information normally separated # into by "" if re.match('^Comme...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _store_compound_info(self): """Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identif...
other_name_l = [name for name in self.other_names if name != self.compound_info['name']] self.compound_info['other_names'] = ' <#> '.join(other_name_l) if not self.compound_info['inchikey_id']: self._set_inchi_pcc(self.compound_info['pubchem_id'], 'cid', 0) if not self.com...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _store_meta_info(self): """Update the meta dictionary with the current chunk of meta data details """
# In the mass bank msp files, sometimes the precursor_mz is missing but we have the neutral mass and # the precursor_type (e.g. adduct) so we can calculate the precursor_mz if not self.meta_info['precursor_mz'] and self.meta_info['precursor_type'] and \ self.compound_info['exact...
<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_spectra_annotation(self, line): """Parse and store the spectral annotation details """
if re.match('^PK\$NUM_PEAK(.*)', line, re.IGNORECASE): self.start_spectra_annotation = False return saplist = line.split() sarow = ( self.current_id_spectra_annotation, float(saplist[self.spectra_annotation_indexes['m/z']]) if 'm/z' in self.spec...
<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_spectra(self, line): """Parse and store the spectral details """
if line in ['\n', '\r\n', '//\n', '//\r\n', '', '//']: self.start_spectra = False self.current_id_meta += 1 self.collect_meta = True return splist = line.split() if len(splist) > 2 and not self.ignore_additional_spectra_info: additio...
<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_inchi_pcc(self, in_str, pcp_type, elem): """Check pubchem compounds via API for both an inchikey and any available compound details """
if not in_str: return 0 try: pccs = pcp.get_compounds(in_str, pcp_type) except pcp.BadRequestError as e: print(e) return 0 except pcp.TimeoutError as e: print(e) return 0 except pcp.ServerError as 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 _get_other_names(self, line): """Parse and extract any other names that might be recorded for the compound Args: line (str): line of the msp file """
m = re.search(self.compound_regex['other_names'][0], line, re.IGNORECASE) if m: self.other_names.append(m.group(1).strip())
<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_meta_info(self, line): """Parse and extract all meta data by looping through the dictionary of meta_info regexs updates self.meta_info Args: line (str...
if self.mslevel: self.meta_info['ms_level'] = self.mslevel if self.polarity: self.meta_info['polarity'] = self.polarity for k, regexes in six.iteritems(self.meta_regex): for reg in regexes: m = re.search(reg, line, re.IGNORECASE) ...
<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_compound_info(self, line): """Parse and extract all compound data by looping through the dictionary of compound_info regexs updates self.compound_info...
for k, regexes in six.iteritems(self.compound_regex): for reg in regexes: if self.compound_info[k]: continue m = re.search(reg, line, re.IGNORECASE) if m: self.compound_info[k] = m.group(1).strip() self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_data(self, remove_data=False, db_type='sqlite'): """Insert data stored in the current chunk of parsing into the selected database Args: remove_data (b...
if self.update_source: # print "insert ref id" import msp2db self.c.execute( "INSERT INTO library_spectra_source (id, name, parsing_software) VALUES" " ({a}, '{b}', 'msp2db-v{c}')".format(a=self.current_id_origin, b=self.source, c=msp2db.__ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def line(line_def, **kwargs): """Highlights a character in the line"""
def replace(s): return "(%s)" % ansi.aformat(s.group()[1:], attrs=["bold", ]) return ansi.aformat( re.sub('@.?', replace, line_def), **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 try_and_error(*funcs): """Apply multiple validation functions Parameters ``*funcs`` Validation functions to test Returns ------- function"""
def validate(value): exc = None for func in funcs: try: return func(value) except (ValueError, TypeError) as e: exc = e raise exc return validate
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_text(value): """Validate a text formatoption Parameters value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError"""
possible_transform = ['axes', 'fig', 'data'] validate_transform = ValidateInStrings('transform', possible_transform, True) tests = [validate_float, validate_float, validate_str, validate_transform, dict] if isinstance(value, six.string_types): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_none(b): """Validate that None is given Parameters b: {None, 'none'} None or string (the case is ignored) Returns ------- None Raises ------ ValueEr...
if isinstance(b, six.string_types): b = b.lower() if b is None or b == 'none': return None else: raise ValueError('Could not convert "%s" to None' % 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 validate_axiscolor(value): """Validate a dictionary containing axiscolor definitions Parameters value: dict see :attr:`psyplot.plotter.baseplotter.axiscolor`...
validate = try_and_error(validate_none, validate_color) possible_keys = {'right', 'left', 'top', 'bottom'} try: value = dict(value) false_keys = set(value) - possible_keys if false_keys: raise ValueError("Wrong keys (%s)!" % (', '.join(false_keys))) for key, val ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_cbarpos(value): """Validate a colorbar position Parameters value: bool or str A string can be a combination of 'sh|sv|fl|fr|ft|fb|b|r' Returns -----...
patt = 'sh|sv|fl|fr|ft|fb|b|r' if value is True: value = {'b'} elif not value: value = set() elif isinstance(value, six.string_types): for s in re.finditer('[^%s]+' % patt, value): warn("Unknown colorbar position %s!" % s.group(), RuntimeWarning) value = set(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_cmap(val): """Validate a colormap Parameters val: str or :class:`mpl.colors.Colormap` Returns ------- str or :class:`mpl.colors.Colormap` Raises ---...
from matplotlib.colors import Colormap try: return validate_str(val) except ValueError: if not isinstance(val, Colormap): raise ValueError( "Could not find a valid colormap!") return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_cmaps(cmaps): """Validate a dictionary of color lists Parameters cmaps: dict a mapping from a colormap name to a list of colors Raises ------ ValueE...
cmaps = {validate_str(key): validate_colorlist(val) for key, val in cmaps} for key, val in six.iteritems(cmaps): cmaps.setdefault(key + '_r', val[::-1]) return cmaps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_lineplot(value): """Validate the value for the LinePlotter.plot formatoption Parameters value: None, str or list with mixture of both The value to v...
if value is None: return value elif isinstance(value, six.string_types): return six.text_type(value) else: value = list(value) for i, v in enumerate(value): if v is None: pass elif isinstance(v, six.string_types): value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_GpxModel(self, gpx_model, *args, **kwargs): """Render a GPXModel as a single JSON structure."""
result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, gpx_model, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, gpx_model, name, json_name) put_scalar('creator') put_scalar('metada...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Metadata(self, metadata, *args, **kwargs): """Render GPX Metadata as a single JSON structure."""
result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, metadata, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, metadata, name, json_name) put_scalar('name') put_scalar('description'...
<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_default(mode, equation, symbol_names, default, **kwargs): ''' Given a `sympy` equation or equality, along with a list of symbol names, substitute the specified default value for each symbol for which a value is not provided through a keyword argument. For example, consider the following eq...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def z_transfer_functions(): r''' Return a symbolic equality representation of the transfer function of RMS voltage measured by either control board analog feedback circuits. According to the figure below, the transfer function describes the following relationship:: # Hardware V1 # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_option(section, name): """ Wrapper around ConfigParser's ``has_option`` method. """
cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) return cfg.has_option(section, 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 get(section, name): """ Wrapper around ConfigParser's ``get`` method. """
cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) val = cfg.get(section, name) return val.strip("'").strip('"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_key(table_name, objid): """Create an object key for storage."""
key = datastore.Key() path = key.path_element.add() path.kind = table_name path.name = str(objid) return key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_entity(found): """Copy found entity to a dict."""
obj = dict() for prop in found.entity.property: obj[prop.name] = prop.value.string_value return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_rec(table_name, objid): """Generator that yields keyed recs from store."""
req = datastore.LookupRequest() req.key.extend([make_key(table_name, objid)]) for found in datastore.lookup(req).found: yield extract_entity(found)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_by_indexes(table_name, index_name_values=None): """Index reader."""
req = datastore.RunQueryRequest() query = req.query query.kind.add().name = table_name if not index_name_values: index_name_values = [] for name, val in index_name_values: queryFilter = query.filter.property_filter queryFilter.property.name = name queryFilter.opera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_table(table_name): """Mainly for testing."""
to_delete = [ make_key(table_name, rec['id']) for rec in read_by_indexes(table_name, []) ] with DatastoreTransaction() as tx: tx.get_commit_req().mutation.delete.extend(to_delete)
<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_commit_req(self): """Lazy commit request getter."""
if not self.commit_req: self.commit_req = datastore.CommitRequest() self.commit_req.transaction = self.tx return self.commit_req
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(command, stdin=None, stdout=subprocess.PIPE, env=os.environ, cwd=None, shell=False, output_log_level=logging.INFO, sensitive_info=False): """ Better, sm...
if not sensitive_info: logger.debug("calling command: %s" % command) else: logger.debug("calling command with sensitive information") try: args = command if shell else whitespace_smart_split(command) kw = {} if not shell and not which(args[0], cwd=cwd): 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 whitespace_smart_split(command): """ Split a command by whitespace, taking care to not split on whitespace within quotes. ['test', 'this', '"in here"', 'agai...
return_array = [] s = "" in_double_quotes = False escape = False for c in command: if c == '"': if in_double_quotes: if escape: s += c escape = False else: s += c in_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 sync(self): """ execute the steps required to have the feature end with the desired state. """
phase = _get_phase(self._formula_instance) self.logger.info("%s %s..." % (phase.verb.capitalize(), self.feature_name)) message = "...finished %s %s." % (phase.verb, self.feature_name) result = getattr(self, phase.name)() if result or phase in (PHASE.INSTALL, PHASE.REMOVE): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isloaded(self, name): """Checks if given hook module has been loaded Args: name (str): The name of the module to check Returns: bool. The return code:: True...
if name is None: return True if isinstance(name, str): return (name in [x.__module__ for x in self]) if isinstance(name, Iterable): return set(name).issubset([x.__module__ for x in self]) 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 hook(self, function, dependencies=None): """Tries to load a hook Args: function (func): Function that will be called when the event is called Kwargs: depend...
if not isinstance(dependencies, (Iterable, type(None), str)): raise TypeError("Invalid list of dependencies provided!") # Tag the function with its dependencies if not hasattr(function, "__deps__"): function.__deps__ = dependencies # If a module is loaded befor...
<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_from_json(json_str): """ Given a Unified Uploader message, parse the contents and return a MarketOrderList or MarketHistoryList instance. :param str js...
try: message_dict = json.loads(json_str) except ValueError: raise ParseError("Mal-formed JSON input.") upload_keys = message_dict.get('uploadKeys', False) if upload_keys is False: raise ParseError( "uploadKeys does not exist. At minimum, an empty array is required."...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_to_json(order_or_history): """ Given an order or history entry, encode it to JSON and return. :type order_or_history: MarketOrderList or MarketHistory...
if isinstance(order_or_history, MarketOrderList): return orders.encode_to_json(order_or_history) elif isinstance(order_or_history, MarketHistoryList): return history.encode_to_json(order_or_history) else: raise Exception("Must be one of MarketOrderList or MarketHistoryList.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, classifier, threshold, begin=None, end=None): """Adds a new strong classifier with the given threshold to the cascade. **Parameters:** classifier :...
boosted_machine = bob.learn.boosting.BoostedMachine() if begin is None: begin = 0 if end is None: end = len(classifier.weak_machines) for i in range(begin, end): boosted_machine.add_weak_machine(classifier.weak_machines[i], classifier.weights[i]) self.cascade.append(boosted_machine) self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_boosted_machine(self, boosted_machine, classifiers_per_round, classification_thresholds=-5.): """Creates this cascade from the given boosted mach...
indices = list(range(0, len(boosted_machine.weak_machines), classifiers_per_round)) if indices[-1] != len(boosted_machine.weak_machines): indices.append(len(boosted_machine.weak_machines)) self.cascade = [] self.indices = [] for i in range(len(indices)-1): machine = bob.learn.boosting.Boosted...
<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, hdf5): """Saves this cascade into the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for writing "...
# write the cascade to file hdf5.set("Thresholds", self.thresholds) for i in range(len(self.cascade)): hdf5.create_group("Classifier_%d" % (i+1)) hdf5.cd("Classifier_%d" % (i+1)) self.cascade[i].save(hdf5) hdf5.cd("..") hdf5.create_group("FeatureExtractor") hdf5.cd("FeatureE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, hdf5): """Loads this cascade from the given HDF5 file. **Parameters:** ``hdf5`` : :py:class:`bob.io.base.HDF5File` An HDF5 file open for reading "...
# write the cascade to file self.thresholds = hdf5.read("Thresholds") self.cascade = [] for i in range(len(self.thresholds)): hdf5.cd("Classifier_%d" % (i+1)) self.cascade.append(bob.learn.boosting.BoostedMachine(hdf5)) hdf5.cd("..") hdf5.cd("FeatureExtractor") self.extractor ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(ctx, repository, config): """Check commits."""
ctx.obj = Repo(repository=repository, config=config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(obj, commit='HEAD', skip_merge_commits=False): """Check the messages of the commits."""
from ..kwalitee import check_message options = obj.options repository = obj.repository if options.get('colors') is not False: colorama.init(autoreset=True) reset = colorama.Style.RESET_ALL yellow = colorama.Fore.YELLOW green = colorama.Fore.GREEN red = colorama....
<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_obj_subcmds(obj): """Fetch action in callable attributes which and commands Callable must have their attribute 'command' set to True to be recognised by ...
subcmds = [] for label in dir(obj.__class__): if label.startswith("_"): continue if isinstance(getattr(obj.__class__, label, False), property): continue rvalue = getattr(obj, label) if not callable(rvalue) or not is_cmd(rvalue): continue ...
<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_module_resources(mod): """Return probed sub module names from given module"""
path = os.path.dirname(os.path.realpath(mod.__file__)) prefix = kf.basename(mod.__file__, (".py", ".pyc")) if not os.path.exists(mod.__file__): import pkg_resources for resource_name in pkg_resources.resource_listdir(mod.__name__, ''): if resource_name.startswith("%s_" % prefi...
<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_mod_subcmds(mod): """Fetch action in same directory in python module python module loaded are of this form: '%s_*.py' % prefix """
## Look in modules attributes subcmds = get_obj_subcmds(mod) path = os.path.dirname(os.path.realpath(mod.__file__)) if mod.__package__ is None: sys.path.insert(0, os.path.dirname(path)) mod.__package__ = kf.basename(path) for module_name in get_module_resources(mod): try...
<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_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic ...
doc = txt.dedent(obj.__doc__ or "") env = env.copy() ## get a local copy doc = doc.strip() if not re.search(r"^usage:\s*$", doc, flags=re.IGNORECASE | re.MULTILINE): doc += txt.dedent(""" Usage: %(std_usage)s Options: %(std_options)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 get_calling_prototype(acallable): """Returns actual working calling prototype This means that the prototype given can be used directly in the same way by bou...
assert callable(acallable) if inspect.ismethod(acallable) or inspect.isfunction(acallable): args, vargs, vkwargs, defaults = inspect.getargspec(acallable) elif not inspect.isfunction(acallable) and hasattr(acallable, "__call__"): ## a class instance ? which is callable... args, varg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize(self): """ Generate the root directory root if it doesn't already exist """
if not os.path.exists(self.root_dir): os.makedirs(self.root_dir) assert os.path.isdir(self.root_dir), "%s is not a directory! Please move or remove it." % self.root_dir for d in ["bin", "lib", "include"]: target_path = os.path.join(self.root_dir, d) if not os...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finalize(self): """ finalize any open file handles """
if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self): """ Removes the sprinter directory, if it exists """
if self.rc_file: self.rc_file.close() if self.env_file: self.env_file.close() shutil.rmtree(self.root_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symlink_to_bin(self, name, path): """ Symlink an object at path to name in the bin folder. """
self.__symlink_dir("bin", name, path) os.chmod(os.path.join(self.root_dir, "bin", name), os.stat(path).st_mode | stat.S_IXUSR | stat.S_IRUSR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_feature(self, feature_name): """ Remove an feature from the environment root folder. """
self.clear_feature_symlinks(feature_name) if os.path.exists(self.install_directory(feature_name)): self.__remove_path(self.install_directory(feature_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 clear_feature_symlinks(self, feature_name): """ Clear the symlinks for a feature in the symlinked path """
logger.debug("Clearing feature symlinks for %s" % feature_name) feature_path = self.install_directory(feature_name) for d in ('bin', 'lib'): if os.path.exists(os.path.join(self.root_dir, d)): for link in os.listdir(os.path.join(self.root_dir, 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 add_to_env(self, content): """ add content to the env script. """
if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.env_file: self.env_path, self.env_file = self.__get_env_handle(self.root_dir) self.env_file.write(content + '\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 add_to_rc(self, content): """ add content to the rc script. """
if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.rc_file: self.rc_path, self.rc_file = self.__get_rc_handle(self.root_dir) self.rc_file.write(content + '\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 add_to_gui(self, content): """ add content to the gui script. """
if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.gui_file: self.gui_path, self.gui_file = self.__get_gui_handle(self.root_dir) self.gui_file.write(content + '\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 __remove_path(self, path): """ Remove an object """
curpath = os.path.abspath(os.curdir) if not os.path.exists(path): logger.warn("Attempted to remove a non-existent path %s" % path) return try: if os.path.islink(path): os.unlink(path) elif os.path.isdir(path): shuti...
<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_rc_handle(self, root_dir): """ get the filepath and filehandle to the rc file for the environment """
rc_path = os.path.join(root_dir, '.rc') env_path = os.path.join(root_dir, '.env') fh = open(rc_path, "w+") # .rc will always source .env fh.write(source_template % (env_path, env_path)) return (rc_path, fh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __symlink_dir(self, dir_name, name, path): """ Symlink an object at path to name in the dir_name folder. remove it if it already exists. """
target_dir = os.path.join(self.root_dir, dir_name) if not os.path.exists(target_dir): os.makedirs(target_dir) target_path = os.path.join(self.root_dir, dir_name, name) logger.debug("Attempting to symlink %s to %s..." % (path, target_path)) if os.path.exists(target_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_docs(self, options=None): """Return list of previously created documents."""
if options is None: raise ValueError("Please pass in an options dict") default_options = { "page": 1, "per_page": 100, "raise_exception_on_failure": False, "user_credentials": self.api_key, } options = dict(list(default_option...