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_argument("--config", help="path to a config file", default="config.json")
return ap.parse_args() |
<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):
make_plot(time, config, args.step) |
<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 of the node or none, if there is no scene node :rtype: str | None :raises: None """ |
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 spectrograms. For other arguments, see: :meth:`SpecWidget.updateData<sparkle.gui.plotting.pyqtgraph_widgets.SpecWidget.updateData>` """ |
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 plot :type ydata: numpy.ndarray """ |
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 potential at time points """ |
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
sizes[1] -=1
else:
sizes[0] -=1
sizes[1] +=1
self.badbadbad = not self.badbadbad
self.splittersw.setSizes(sizes)
self._ignore_range_signal = 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 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.destroy() |
<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.option_frame.pack(side=tk.RIGHT, fill=None, expand=False)
self.make_options_frame()
self.make_canvas_frame()
self.disable_singlecolor() |
<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")
self.tab_frame.add(self.tab_classify, text="Classify")
self.tab_frame.pack(fill=tk.BOTH, expand=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 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[color].config(bg='grey', state=tk.DISABLED)
self.multicolorminscale[color].config(bg='grey', state=tk.DISABLED)
self.multicolormaxscale[color].config(bg='grey', state=tk.DISABLED)
# enable the single color
self.singlecolorscale.config(state=tk.NORMAL, bg=self.single_color_theme)
self.singlecolorframe.config(bg=self.single_color_theme)
self.singlecolorlabel.config(bg=self.single_color_theme)
self.singlecolordropdown.config(bg=self.single_color_theme, state=tk.NORMAL)
self.singlecolorminscale.config(bg=self.single_color_theme, state=tk.NORMAL)
self.singlecolormaxscale.config(bg=self.single_color_theme, state=tk.NORMAL) |
<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.image)
if self.mode.get() == 1: # singlecolor
self.imageplot.set_cmap('gist_gray')
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 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())
multicolor = tk.Radiobutton(modeframe, text="Three color", variable=self.mode,
value=3, command=lambda: self.disable_singlecolor())
self.mode.set(3)
singlecolor.pack(side=tk.LEFT)
multicolor.pack(side=tk.LEFT)
updatebutton = tk.Button(master=modeframe, text="Update",
command=self.update_button_action)
updatebutton.pack(side=tk.RIGHT)
modeframe.grid(row=0, column=0)
self.setup_multicolor()
self.setup_singlecolor() |
<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 self.config.solar_classes:
b = tk.Radiobutton(frame[buttonnum % 2], text=text,
variable=self.solar_class_var,
value=value, background=self.config.solar_colors[text],
indicatoron=0, width=50, height=2, command=self.change_class)
b.pack(fill=tk.BOTH, expand=1)
buttonnum += 1
self.pick_frame.grid(row=0, column=0, rowspan=5, sticky=tk.W + tk.E + tk.N + tk.S)
self.pick_frame2.grid(row=0, column=1, rowspan=5, sticky=tk.W + tk.E + tk.N + tk.S)
undobutton = tk.Button(master=self.tab_classify, text="Undo",
command=self.undobutton_action)
undobutton.grid(row=6, column=0, columnspan=2, sticky=tk.W + tk.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 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()
self.singlecolorpower = tk.DoubleVar()
self.singlecolormin = tk.DoubleVar()
self.singlecolormax = tk.DoubleVar()
self.singlecolordropdown = tk.OptionMenu(self.singlecolorframe, self.singlecolorvar, *channel_choices)
self.singlecolorscale = tk.Scale(self.singlecolorframe, variable=self.singlecolorpower,
orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_power_min'],
bg=self.single_color_theme,
to_=self.config.ranges['single_color_power_max'],
resolution=self.config.ranges['single_color_power_resolution'],
length=200)
self.singlecolorminscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormin,
orient=tk.HORIZONTAL, from_=0,
bg=self.single_color_theme,
to_=self.config.ranges['single_color_vmin'],
resolution=self.config.ranges['single_color_vresolution'], length=200)
self.singlecolormaxscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormax,
orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_vmax'],
bg=self.single_color_theme,
to_=100, resolution=self.config.ranges['single_color_vresolution'],
length=200)
self.singlecolorvar.set(self.config.products_map[self.config.default['single']])
self.singlecolorpower.set(self.config.default['single_power'])
self.singlecolormin.set(0)
self.singlecolormax.set(100)
self.singlecolordropdown.config(bg=self.single_color_theme, width=10)
self.singlecolorlabel.pack(side=tk.LEFT)
self.singlecolorscale.pack(side=tk.RIGHT)
self.singlecolormaxscale.pack(side=tk.RIGHT)
self.singlecolorminscale.pack(side=tk.RIGHT)
self.singlecolordropdown.pack()
self.singlecolorframe.grid(row=4, columnspan=5, rowspan=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 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 to apply to FFT chunks | *'overlap'*: float -- percent overlap of windows """ |
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 provided, the '
'results will be printed to stdout.',
default=sys.stdout)
parser.add_argument('-t', '--temp',
help='A desired metapipe binary file. This is used to store '
'temp data between generation and execution. '
'(Default: "%(default)s")', default='.metapipe')
parser.add_argument('-s', '--shell',
help='The path to the shell to be used when executing the '
'pipeline. (Default: "%(default)s)"',
default='/bin/bash')
parser.add_argument('-r', '--run',
help='Run the pipeline as soon as it\'s ready.',
action='store_true')
parser.add_argument('-n', '--name',
help='A name for the pipeline.',
default='')
parser.add_argument('-j', '--job-type',
help='The destination for calculations (i.e. local, a PBS '
'queue on a cluster, etc).\nOptions: {}. '
'(Default: "%(default)s)"'.format(JOB_TYPES.keys()),
default='local')
parser.add_argument('-p', '--max-jobs',
help='The maximum number of concurrent jobs allowed. '
'Defaults to maximum available cores.',
default=None)
parser.add_argument('--report-type',
help='The output report type. By default metapipe will '
'print updates to the console. \nOptions: {}. '
'(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()),
default='text')
parser.add_argument('-v','--version',
help='Displays the current version of the application.',
action='store_true')
args = parser.parse_args()
if args.version:
print('Version: {}'.format(__version__))
sys.exit(0)
try:
with open(args.input) as f:
config = f.read()
except IOError:
print('No valid config file found.')
return -1
run(config, args.max_jobs, args.output, args.job_type, args.report_type,
args.shell, args.temp, args.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 run(config, max_jobs, output=sys.stdout, job_type='local', report_type='text', shell='/bin/bash', temp='.metapipe', run_now=False):
""" Create the metapipe based on the provided input. """ |
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]
pipeline = Runtime(command_templates,queue_type,JOB_TYPES,job_type,max_jobs)
template = env.get_template('output_script.tmpl.sh')
with open(temp, 'wb') as f:
pickle.dump(pipeline, f, 2)
script = template.render(shell=shell,
temp=os.path.abspath(temp), options=options)
if run_now:
output = output if output != sys.stdout else PIPELINE_ALIAS
submit_job = make_submit_job(shell, output, job_type)
submit_job.submit()
try:
f = open(output, 'w')
output = f
except TypeError:
pass
output.write(script)
f.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 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 configuration. Args: modules_to_register: Modules containing classes to be registered with the YAML object. Default: None. classes_to_register: Classes to be registered with the YAML object. Default: None. Returns: A newly creating YAML object, configured as apporpirate. """ |
# 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_yaml)
yaml.constructor.add_constructor("!numpy_array", numpy_from_yaml)
# Register external classes
yaml = register_module_classes(yaml = yaml, modules = modules_to_register)
yaml = register_classes(yaml = yaml, classes = classes_to_register)
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_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 with the YAML object. This is a simple helper function. """ |
# 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)
# Register the extracted classes
return register_classes(yaml = yaml, classes = classes_to_register) |
<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_array``. Use with: .. code-block:: python Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ |
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 registered under the tag ``!numpy_array``. Use with: .. code-block:: python Note: We cannot use ``yaml.register_class`` because it won't register the proper type. (It would register the type of the class, rather than of `numpy.ndarray`). Instead, we use the above approach to register this method explicitly with the representer. """ |
# 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 a mixin method for writing enum values to YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. This method writes whatever is used in the string representation of the YAML value. Usually, this will be the unique name of the enumeration value. If the name is used, the corresponding ``EnumFromYAML`` mixin can be used to recreate the value. If the name isn't used, more care may be necessary, so a ``from_yaml`` method for that particular enumeration may be necessary. Note: This method assumes that the name of the enumeration value should be stored as a scalar node. Args: representer: Representation from YAML. data: Enumeration value to be encoded. Returns: Scalar representation of the name of the enumeration value. """ |
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. This is a mixin method for reading enum values from YAML. It needs to be added to the enum as a classmethod. See the module docstring for further information on this approach and how to implement it. Note: This method assumes that the name of the enumeration value was stored as a scalar node. Args: constructor: Constructor from the YAML object. node: Scalar node extracted from the YAML being read. Returns: The constructed YAML value from the name of the enumerated value. """ |
# 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 (boolean):
get the id for the table "library_spectra_source" will update self.current_id_origin meta (boolean):
get the id for the table "library_spectra_meta" will update self.current_id_meta spectra (boolean):
get the id for the table "library_spectra" will update self.current_id_spectra spectra_annotation (boolean):
get the id for the table "library_spectra_annotation" will update self.current_id_spectra_annotation """ |
# 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_id_origin = last_id_origin + 1
else:
self.current_id_origin = 1
if meta:
c.execute('SELECT max(id) FROM library_spectra_meta')
last_id_meta = c.fetchone()[0]
if last_id_meta:
self.current_id_meta = last_id_meta + 1
else:
self.current_id_meta = 1
if spectra:
c.execute('SELECT max(id) FROM library_spectra')
last_id_spectra = c.fetchone()[0]
if last_id_spectra:
self.current_id_spectra = last_id_spectra + 1
else:
self.current_id_spectra = 1
if spectra_annotation:
c.execute('SELECT max(id) FROM library_spectra_annotation')
last_id_spectra_annotation = c.fetchone()[0]
if last_id_spectra_annotation:
self.current_id_spectra_annotation = last_id_spectra_annotation + 1
else:
self.current_id_spectra_annotation = 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 _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 parsed """ |
####################################################
# 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('^Comment.*$', line, re.IGNORECASE):
comments = re.findall('"([^"]*)"', line)
for c in comments:
self._parse_meta_info(c)
self._parse_compound_info(c)
####################################################
# parse meta and compound info lines
####################################################
# check the current line for both general meta data
# and compound information
self._parse_meta_info(line)
self._parse_compound_info(line)
####################################################
# End of meta data
####################################################
# Most MSP files have the a standard line of text before the spectra information begins. Here we check
# for this line and store the relevant details for the compound and meta information to be ready for insertion
# into the database
if self.collect_meta and (re.match('^Num Peaks(.*)$', line, re.IGNORECASE) or re.match('^PK\$PEAK:(.*)', line,
re.IGNORECASE) or re.match('^PK\$ANNOTATION(.*)', line, re.IGNORECASE)):
self._store_compound_info()
self._store_meta_info()
# Reset the temp meta and compound information
self.meta_info = get_blank_dict(self.meta_regex)
self.compound_info = get_blank_dict(self.compound_regex)
self.other_names = []
self.collect_meta = False
# ignore additional information in the 3rd column if using the MassBank spectra schema
if re.match('^PK\$PEAK: m/z int\. rel\.int\.$', line, re.IGNORECASE):
self.ignore_additional_spectra_info = True
# Check if annnotation or spectra is to be in the next lines to be parsed
if re.match('^Num Peaks(.*)$', line, re.IGNORECASE) or re.match('^PK\$PEAK:(.*)', line, re.IGNORECASE):
self.start_spectra = True
return
elif re.match('^PK\$ANNOTATION(.*)', line, re.IGNORECASE):
self.start_spectra_annotation = True
match = re.match('^PK\$ANNOTATION:(.*)', line, re.IGNORECASE)
columns = match.group(1)
cl = columns.split()
self.spectra_annotation_indexes = {i: cl.index(i) for i in cl}
return
####################################################
# Process annotation details
####################################################
# e.g. molecular formula for each peak in the spectra
if self.start_spectra_annotation:
self._parse_spectra_annotation(line)
####################################################
# Process spectra
####################################################
if self.start_spectra:
self._parse_spectra(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 _store_compound_info(self):
"""Update the compound_info dictionary with the current chunk of compound details Note that we use the inchikey as unique identifier. If we can't find an appropiate inchikey we just use a random string (uuid4) suffixed with UNKNOWN """ |
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.compound_info['inchikey_id']:
self._set_inchi_pcc(self.compound_info['smiles'], 'smiles', 0)
if not self.compound_info['inchikey_id']:
self._set_inchi_pcc(self.compound_info['name'], 'name', 0)
if not self.compound_info['inchikey_id']:
print('WARNING, cant get inchi key for ', self.compound_info)
print(self.meta_info)
print('#########################')
self.compound_info['inchikey_id'] = 'UNKNOWN_' + str(uuid.uuid4())
if not self.compound_info['pubchem_id'] and self.compound_info['inchikey_id']:
self._set_inchi_pcc(self.compound_info['inchikey_id'], 'inchikey', 0)
if not self.compound_info['name']:
self.compound_info['name'] = 'unknown name'
if not self.compound_info['inchikey_id'] in self.compound_ids:
self.compound_info_all.append(tuple(self.compound_info.values()) + (
str(datetime.datetime.now()),
str(datetime.datetime.now()),
))
self.compound_ids.append(self.compound_info['inchikey_id']) |
<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_mass']:
self.meta_info['precursor_mz'] = get_precursor_mz(float(self.compound_info['exact_mass']),
self.meta_info['precursor_type'])
if not self.meta_info['polarity']:
# have to do special check for polarity (as sometimes gets missed)
m = re.search('^\[.*\](\-|\+)', self.meta_info['precursor_type'], re.IGNORECASE)
if m:
polarity = m.group(1).strip()
if polarity == '+':
self.meta_info['polarity'] = 'positive'
elif polarity == '-':
self.meta_info['polarity'] = 'negative'
if not self.meta_info['accession']:
self.meta_info['accession'] = 'unknown accession'
self.meta_info_all.append(
(str(self.current_id_meta),) +
tuple(self.meta_info.values()) +
(str(self.current_id_origin), self.compound_info['inchikey_id'],)
) |
<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.spectra_annotation_indexes else None,
saplist[self.spectra_annotation_indexes[
'tentative_formula']] if 'tentative_formula' in self.spectra_annotation_indexes else None,
float(saplist[self.spectra_annotation_indexes[
'mass_error(ppm)']]) if 'mass_error(ppm)' in self.spectra_annotation_indexes else None,
self.current_id_meta)
self.spectra_annotation_all.append(sarow)
self.current_id_spectra_annotation += 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 _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:
additional_info = ''.join(map(str, splist[2:len(splist)]))
else:
additional_info = ''
srow = (
self.current_id_spectra, float(splist[0]), float(splist[1]), additional_info,
self.current_id_meta)
self.spectra_all.append(srow)
self.current_id_spectra += 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 _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:
print(e)
return 0
except URLError as e:
print(e)
return 0
except BadStatusLine as e:
print(e)
return 0
if pccs:
pcc = pccs[elem]
self.compound_info['inchikey_id'] = pcc.inchikey
self.compound_info['pubchem_id'] = pcc.cid
self.compound_info['molecular_formula'] = pcc.molecular_formula
self.compound_info['molecular_weight'] = pcc.molecular_weight
self.compound_info['exact_mass'] = pcc.exact_mass
self.compound_info['smiles'] = pcc.canonical_smiles
if len(pccs) > 1:
print('WARNING, multiple compounds for ', self.compound_info) |
<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):
line of the msp file """ |
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)
if m:
self.meta_info[k] = 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_compound_info(self, line):
"""Parse and extract all compound data by looping through the dictionary of compound_info regexs updates self.compound_info Args: line (str):
line of the msp file """ |
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._get_other_names(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 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 (boolean):
Remove the data stored within the LibraryData object for the current chunk of processing db_type (str):
The type of database to submit to either 'sqlite', 'mysql' or 'django_mysql' [default sqlite] """ |
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.__version__))
self.conn.commit()
if self.compound_info_all:
self.compound_info_all = _make_sql_compatible(self.compound_info_all)
cn = ', '.join(self.compound_info.keys()) + ',created_at,updated_at'
insert_query_m(self.compound_info_all, columns=cn, conn=self.conn, table='metab_compound',
db_type=db_type)
self.meta_info_all = _make_sql_compatible(self.meta_info_all)
cn = 'id,' + ', '.join(self.meta_info.keys()) + ',library_spectra_source_id, inchikey_id'
insert_query_m(self.meta_info_all, columns=cn, conn=self.conn, table='library_spectra_meta',
db_type=db_type)
cn = "id, mz, i, other, library_spectra_meta_id"
insert_query_m(self.spectra_all, columns=cn, conn=self.conn, table='library_spectra', db_type=db_type)
if self.spectra_annotation_all:
cn = "id, mz, tentative_formula, mass_error, library_spectra_meta_id"
insert_query_m(self.spectra_annotation_all, columns=cn, conn=self.conn,
table='library_spectra_annotation', db_type=db_type)
# self.conn.close()
if remove_data:
self.meta_info_all = []
self.spectra_all = []
self.spectra_annotation_all = []
self.compound_info_all = []
self._get_current_ids(source=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 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):
xpos, ypos = rcParams['texts.default_position']
return [(xpos, ypos, value, 'axes', {'ha': 'right'})]
elif isinstance(value, tuple):
value = [value]
try:
value = list(value)[:]
except TypeError:
raise ValueError("Value must be string or list of tuples!")
for i, val in enumerate(value):
try:
val = tuple(val)
except TypeError:
raise ValueError(
"Text must be an iterable of the form "
"(x, y, s[, trans, params])!")
if len(val) < 3:
raise ValueError(
"Text tuple must at least be like [x, y, s], with floats x, "
"y and string s!")
elif len(val) == 3 or isinstance(val[3], dict):
val = list(val)
val.insert(3, 'data')
if len(val) == 4:
val += [{}]
val = tuple(val)
if len(val) > 5:
raise ValueError(
"Text tuple must not be longer then length 5. It can be "
"like (x, y, s[, trans, params])!")
value[i] = (validate(x) for validate, x in zip(tests, val))
return 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 validate_none(b):
"""Validate that None is given Parameters b: {None, 'none'} None or string (the case is ignored) Returns ------- None Raises ------ ValueError""" |
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` Returns ------- dict Raises ------ ValueError""" |
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 in value.items():
value[key] = validate(val)
except:
value = dict(zip(possible_keys, repeat(validate(value))))
return 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 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 ------- list list of strings with possible colorbar positions Raises ------ ValueError""" |
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(re.findall(patt, value))
else:
value = validate_stringset(value)
for s in (s for s in value
if not re.match(patt, s)):
warn("Unknown colorbar position %s!" % s)
value.remove(s)
return 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 validate_cmap(val):
"""Validate a colormap Parameters val: str or :class:`mpl.colors.Colormap` Returns ------- str or :class:`mpl.colors.Colormap` Raises ------ ValueError""" |
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 ------ ValueError If one of the values in `cmaps` is not a color list Notes ----- For all items (listname, list) in `cmaps`, the reversed list is automatically inserted with the ``listname + '_r'`` key.""" |
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 validate""" |
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[i] = six.text_type(v)
else:
raise ValueError('Expected None or string, found %s' % (v, ))
return 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('metadata')
put_list('waypoints')
put_list('routes')
put_list('tracks')
put_list('extensions')
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 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')
put_scalar('author')
put_scalar('copyright')
put_list('links')
put_scalar('time')
put_scalar('keywords')
put_scalar('bounds')
put_list('extensions')
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 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 equality:
>>> sp.pprint(H)
V₂ Z₂
── = ──
V₁ Z₁
Let us substitute a default value of 1 for terms Z1 and Z2:
>>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1))
V₂
── = 1
V₁
Now, let us specify a default value of 1 for terms Z1 and Z2, but provide
an overriding value for Z1:
>>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4))
V₂
── = 1/4
V₁
Note that keyword arguments for terms not specified in the list of symbol
names are ignored:
>>> sp.pprint(subs_default(H, ['Z1', 'Z2'], 1, Z1=4, Q=7))
V₂
── = 1/4
V₁
'''
if mode == 'subs':
swap_f = _subs
default_swap_f = _subs
elif mode == 'limit':
swap_f = _limit
default_swap_f = _subs
elif mode == 'limit_default':
swap_f = _subs
default_swap_f = _limit
else:
raise ValueError('''Unsupported mode. `mode` must be one of: '''
'''('subs', 'limit').''')
result = equation
for s in symbol_names:
if s in kwargs:
if isinstance(kwargs[s], Iterable):
continue
else:
result = swap_f(result, s, kwargs[s])
else:
result = default_swap_f(result, s, default)
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 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 # # Hardware V2 #
V₂ V₁ V₂ Z₁
── = ─────── ── = ──
Z₂ Z₁ + Z₂ V₁ Z₂
where $V_{1}$ denotes the high-voltage actuation signal from the amplifier
output and $V_{2}$ denotes the signal sufficiently attenuated to fall
within the measurable input range of the analog-to-digital converter
*(approx. 5V)*. The feedback circuits for control board **hardware version
1** and **hardware version 2** are shown below.
.. code-block:: none
# Hardware V1 # # Hardware V2 #
V_1 @ frequency V_1 @ frequency
┯ ┯
┌─┴─┐ ┌─┴─┐ ┌───┐
│Z_1│ │Z_1│ ┌─┤Z_2├─┐
└─┬─┘ └─┬─┘ │ └───┘ │
├───⊸ V_2 │ │ │╲ ├───⊸ V_2
┌─┴─┐ └────┴──│-╲__│
│Z_2│ ┌──│+╱
└─┬─┘ │ │╱
═╧═ │
¯ ═╧═
¯
Notes
-----
- The symbolic equality can be solved for any symbol, _e.g.,_ $V_{1}$ or
$V_{2}$.
- A symbolically solved representation can be converted to a Python function
using `sympy.utilities.lambdify.lambdify`_, to compute results for
specific values of the remaining parameters.
.. _`sympy.utilities.lambdify.lambdify`: http://docs.sympy.org/dev/modules/utilities/lambdify.html
'''
# Define transfer function as a symbolic equality using SymPy.
V1, V2, Z1, Z2 = sp.symbols('V1 V2 Z1 Z2')
xfer_funcs = pd.Series([sp.Eq(V2 / Z2, V1 / (Z1 + Z2)),
sp.Eq(V2 / V1, Z2 / Z1)],
# Index by hardware version.
index=[1, 2])
xfer_funcs.index.name = 'Hardware version'
return xfer_funcs |
<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.operator = datastore.PropertyFilter.EQUAL
queryFilter.value.string_value = str(val)
loop_its = 0
have_more = True
while have_more:
resp = datastore.run_query(req)
found_something = False
for found in resp.batch.entity_result:
yield extract_entity(found)
found_something = True
if not found_something:
# This is a guard against bugs or excessive looping - as long we
# can keep yielding records we'll continue to execute
loop_its += 1
if loop_its > 5:
raise ValueError("Exceeded the excessive query threshold")
if resp.batch.more_results != datastore.QueryResultBatch.NOT_FINISHED:
have_more = False
else:
have_more = True
end_cursor = resp.batch.end_cursor
query.start_cursor.CopyFrom(end_cursor) |
<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, smarter call logic """ |
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):
raise CommandMissingException(args[0])
if shell:
kw['shell'] = True
process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=stdout,
stderr=subprocess.STDOUT, env=env, cwd=cwd,
**kw)
output = process.communicate(input=stdin)[0]
if output is not None:
try:
logger.log(output_log_level, output.decode('utf-8'))
except UnicodeDecodeError:
pass
return (process.returncode, output)
except OSError:
e = sys.exc_info()[1]
if not sensitive_info:
logger.exception("Error running command: %s" % command)
logger.error("Root directory: %s" % cwd)
if stdin:
logger.error("stdin: %s" % stdin)
raise 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 whitespace_smart_split(command):
""" Split a command by whitespace, taking care to not split on whitespace within quotes. ['test', 'this', '"in here"', 'again'] """ |
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_double_quotes = False
else:
in_double_quotes = True
s += c
else:
if in_double_quotes:
if c == '\\':
escape = True
s += c
else:
escape = False
s += c
else:
if c == ' ':
return_array.append(s)
s = ""
else:
s += c
if s != "":
return_array.append(s)
return return_array |
<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):
self.logger.info(message)
else:
self.logger.debug(message)
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 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 -- Loaded False -- Not Loaded """ |
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: dependencies (str):
String or Iterable with modules whose hooks should be called before this one Raises: :class:TypeError Note that the dependencies are module-wide, that means that if `parent.foo` and `parent.bar` are both subscribed to `example` event and `child` enumerates `parent` as dependcy, **both** `foo` and `bar` must be called in order for the dependcy to get resolved. """ |
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 before all its dependencies are loaded, put
# it in _later list and don't load yet
if self.isloaded(function.__deps__):
self.append(function)
else:
self._later.append(function)
# After each module load, retry to resolve dependencies
for ext in self._later:
if self.isloaded(ext.__deps__):
self._later.remove(ext)
self.hook(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 parse_from_json(json_str):
""" Given a Unified Uploader message, parse the contents and return a MarketOrderList or MarketHistoryList instance. :param str json_str: A Unified Uploader message as a JSON string. :rtype: MarketOrderList or MarketHistoryList :raises: MalformedUploadError when invalid JSON is passed in. """ |
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."
)
elif not isinstance(upload_keys, list):
raise ParseError(
"uploadKeys must be an array object."
)
upload_type = message_dict['resultType']
try:
if upload_type == 'orders':
return orders.parse_from_dict(message_dict)
elif upload_type == 'history':
return history.parse_from_dict(message_dict)
else:
raise ParseError(
'Unified message has unknown upload_type: %s' % upload_type)
except TypeError as exc:
# MarketOrder and HistoryEntry both raise TypeError exceptions if
# invalid input is encountered.
raise ParseError(exc.message) |
<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 MarketHistoryList :param order_or_history: A MarketOrderList or MarketHistoryList instance to encode to JSON. :rtype: str :return: The encoded JSON string. """ |
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 : :py:class:`bob.learn.boosting.BoostedMachine` A strong classifier to add ``threshold`` : float The classification threshold for this cascade step ``begin``, ``end`` : int or ``None`` If specified, only the weak machines with the indices ``range(begin,end)`` will be added. """ |
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.thresholds.append(threshold)
self._indices() |
<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 machine, by simply splitting off strong classifiers that have classifiers_per_round weak classifiers. **Parameters:** ``boosted_machine`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier to split into a regular cascade. ``classifiers_per_round`` : int The number of classifiers that each cascade step should contain. ``classification_threshold`` : float A single threshold that will be applied in all rounds of the cascade. """ |
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.BoostedMachine()
for index in range(indices[i], indices[i+1]):
machine.add_weak_machine(boosted_machine.weak_machines[index], boosted_machine.weights[index, 0])
self.cascade.append(machine)
if isinstance(classification_thresholds, (int, float)):
self.thresholds = [classification_thresholds] * len(self.cascade)
else:
self.thresholds = classification_thresholds |
<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("FeatureExtractor")
self.extractor.save(hdf5)
hdf5.cd("..") |
<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 = FeatureExtractor(hdf5)
hdf5.cd("..")
self._indices() |
<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.Fore.RED
else:
reset = yellow = green = red = ''
try:
sha = 'oid'
commits = _pygit2_commits(commit, repository)
except ImportError:
try:
sha = 'hexsha'
commits = _git_commits(commit, repository)
except ImportError:
click.echo('To use this feature, please install pygit2. '
'GitPython will also work but is not recommended '
'(python <= 2.7 only).',
file=sys.stderr)
return 2
template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset)
template += '{message}{errors}'
count = 0
ident = ' '
re_line = re.compile('^', re.MULTILINE)
for commit in commits:
if skip_merge_commits and _is_merge_commit(commit):
continue
message = commit.message
errors = check_message(message, **options)
message = re.sub(re_line, ident, message)
if errors:
count += 1
errors.insert(0, red)
else:
errors = [green, 'Everything is OK.']
errors.append(reset)
click.echo(template.format(commit=commit,
message=message.encode('utf-8'),
errors='\n'.join(errors)))
if min(count, 1):
raise click.Abort |
<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 this lookup. Please consider using the decorator ``@cmd`` to declare your subcommands in classes for instance. """ |
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
if isinstance(obj, types.MethodType) and \
label in ("im_func", "im_self", "im_class"):
continue
## potential command
command_name = getattr(rvalue, "command_name",
label[:-1] if label.endswith("_") else
label)
subcmds.append((command_name, rvalue))
return OrderedDict(subcmds) |
<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_" % prefix) and resource_name.endswith(".py"):
module_name, _ext = os.path.splitext(kf.basename(resource_name))
yield module_name
for f in glob.glob(os.path.join(path, '%s_*.py' % prefix)):
module_name, _ext = os.path.splitext(kf.basename(f))
yield module_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_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:
mod = importlib.import_module(".%s" % module_name, mod.__package__)
except ImportError as e:
msg.warn("%r could not be loaded: %s"
% (module_name, e.message))
continue
except IOError as e:
print("%s" % module_name)
raise
if hasattr(mod, "Command") and is_cmd(mod.Command):
obj = mod.Command
if obj.__doc__ is None:
msg.warn("Missing doc string for command from "
"module %s" % module_name)
continue
if isinstance(obj, type):
obj = obj() ## instanciate it.
name = module_name.split("_", 1)[1]
if name in subcmds:
raise ValueError(
"Module command %r conflicts with already defined object "
"command."
% name)
subcmds[name] = obj
return subcmds |
<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 help object. obj.get_actions_titles() returns the subcommand if any. """ |
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""")
help_line = (" %%-%ds %%s"
% (max([5] + [len(a) for a in subcmds]), ))
env["actions"] = "\n".join(
help_line % (
name,
get_help(subcmd, subcmd_env(env, name), {}).split("\n")[0])
for name, subcmd in subcmds.items())
env["actions_help"] = "" if not env["actions"] else (
"ACTION could be one of:\n\n"
"%(actions)s\n\n"
"See '%(surcmd)s help ACTION' for more information "
"on a specific command."
% env)
if "%(std_usage)s" in doc:
env["std_usage"] = txt.indent(
("%(surcmd)s --help\n"
"%(surcmd)s --version" +
(("\n%(surcmd)s help [COMMAND]"
"\n%(surcmd)s ACTION [ARGS...]") if subcmds else ""))
% env,
_find_prefix(doc, "%(std_usage)s"),
first="")
if "%(std_options)s" in doc:
env["std_options"] = txt.indent(
"--help Show this screen.\n"
"--version Show version.",
_find_prefix(doc, "%(std_options)s"),
first="")
if subcmds and "%(actions_help)s" not in doc:
doc += "\n\n%(actions_help)s"
try:
output = doc % env
except KeyError as e:
msg.err("Doc interpolation of %s needed missing key %r"
% (aformat(env["surcmd"], attrs=["bold", ]),
e.args[0]))
exit(1)
except Exception as e:
msg.err(
"Documentation of %s is not valid. Please check it:\n%s"
% (aformat(env["surcmd"], attrs=["bold", ]),
doc))
exit(1)
return 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 get_calling_prototype(acallable):
"""Returns actual working calling prototype This means that the prototype given can be used directly in the same way by bound method, method, function, lambda:: (['a', 'b', 'c'], (1,)) (['a', 'b'], ()) (['a'], (None,)) ([], ()) (['self', 'a', 'b', 'c'], (None,)) (['a', 'b', 'c'], (None,)) (['a', 'b', 'c'], (None,)) (['a', 'b', 'c'], (None,)) (['a', 'b', 'c'], (None,)) (['a', 'b', 'c'], (None,)) (['a', 'b', 'c'], (None,)) """ |
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, vargs, vkwargs, defaults = inspect.getargspec(acallable.__call__)
## remove the 'self' argument
args = args[1:]
else:
raise ValueError("Hum, %r is a callable, but not a function/method, "
"nor a instance with __call__ arg..."
% acallable)
if vargs or vkwargs:
raise SyntaxError("variable *arg or **kwarg are not supported.")
if is_bound(acallable):
args = args[1:]
if defaults is None:
defaults = () ## be coherent
return args, defaults |
<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.path.exists(target_path):
os.makedirs(target_path)
if not os.path.exists(self.manifest_path):
open(self.manifest_path, "w+").close()
self.new = 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 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)):
path = os.path.join(self.root_dir, d, link)
if feature_path in os.path.realpath(path):
getattr(self, 'remove_from_%s' % d)(link) |
<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):
shutil.rmtree(path)
else:
os.unlink(path)
# in the case we just deleted ourselves out of a valid directory,
# we move to a valid directory.
if curpath == path:
os.chdir(tempfile.gettempdir())
except OSError:
logger.error("Unable to remove object at path %s" % path)
raise DirectoryException("Unable to remove object at path %s" % path) |
<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_path):
if os.path.islink(target_path):
os.remove(target_path)
else:
logger.warn("%s is not a symlink! please remove it manually." % target_path)
return
os.symlink(path, target_path) |
<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_options.items()) + list(options.items()))
raise_exception_on_failure = options.pop("raise_exception_on_failure")
resp = requests.get(
"%sdocs" % (self._url), params=options, timeout=self._timeout
)
if raise_exception_on_failure and resp.status_code != 200:
raise DocumentListingFailure(resp.content, resp.status_code)
return resp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.