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 _remove_blacklisted(self, directories): """ Attempts to remove the blacklisted directories from `directories` and then returns whatever is left in the set. Called from the `collect_directories` method. """
directories = util.to_absolute_paths(directories) directories = util.remove_from_set(directories, self.blacklisted_directories) return directories
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imread(filename, *args, **kwargs): """Return image data from TIFF file as numpy array. The first image series is returned if no arguments are provided. Parameters key : int, slice, or sequence of page indices Defines which pages to return as array. series : int Defines which series of pages to return as array. Examples -------- """
with TIFFfile(filename) as tif: return tif.asarray(*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 read_nih_image_header(fd, byte_order, dtype, count): """Read NIH_IMAGE_HEADER tag from file and return as dictionary."""
fd.seek(12, 1) return {'version': struct.unpack(byte_order+'H', fd.read(2))[0]}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_mm_header(fd, byte_order, dtype, count): """Read MM_HEADER tag from file and return as numpy.rec.array."""
return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_mm_uic1(fd, byte_order, dtype, count): """Read MM_UIC1 tag from file and return as dictionary."""
t = fd.read(8*count) t = struct.unpack('%s%iI' % (byte_order, 2*count), t) return dict((MM_TAG_IDS[k], v) for k, v in zip(t[::2], t[1::2]) if k in MM_TAG_IDS)
<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_mm_uic2(fd, byte_order, dtype, count): """Read MM_UIC2 tag from file and return as dictionary."""
result = {'number_planes': count} values = numpy.fromfile(fd, byte_order+'I', 6*count) result['z_distance'] = values[0::6] // values[1::6] #result['date_created'] = tuple(values[2::6]) #result['time_created'] = tuple(values[3::6]) #result['date_modified'] = tuple(values[4::6]) #result['time_modified'] = tuple(values[5::6]) 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 read_mm_uic3(fd, byte_order, dtype, count): """Read MM_UIC3 tag from file and return as dictionary."""
t = numpy.fromfile(fd, byte_order+'I', 2*count) return {'wavelengths': t[0::2] // t[1::2]}
<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_cz_lsm_info(fd, byte_order, dtype, count): """Read CS_LSM_INFO tag from file and return as numpy.rec.array."""
result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1, byteorder=byte_order)[0] {50350412: '1.3', 67127628: '2.0'}[result.magic_number] # validation 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 read_cz_lsm_scan_info(fd, byte_order): """Read LSM scan information from file and return as Record."""
block = Record() blocks = [block] unpack = struct.unpack if 0x10000000 != struct.unpack(byte_order+"I", fd.read(4))[0]: raise ValueError("not a lsm_scan_info structure") fd.read(8) while True: entry, dtype, size = unpack(byte_order+"III", fd.read(12)) if dtype == 2: value = stripnull(fd.read(size)) elif dtype == 4: value = unpack(byte_order+"i", fd.read(4))[0] elif dtype == 5: value = unpack(byte_order+"d", fd.read(8))[0] else: value = 0 if entry in CZ_LSM_SCAN_INFO_ARRAYS: blocks.append(block) name = CZ_LSM_SCAN_INFO_ARRAYS[entry] newobj = [] setattr(block, name, newobj) block = newobj elif entry in CZ_LSM_SCAN_INFO_STRUCTS: blocks.append(block) newobj = Record() block.append(newobj) block = newobj elif entry in CZ_LSM_SCAN_INFO_ATTRIBUTES: name = CZ_LSM_SCAN_INFO_ATTRIBUTES[entry] setattr(block, name, value) elif entry == 0xffffffff: block = blocks.pop() else: setattr(block, "unknown_%x" % entry, value) if not blocks: break return block
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replace_by(module_function, warn=False): """Try replace decorated function by module.function."""
def decorate(func, module_function=module_function, warn=warn): sys.path.append(os.path.dirname(__file__)) try: module, function = module_function.split('.') func, oldfunc = getattr(__import__(module), function), func globals()['__old_' + func.__name__] = oldfunc except Exception: if warn: warnings.warn("failed to import %s" % module_function) sys.path.pop() return func return decorate
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decodepackbits(encoded): """Decompress PackBits encoded byte string. PackBits is a simple byte-oriented run-length compression scheme. """
func = ord if sys.version[0] == '2' else lambda x: x result = [] i = 0 try: while True: n = func(encoded[i]) + 1 i += 1 if n < 129: result.extend(encoded[i:i+n]) i += n elif n > 129: result.extend(encoded[i:i+1] * (258-n)) i += 1 except IndexError: pass return b''.join(result) if sys.version[0] == '2' else bytes(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 unpackints(data, dtype, itemsize, runlen=0): """Decompress byte string to array of integers of any bit size <= 32. Parameters data : byte str Data to decompress. dtype : numpy.dtype or str A numpy boolean or integer type. itemsize : int Number of bits per integer. runlen : int Number of consecutive integers, after which to start at next byte. """
if itemsize == 1: # bitarray data = numpy.fromstring(data, '|B') data = numpy.unpackbits(data) if runlen % 8: data = data.reshape(-1, runlen+(8-runlen%8)) data = data[:, :runlen].reshape(-1) return data.astype(dtype) dtype = numpy.dtype(dtype) if itemsize in (8, 16, 32, 64): return numpy.fromstring(data, dtype) if itemsize < 1 or itemsize > 32: raise ValueError("itemsize out of range: %i" % itemsize) if dtype.kind not in "biu": raise ValueError("invalid dtype") itembytes = next(i for i in (1, 2, 4, 8) if 8 * i >= itemsize) if itembytes != dtype.itemsize: raise ValueError("dtype.itemsize too small") if runlen == 0: runlen = len(data) // itembytes skipbits = runlen*itemsize % 8 if skipbits: skipbits = 8 - skipbits shrbits = itembytes*8 - itemsize bitmask = int(itemsize*'1'+'0'*shrbits, 2) dtypestr = '>' + dtype.char # dtype always big endian? unpack = struct.unpack l = runlen * (len(data)*8 // (runlen*itemsize + skipbits)) result = numpy.empty((l, ), dtype) bitcount = 0 for i in range(len(result)): start = bitcount // 8 s = data[start:start+itembytes] try: code = unpack(dtypestr, s)[0] except Exception: code = unpack(dtypestr, s + b'\x00'*(itembytes-len(s)))[0] code = code << (bitcount % 8) code = code & bitmask result[i] = code >> shrbits bitcount += itemsize if (i+1) % runlen == 0: bitcount += skipbits 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 stripnull(string): """Return string truncated at first null character."""
i = string.find(b'\x00') return string if (i < 0) else string[: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 _fromfile(self): """Read TIFF header and all page records from file."""
self._fd.seek(0) try: self.byte_order = {b'II': '<', b'MM': '>'}[self._fd.read(2)] except KeyError: raise ValueError("not a valid TIFF file") version = struct.unpack(self.byte_order+'H', self._fd.read(2))[0] if version == 43: # BigTiff self.offset_size, zero = struct.unpack(self.byte_order+'HH', self._fd.read(4)) if zero or self.offset_size != 8: raise ValueError("not a valid BigTIFF file") elif version == 42: self.offset_size = 4 else: raise ValueError("not a TIFF file") self.pages = [] while True: try: page = TIFFpage(self) self.pages.append(page) except StopIteration: break if not self.pages: raise ValueError("empty TIFF file")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asarray(self, key=None, series=None): """Return image data of multiple TIFF pages as numpy array. By default the first image series is returned. Parameters key : int, slice, or sequence of page indices Defines which pages to return as array. series : int Defines which series of pages to return as array. """
if key is None and series is None: series = 0 if series is not None: pages = self.series[series].pages else: pages = self.pages if key is None: pass elif isinstance(key, int): pages = [pages[key]] elif isinstance(key, slice): pages = pages[key] elif isinstance(key, collections.Iterable): pages = [pages[k] for k in key] else: raise TypeError('key must be an int, slice, or sequence') if len(pages) == 1: return pages[0].asarray() elif self.is_nih: result = numpy.vstack(p.asarray(colormapped=False, squeeze=False) for p in pages) if pages[0].is_palette: result = numpy.take(pages[0].color_map, result, axis=1) result = numpy.swapaxes(result, 0, 1) else: if self.is_ome and any(p is None for p in pages): firstpage = next(p for p in pages if p) nopage = numpy.zeros_like( firstpage.asarray()) result = numpy.vstack((p.asarray() if p else nopage) for p in pages) if key is None: try: result.shape = self.series[series].shape except ValueError: warnings.warn("failed to reshape %s to %s" % ( result.shape, self.series[series].shape)) result.shape = (-1,) + pages[0].shape else: result.shape = (-1,) + pages[0].shape 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 _fromfile(self): """Read TIFF IFD structure and its tags from file. File cursor must be at storage position of IFD offset and is left at offset to next IFD. Raises StopIteration if offset (first bytes read) is 0. """
fd = self.parent._fd byte_order = self.parent.byte_order offset_size = self.parent.offset_size fmt = {4: 'I', 8: 'Q'}[offset_size] offset = struct.unpack(byte_order + fmt, fd.read(offset_size))[0] if not offset: raise StopIteration() # read standard tags tags = self.tags fd.seek(offset) fmt, size = {4: ('H', 2), 8: ('Q', 8)}[offset_size] try: numtags = struct.unpack(byte_order + fmt, fd.read(size))[0] except Exception: warnings.warn("corrupted page list") raise StopIteration() for _ in range(numtags): tag = TIFFtag(self.parent) tags[tag.name] = tag # read LSM info subrecords if self.is_lsm: pos = fd.tell() for name, reader in CZ_LSM_INFO_READERS.items(): try: offset = self.cz_lsm_info["offset_"+name] except KeyError: continue if not offset: continue fd.seek(offset) try: setattr(self, "cz_lsm_"+name, reader(fd, byte_order)) except ValueError: pass fd.seek(pos)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fromdata(self, code, dtype, count, value, name=None): """Initialize instance from arguments."""
self.code = int(code) self.name = name if name else str(code) self.dtype = TIFF_DATA_TYPES[dtype] self.count = int(count) self.value = 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 _fromfile(self, parent): """Read tag structure from open file. Advance file cursor."""
fd = parent._fd byte_order = parent.byte_order self._offset = fd.tell() self.value_offset = self._offset + parent.offset_size + 4 fmt, size = {4: ('HHI4s', 12), 8: ('HHQ8s', 20)}[parent.offset_size] data = fd.read(size) code, dtype = struct.unpack(byte_order + fmt[:2], data[:4]) count, value = struct.unpack(byte_order + fmt[2:], data[4:]) if code in TIFF_TAGS: name = TIFF_TAGS[code][0] elif code in CUSTOM_TAGS: name = CUSTOM_TAGS[code][0] else: name = str(code) try: dtype = TIFF_DATA_TYPES[dtype] except KeyError: raise ValueError("unknown TIFF tag data type %i" % dtype) fmt = '%s%i%s' % (byte_order, count*int(dtype[0]), dtype[1]) size = struct.calcsize(fmt) if size > parent.offset_size or code in CUSTOM_TAGS: pos = fd.tell() tof = {4: 'I', 8: 'Q'}[parent.offset_size] self.value_offset = struct.unpack(byte_order+tof, value)[0] fd.seek(self.value_offset) if code in CUSTOM_TAGS: readfunc = CUSTOM_TAGS[code][1] value = readfunc(fd, byte_order, dtype, count) fd.seek(0, 2) # bug in numpy/Python 3.x ? if isinstance(value, dict): # numpy.core.records.record value = Record(value) elif code in TIFF_TAGS or dtype[-1] == 's': value = struct.unpack(fmt, fd.read(size)) else: value = read_numpy(fd, byte_order, dtype, count) fd.seek(0, 2) # bug in numpy/Python 3.x ? fd.seek(pos) else: value = struct.unpack(fmt, value[:size]) if not code in CUSTOM_TAGS: if len(value) == 1: value = value[0] if dtype.endswith('s'): value = stripnull(value) self.code = code self.name = name self.dtype = dtype self.count = count self.value = 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 set_xylims(self, lims, axes=None, panel='top', **kws): """set xy limits"""
panel = self.get_panel(panel) # print("Stacked set_xylims ", panel, self.panel) panel.set_xylims(lims, axes=axes, **kws)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onThemeColor(self, color, item): """pass theme colors to bottom panel"""
bconf = self.panel_bot.conf if item == 'grid': bconf.set_gridcolor(color) elif item == 'bg': bconf.set_bgcolor(color) elif item == 'frame': bconf.set_framecolor(color) elif item == 'text': bconf.set_textcolor(color) bconf.canvas.draw()
<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_entry_points(self, names): """ adds `names` to the internal collection of entry points to track `names` can be a single object or an iterable but must be a string or iterable of strings. """
names = util.return_set(names) self.entry_point_names.update(names)
<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_entry_points(self, names): """ sets the internal collection of entry points to be equal to `names` `names` can be a single object or an iterable but must be a string or iterable of strings. """
names = util.return_set(names) self.entry_point_names = names
<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_entry_points(self, names): """ removes `names` from the set of entry points to track. `names` can be a single object or an iterable. """
names = util.return_set(names) util.remove_from_set(self.entry_point_names, names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_absolute_paths(paths): """ helper method to change `paths` to absolute paths. Returns a `set` object `paths` can be either a single object or iterable """
abspath = os.path.abspath paths = return_set(paths) absolute_paths = {abspath(x) for x in paths} return absolute_paths
<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(self, line=None): """ set a matplotlib Line2D to have the current properties"""
if line: markercolor = self.markercolor if markercolor is None: markercolor=self.color # self.set_markeredgecolor(markercolor, line=line) # self.set_markerfacecolor(markercolor, line=line) self.set_label(self.label, line=line) self.set_color(self.color, line=line) self.set_style(self.style, line=line) self.set_drawstyle(self.drawstyle, line=line) self.set_marker(self.marker,line=line) self.set_markersize(self.markersize, line=line) self.set_linewidth(self.linewidth, line=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 _init_trace(self, n, color, style, linewidth=2.5, zorder=None, marker=None, markersize=6): """ used for building set of traces"""
while n >= len(self.traces): self.traces.append(LineProperties()) line = self.traces[n] label = "trace %i" % (n+1) line.label = label line.drawstyle = 'default' if zorder is None: zorder = 5 * (n+1) line.zorder = zorder if color is not None: line.color = color if style is not None: line.style = style if linewidth is not None: line.linewidth = linewidth if marker is not None: line.marker = marker if markersize is not None: line.markersize = markersize self.traces[n] = 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 set_gridcolor(self, color): """set color for grid"""
self.gridcolor = color for ax in self.canvas.figure.get_axes(): for i in ax.get_xgridlines()+ax.get_ygridlines(): i.set_color(color) i.set_zorder(-1) if callable(self.theme_color_callback): self.theme_color_callback(color, 'grid')
<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_bgcolor(self, color): """set color for background of plot"""
self.bgcolor = color for ax in self.canvas.figure.get_axes(): if matplotlib.__version__ < '2.0': ax.set_axis_bgcolor(color) else: ax.set_facecolor(color) if callable(self.theme_color_callback): self.theme_color_callback(color, 'bg')
<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_framecolor(self, color): """set color for outer frame"""
self.framecolor = color self.canvas.figure.set_facecolor(color) if callable(self.theme_color_callback): self.theme_color_callback(color, 'frame')
<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_textcolor(self, color): """set color for labels and axis text"""
self.textcolor = color self.relabel() if callable(self.theme_color_callback): self.theme_color_callback(color, 'text')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def draw_legend(self, show=None, auto_location=True, delay_draw=False): "redraw the legend" if show is not None: self.show_legend = show axes = self.canvas.figure.get_axes() # clear existing legend try: lgn = self.mpl_legend if lgn: for i in lgn.get_texts(): i.set_text('') for i in lgn.get_lines(): i.set_linewidth(0) i.set_markersize(0) i.set_marker('None') lgn.draw_frame(False) lgn.set_visible(False) except: pass labs = [] lins = [] for ax in axes: for xline in ax.get_lines(): xlab = xline.get_label() if (xlab != '_nolegend_' and len(xlab)>0): lins.append(xline) for l in lins: xl = l.get_label() if not self.show_legend: xl = '' labs.append(xl) labs = tuple(labs) lgn = axes[0].legend if self.legend_onaxis.startswith('off'): lgn = self.canvas.figure.legend # 'best' and 'off axis' not implemented yet if self.legend_loc == 'best': self.legend_loc = 'upper right' if self.show_legend: self.mpl_legend = lgn(lins, labs, prop=self.legendfont, loc=self.legend_loc) self.mpl_legend.draw_frame(self.show_legend_frame) if matplotlib.__version__ < '2.0': facecol = axes[0].get_axis_bgcolor() else: facecol = axes[0].get_facecolor() self.mpl_legend.legendPatch.set_facecolor(facecol) if self.draggable_legend: self.mpl_legend.draggable(True, update='loc') self.legend_map = {} for legline, legtext, mainline in zip(self.mpl_legend.get_lines(), self.mpl_legend.get_texts(), lins): legline.set_picker(5) legtext.set_picker(5) self.legend_map[legline] = (mainline, legline, legtext) self.legend_map[legtext] = (mainline, legline, legtext) legtext.set_color(self.textcolor) self.set_added_text_size() if not delay_draw: self.canvas.draw()
<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_legend_location(self, loc, onaxis): "set legend location" self.legend_onaxis = 'on plot' if not onaxis: self.legend_onaxis = 'off plot' if loc == 'best': loc = 'upper right' if loc in self.legend_abbrevs: loc = self.legend_abbrevs[loc] if loc in self.legend_locs: self.legend_loc = loc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzoom(self, full=False, delay_draw=False): """unzoom display 1 level or all the way"""
if full: self.zoom_lims = self.zoom_lims[:1] self.zoom_lims = [] elif len(self.zoom_lims) > 0: self.zoom_lims.pop() self.set_viewlimits() if not delay_draw: self.canvas.draw()
<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_text(self, text, x, y, **kws): """add text to plot"""
self.panel.add_text(text, x, y, **kws)
<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_arrow(self, x1, y1, x2, y2, **kws): """add arrow to plot"""
self.panel.add_arrow(x1, y1, x2, y2, **kws)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ExportTextFile(self, fname, title='unknown plot'): "save plot data to external file" buff = ["# Plot Data for %s" % title, "#---------------------------------"] out = [] labels = [] itrace = 0 for ax in self.panel.fig.get_axes(): for line in ax.lines: itrace += 1 x = line.get_xdata() y = line.get_ydata() ylab = line.get_label() if len(ylab) < 1: ylab = 'Y%i' % itrace for c in ' .:";|/\\(){}[]\'&^%*$+=-?!@#': ylab = ylab.replace(c, '_') xlab = (' X%d' % itrace + ' '*3)[:4] ylab = ' '*(18-len(ylab)) + ylab + ' ' out.extend([x, y]) labels.extend([xlab, ylab]) if itrace == 0: return buff.append('# %s' % (' '.join(labels))) npts = [len(a) for a in out] for i in range(max(npts)): oline = [] for a in out: d = np.nan if i < len(a): d = a[i] oline.append(gformat(d, 12)) buff.append(' '.join(oline)) buff.append('') with open(fname, 'w') as fout: fout.write("\n".join(buff)) fout.close() self.write_message("Exported data to '%s'" % fname, panel=0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Adds `filepaths` to internal state. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be added. """
self.file_manager.add_plugin_filepaths(filepaths, except_blacklisted)
<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_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets internal state to `filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be set. """
self.file_manager.set_plugin_filepaths(filepaths, except_blacklisted)
<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_blacklisted_filepaths(self, filepaths, remove_from_stored=True): """ Add `filepaths` to blacklisted filepaths. If `remove_from_stored` is `True`, any `filepaths` in internal state will be automatically removed. """
self.file_manager.add_blacklisted_filepaths(filepaths, remove_from_stored)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_filepaths(self, directories): """ Collects and returns every filepath from each directory in `directories` that is filtered through the `file_filters`. If no `file_filters` are present, passes every file in directory as a result. Always returns a `set` object `directories` can be a object or an iterable. Recommend using absolute paths. """
plugin_filepaths = set() directories = util.to_absolute_paths(directories) for directory in directories: filepaths = util.get_filepaths_from_dir(directory) filepaths = self._filter_filepaths(filepaths) plugin_filepaths.update(set(filepaths)) plugin_filepaths = self._remove_blacklisted(plugin_filepaths) return plugin_filepaths
<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_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be added. """
filepaths = util.to_absolute_paths(filepaths) if except_blacklisted: filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) self.plugin_filepaths.update(filepaths)
<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_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blacklisted will not be set. """
filepaths = util.to_absolute_paths(filepaths) if except_blacklisted: filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) self.plugin_filepaths = filepaths
<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_plugin_filepaths(self, filepaths): """ Removes `filepaths` from `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if not passed in. `filepaths` can be a single object or an iterable. """
filepaths = util.to_absolute_paths(filepaths) self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
<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_file_filters(self, file_filters): """ Sets internal file filters to `file_filters` by tossing old state. `file_filters` can be single object or iterable. """
file_filters = util.return_list(file_filters) self.file_filters = file_filters
<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_file_filters(self, file_filters): """ Adds `file_filters` to the internal file filters. `file_filters` can be single object or iterable. """
file_filters = util.return_list(file_filters) self.file_filters.extend(file_filters)
<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_file_filters(self, file_filters): """ Removes the `file_filters` from the internal state. `file_filters` can be a single object or an iterable. """
self.file_filters = util.remove_from_list(self.file_filters, file_filters)
<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_blacklisted_filepaths(self, filepaths, remove_from_stored=True): """ Add `filepaths` to blacklisted filepaths. If `remove_from_stored` is `True`, any `filepaths` in `plugin_filepaths` will be automatically removed. Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory. """
filepaths = util.to_absolute_paths(filepaths) self.blacklisted_filepaths.update(filepaths) if remove_from_stored: self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
<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_blacklisted_filepaths(self, filepaths, remove_from_stored=True): """ Sets internal blacklisted filepaths to filepaths. If `remove_from_stored` is `True`, any `filepaths` in `self.plugin_filepaths` will be automatically removed. Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory. """
filepaths = util.to_absolute_paths(filepaths) self.blacklisted_filepaths = filepaths if remove_from_stored: self.plugin_filepaths = util.remove_from_set(self.plugin_filepaths, filepaths)
<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_blacklisted_filepaths(self, filepaths): """ Removes `filepaths` from blacklisted filepaths Recommend passing in absolute filepaths but method will attempt to convert to absolute filepaths based on current working directory. """
filepaths = util.to_absolute_paths(filepaths) black_paths = self.blacklisted_filepaths black_paths = util.remove_from_set(black_paths, filepaths)
<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_blacklisted(self, filepaths): """ internal helper method to remove the blacklisted filepaths from `filepaths`. """
filepaths = util.remove_from_set(filepaths, self.blacklisted_filepaths) return filepaths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filter_filepaths(self, filepaths): """ helps iterate through all the file parsers each filter is applied individually to the same set of `filepaths` """
if self.file_filters: plugin_filepaths = set() for file_filter in self.file_filters: plugin_paths = file_filter(filepaths) plugin_filepaths.update(plugin_paths) else: plugin_filepaths = filepaths return plugin_filepaths
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rgb(color,default=(0,0,0)): """ return rgb tuple for named color in rgb.txt or a hex color """
c = color.lower() if c[0:1] == '#' and len(c)==7: r,g,b = c[1:3], c[3:5], c[5:] r,g,b = [int(n, 16) for n in (r, g, b)] return (r,g,b) if c.find(' ')>-1: c = c.replace(' ','') if c.find('gray')>-1: c = c.replace('gray','grey') if c in x11_colors.keys(): return x11_colors[c] return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hexcolor(color): " returns hex color given a tuple, wx.Color, or X11 named color" # first, if this is a hex color already, return! # Python 3: needs rewrite for str/unicode change if isinstance(color, six.string_types): if color[0] == '#' and len(color)==7: return color.lower() # now, get color to an rgb tuple rgb = (0,0,0) if isinstance(color, tuple): rgb = color elif isinstance(color, list): rgb = tuple(color) elif isinstance(color, six.string_types): c = color.lower() if c.find(' ')>-1: c = c.replace(' ','') if c.find('gray')>-1: c = c.replace('gray','grey') if c in x11_colors: rgb = x11_colors[c] else: try: rgb = color.Red(), color.Green(), color.Blue() except: pass # convert rgb to hex color col = '#%02x%02x%02x' % (rgb) return col.lower()
<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_custom_colormaps(): """ registers custom color maps """
if not HAS_MPL: return () makemap = LinearSegmentedColormap.from_list for name, val in custom_colormap_data.items(): cm1 = np.array(val).transpose().astype('f8')/256.0 cm2 = cm1[::-1] nam1 = name nam2 = '%s_r' % name register_cmap(name=nam1, cmap=makemap(nam1, cm1, 256), lut=256) register_cmap(name=nam2, cmap=makemap(nam2, cm2, 256), lut=256) return ('stdgamma', 'red', 'green', 'blue', 'red_heat', 'green_heat', 'blue_heat', 'magenta', 'yellow', 'cyan')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onCMapSave(self, event=None, col='int'): """save color table image"""
file_choices = 'PNG (*.png)|*.png' ofile = 'Colormap.png' dlg = wx.FileDialog(self, message='Save Colormap as...', defaultDir=os.getcwd(), defaultFile=ofile, wildcard=file_choices, style=wx.FD_SAVE|wx.FD_CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: self.cmap_panels[0].cmap_canvas.print_figure(dlg.GetPath(), dpi=600)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plugin_valid(self, filename): """ Checks if the given filename is a valid plugin for this Strategy """
filename = os.path.basename(filename) for regex in self.regex_expressions: if regex.match(filename): return True 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 get_message(self, message_id): """Gets message matching provided id. the Outlook email matching the provided message_id. Args: message_id: A string for the intended message, provided by Outlook Returns: :class:`Message <pyOutlook.core.message.Message>` """
r = requests.get('https://outlook.office.com/api/v2.0/me/messages/' + message_id, headers=self._headers) check_response(r) return Message._json_to_message(self, r.json())
<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_messages(self, page=0): """Get first 10 messages in account, across all folders. Keyword Args: page (int): Integer representing the 'page' of results to fetch Returns: List[:class:`Message <pyOutlook.core.message.Message>`] """
endpoint = 'https://outlook.office.com/api/v2.0/me/messages' if page > 0: endpoint = endpoint + '/?%24skip=' + str(page) + '0' log.debug('Getting messages from endpoint: {} with Headers: {}'.format(endpoint, self._headers)) r = requests.get(endpoint, headers=self._headers) check_response(r) return Message._json_to_messages(self, r.json())
<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_folders(self): """ Returns a list of all folders for this account Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`] """
endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' r = requests.get(endpoint, headers=self._headers) if check_response(r): return Folder._json_to_folders(self, r.json())
<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_folder_by_id(self, folder_id): """ Retrieve a Folder by its Outlook ID Args: folder_id: The ID of the :class:`Folder <pyOutlook.core.folder.Folder>` to retrieve Returns: :class:`Folder <pyOutlook.core.folder.Folder>` """
endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_id r = requests.get(endpoint, headers=self._headers) check_response(r) return_folder = r.json() return Folder._json_to_folder(self, return_folder)
<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_messages_from_folder_name(self, folder_name): """ Retrieves all messages from a folder, specified by its name. This only works with "Well Known" folders, such as 'Inbox' or 'Drafts'. Args: folder_name (str): The name of the folder to retrieve Returns: List[:class:`Message <pyOutlook.core.message.Message>` ] """
r = requests.get('https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_name + '/messages', headers=self._headers) check_response(r) return Message._json_to_messages(self, r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_representation(self, content_type): """ Returns the JSON representation of this message required for making requests to the API. Args: content_type (str): Either 'HTML' or 'Text' """
payload = dict(Subject=self.subject, Body=dict(ContentType=content_type, Content=self.body)) if self.sender is not None: payload.update(From=self.sender.api_representation()) # A list of strings can also be provided for convenience. If provided, convert them into Contacts if any(isinstance(item, str) for item in self.to): self.to = [Contact(email=email) for email in self.to] # Turn each contact into the JSON needed for the Outlook API recipients = [contact.api_representation() for contact in self.to] payload.update(ToRecipients=recipients) # Conduct the same process for CC and BCC if needed if self.cc: if any(isinstance(email, str) for email in self.cc): self.cc = [Contact(email) for email in self.cc] cc_recipients = [contact.api_representation() for contact in self.cc] payload.update(CcRecipients=cc_recipients) if self.bcc: if any(isinstance(email, str) for email in self.bcc): self.bcc = [Contact(email) for email in self.bcc] bcc_recipients = [contact.api_representation() for contact in self.bcc] payload.update(BccRecipients=bcc_recipients) if self._attachments: payload.update(Attachments=[attachment.api_representation() for attachment in self._attachments]) payload.update(Importance=str(self.importance)) return dict(Message=payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, content_type='HTML'): """ Takes the recipients, body, and attachments of the Message and sends. Args: content_type: Can either be 'HTML' or 'Text', defaults to HTML. """
payload = self.api_representation(content_type) endpoint = 'https://outlook.office.com/api/v1.0/me/sendmail' self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, to_recipients, forward_comment=None): # type: (Union[List[Contact], List[str]], str) -> None """Forward Message to recipients with an optional comment. Args: to_recipients: A list of :class:`Contacts <pyOutlook.core.contact.Contact>` to send the email to. forward_comment: String comment to append to forwarded email. Examples: """
payload = dict() if forward_comment is not None: payload.update(Comment=forward_comment) # A list of strings can also be provided for convenience. If provided, convert them into Contacts if any(isinstance(recipient, str) for recipient in to_recipients): to_recipients = [Contact(email=email) for email in to_recipients] # Contact() will handle turning itself into the proper JSON format for the API to_recipients = [contact.api_representation() for contact in to_recipients] payload.update(ToRecipients=to_recipients) endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/forward'.format(self.message_id) self._make_api_call('post', endpoint=endpoint, data=json.dumps(payload))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reply(self, reply_comment): """Reply to the Message. Notes: HTML can be inserted in the string and will be interpreted properly by Outlook. Args: reply_comment: String message to send with email. """
payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/' + self.message_id + '/reply' self._make_api_call('post', endpoint, data=payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reply_all(self, reply_comment): """Replies to everyone on the email, including those on the CC line. With great power, comes great responsibility. Args: reply_comment: The string comment to send to everyone on the email. """
payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/replyall'.format(self.message_id) self._make_api_call('post', endpoint, data=payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to(self, folder): """Moves the email to the folder specified by the folder parameter. Args: folder: A string containing the folder ID the message should be moved to, or a Folder instance """
if isinstance(folder, Folder): self.move_to(folder.id) else: self._move_to(folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rgb2cmy(self, img, whitebg=False): """transforms image from RGB to CMY"""
tmp = img*1.0 if whitebg: tmp = (1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0 out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0 out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/2.0 return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plugin_valid(self, filepath): """ checks to see if plugin ends with one of the approved extensions """
plugin_valid = False for extension in self.extensions: if filepath.endswith(".{}".format(extension)): plugin_valid = True break return plugin_valid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_representation(self): """ Returns the JSON formatting required by Outlook's API for contacts """
return dict(EmailAddress=dict(Name=self.name, Address=self.email))
<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_focused(self, account, is_focused): # type: (OutlookAccount, bool) -> bool """ Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on the value of is_focused. Args: account (OutlookAccount): The :class:`OutlookAccount <pyOutlook.core.main.OutlookAccount>` the override should be set for is_focused (bool): Whether this contact should be set to Focused, or Other. Returns: True if the request was successful """
endpoint = 'https://outlook.office.com/api/v2.0/me/InferenceClassification/Overrides' if is_focused: classification = 'Focused' else: classification = 'Other' data = dict(ClassifyAs=classification, SenderEmailAddress=dict(Address=self.email)) r = requests.post(endpoint, headers=account._headers, data=json.dumps(data)) # Will raise an error if necessary, otherwise returns True result = check_response(r) self.focused = is_focused 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 image2wxbitmap(img): "PIL image 2 wx bitmap" if is_wxPhoenix: wximg = wx.Image(*img.size) else: wximg = wx.EmptyImage(*img.size) wximg.SetData(img.tobytes()) return wximg.ConvertToBitmap()
<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_response(response): """ Checks that a response is successful, raising the appropriate Exceptions otherwise. """
status_code = response.status_code if 100 < status_code < 299: return True elif status_code == 401 or status_code == 403: message = get_response_data(response) raise AuthError('Access Token Error, Received ' + str(status_code) + ' from Outlook REST Endpoint with the message: {}'.format(message)) elif status_code == 400: message = get_response_data(response) raise RequestError('The request made to the Outlook API was invalid. Received the following message: {}'. format(message)) else: message = get_response_data(response) raise APIError('Encountered an unknown error from the Outlook API: {}'.format(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 get_plugins(self, filter_function=None): """ Gets out the plugins from the internal state. Returns a list object. If the optional filter_function is supplied, applies the filter function to the arguments before returning them. Filters should be callable and take a list argument of plugins. """
plugins = self.plugins if filter_function is not None: plugins = filter_function(plugins) return plugins
<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_instance(self, klasses): """ internal method that gets every instance of the klasses out of the internal plugin state. """
return [x for x in self.plugins if isinstance(x, klasses)]
<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_instances(self, filter_function=IPlugin): """ Gets instances out of the internal state using the default filter supplied in filter_function. By default, it is the class IPlugin. Can optionally pass in a list or tuple of classes in for `filter_function` which will accomplish the same goal. lastly, a callable can be passed in, however it is up to the user to determine if the objects are instances or not. """
if isinstance(filter_function, (list, tuple)): return self._get_instance(filter_function) elif inspect.isclass(filter_function): return self._get_instance(filter_function) elif filter_function is None: return self.plugins else: return filter_function(self.plugins)
<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(self, classes): """ Register classes as plugins that are not subclassed from IPlugin. `classes` may be a single object or an iterable. """
classes = util.return_list(classes) for klass in classes: IPlugin.register(klass)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _instance_parser(self, plugins): """ internal method to parse instances of plugins. Determines if each class is a class instance or object instance and calls the appropiate handler method. """
plugins = util.return_list(plugins) for instance in plugins: if inspect.isclass(instance): self._handle_class_instance(instance) else: self._handle_object_instance(instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_class_instance(self, klass): """ handles class instances. If a class is blacklisted, returns. If uniuqe_instances is True and the class is unique, instantiates the class and adds the new object to plugins. If not unique_instances, creates and adds new instance to plugin state """
if (klass in self.blacklisted_plugins or not self.instantiate_classes or klass == IPlugin): return elif self.unique_instances and self._unique_class(klass): self.plugins.append(klass()) elif not self.unique_instances: self.plugins.append(klass())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unique_class(self, cls): """ internal method to check if any of the plugins are instances of a given cls """
return not any(isinstance(obj, cls) for obj in self.plugins)
<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_blacklisted_plugins(self, plugins): """ add blacklisted plugins. `plugins` may be a single object or iterable. """
plugins = util.return_list(plugins) self.blacklisted_plugins.extend(plugins)
<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_blacklisted_plugins(self, plugins): """ sets blacklisted plugins. `plugins` may be a single object or iterable. """
plugins = util.return_list(plugins) self.blacklisted_plugins = plugins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_plugins(self, modules=None): """ Collects all the plugins from `modules`. If modules is None, collects the plugins from the loaded modules. All plugins are passed through the module filters, if any are any, and returned as a list. """
if modules is None: modules = self.get_loaded_modules() else: modules = util.return_list(modules) plugins = [] for module in modules: module_plugins = [(item[1], item[0]) for item in inspect.getmembers(module) if item[1] and item[0] != '__builtins__'] module_plugins, names = zip(*module_plugins) module_plugins = self._filter_modules(module_plugins, names) plugins.extend(module_plugins) return plugins
<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_module_plugin_filters(self, module_plugin_filters): """ Sets the internal module filters to `module_plugin_filters` `module_plugin_filters` may be a single object or an iterable. Every module filters must be a callable and take in a list of plugins and their associated names. """
module_plugin_filters = util.return_list(module_plugin_filters) self.module_plugin_filters = module_plugin_filters
<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_module_plugin_filters(self, module_plugin_filters): """ Adds `module_plugin_filters` to the internal module filters. May be a single object or an iterable. Every module filters must be a callable and take in a list of plugins and their associated names. """
module_plugin_filters = util.return_list(module_plugin_filters) self.module_plugin_filters.extend(module_plugin_filters)
<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_modules(self, names): """ An internal method that gets the `names` from sys.modules and returns them as a list """
loaded_modules = [] for name in names: loaded_modules.append(sys.modules[name]) return loaded_modules
<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_loaded_modules(self, modules): """ Manually add in `modules` to be tracked by the module manager. `modules` may be a single object or an iterable. """
modules = util.return_set(modules) for module in modules: if not isinstance(module, str): module = module.__name__ self.loaded_modules.add(module)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filter_modules(self, plugins, names): """ Internal helper method to parse all of the plugins and names through each of the module filters """
if self.module_plugin_filters: # check to make sure the number of plugins isn't changing original_length_plugins = len(plugins) module_plugins = set() for module_filter in self.module_plugin_filters: module_plugins.update(module_filter(plugins, names)) if len(plugins) < original_length_plugins: warning = """Module Filter removing plugins from original data member! Suggest creating a new list in each module filter and returning new list instead of modifying the original data member so subsequent module filters can have access to all the possible plugins.\n {}""" self._log.info(warning.format(module_filter)) plugins = module_plugins return plugins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_filepath(self, filepath): """ processes the filepath by checking if it is a directory or not and adding `.py` if not present. """
if (os.path.isdir(filepath) and os.path.isfile(os.path.join(filepath, '__init__.py'))): filepath = os.path.join(filepath, '__init__.py') if (not filepath.endswith('.py') and os.path.isfile(filepath + '.py')): filepath += '.py' return filepath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _processed_filepath(self, filepath): """ checks to see if the filepath has already been processed """
processed = False if filepath in self.processed_filepaths.values(): processed = True return processed
<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_loaded_modules(self): """ Updates the loaded modules by checking if they are still in sys.modules """
system_modules = sys.modules.keys() for module in list(self.loaded_modules): if module not in system_modules: self.processed_filepaths.pop(module) self.loaded_modules.remove(module)
<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_right_axes(self): "create, if needed, and return right-hand y axes" if len(self.fig.get_axes()) < 2: ax = self.axes.twinx() return self.fig.get_axes()[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 onLeftUp(self, event=None): """ left button up"""
if event is None: return self.cursor_mode_action('leftup', event=event) self.canvas.draw_idle() self.canvas.draw() self.ForwardEvent(event=event.guiEvent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ForwardEvent(self, event=None): """finish wx event, forward it to other wx objects"""
if event is not None: event.Skip() if self.HasCapture(): try: self.ReleaseMouse() except: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __date_format(self, x): """ formatter for date x-data. primitive, and probably needs improvement, following matplotlib's date methods. """
if x < 1: x = 1 span = self.axes.xaxis.get_view_interval() tmin = max(1.0, span[0]) tmax = max(2.0, span[1]) tmin = time.mktime(dates.num2date(tmin).timetuple()) tmax = time.mktime(dates.num2date(tmax).timetuple()) nhours = (tmax - tmin)/3600.0 fmt = "%m/%d" if nhours < 0.1: fmt = "%H:%M\n%Ssec" elif nhours < 4: fmt = "%m/%d\n%H:%M" elif nhours < 24*8: fmt = "%m/%d\n%H:%M" try: return time.strftime(fmt, dates.num2date(x).timetuple()) except: return "?"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def xformatter(self, x, pos): " x-axis formatter " if self.use_dates: return self.__date_format(x) else: return self.__format(x, type='x')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __onKeyEvent(self, event=None): """ handles key events on canvas """
if event is None: return key = event.guiEvent.GetKeyCode() if (key < wx.WXK_SPACE or key > 255): return ckey = chr(key) mod = event.guiEvent.ControlDown() if self.is_macosx: mod = event.guiEvent.MetaDown() if mod: if ckey == 'C': self.canvas.Copy_to_Clipboard(event) elif ckey == 'S': self.save_figure(event) elif ckey == 'K': self.configure(event) elif ckey == 'Z': self.unzoom(event) elif ckey == 'P': self.canvas.printer.Print(event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zoom_motion(self, event=None): """motion event handler for zoom mode"""
try: x, y = event.x, event.y except: return self.report_motion(event=event) if self.zoom_ini is None: return ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini if event.xdata is not None: self.x_lastmove = event.xdata if event.ydata is not None: self.y_lastmove = event.ydata x0 = min(x, ini_x) ymax = max(y, ini_y) width = abs(x-ini_x) height = abs(y-ini_y) y0 = self.canvas.figure.bbox.height - ymax zdc = wx.ClientDC(self.canvas) zdc.SetLogicalFunction(wx.XOR) zdc.SetBrush(wx.TRANSPARENT_BRUSH) zdc.SetPen(wx.Pen('White', 2, wx.SOLID)) zdc.ResetBoundingBox() if not is_wxPhoenix: zdc.BeginDrawing() # erase previous box if self.rbbox is not None: zdc.DrawRectangle(*self.rbbox) self.rbbox = (x0, y0, width, height) zdc.DrawRectangle(*self.rbbox) if not is_wxPhoenix: zdc.EndDrawing()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zoom_leftdown(self, event=None): """leftdown event handler for zoom mode"""
self.x_lastmove, self.y_lastmove = None, None self.zoom_ini = (event.x, event.y, event.xdata, event.ydata) self.report_leftdown(event=event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lasso_leftdown(self, event=None): """leftdown event handler for lasso mode"""
try: self.report_leftdown(event=event) except: return if event.inaxes: # set lasso color color='goldenrod' cmap = getattr(self.conf, 'cmap', None) if isinstance(cmap, dict): cmap = cmap['int'] try: if cmap is not None: rgb = (int(i*255)^255 for i in cmap._lut[0][:3]) color = '#%02x%02x%02x' % tuple(rgb) except: pass self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.lassoHandler) self.lasso.line.set_color(color)