def _setup_summaries(self): if self._short_summary is None: self._size = rich_string( self._summary_data[0][1].replace("×", "x"), self._summary_data[0][1]) self._summary_data[0][0] += ":" sum = self._summary_data[0] self._summary_set = True self._summary = rich_string( " ".join(map(str, sum)).replace("×", "x"), render_table(self._summary_data, html=("size", "axes", "res"), labels=("name", "size", "res", "axes", "modified"), styles=dict(name="font-weight: bold"), header=False, numbering=False)) ssum = [(sum[0], sum[1])] self._short_summary = rich_string( " ".join(map(str, ssum[0])).replace("×", "x"), render_table(ssum, html=("size", "axes", "res"), labels=("name", "size"), styles=dict(name="font-weight: bold"), header=False, numbering=False)) desc = [self._summary_data[0][1:]] self._description = rich_string( " ".join(map(str, desc[0])).replace("×", "x"), render_table(desc, html=("size", "axes", "res"), labels=("size", "res", "axes", "modified"), header=False, numbering=False))
def _setup_summaries(self): if self._short_summary is None: preamble = OrderedDict() postscript = OrderedDict() div_id = uuid.uuid4().hex actions = [ self._action_buttons_(preamble=preamble, postscript=postscript, div_id=div_id) ] self._size = rich_string(self._summary_data[0][1].replace("×", "x"), self._summary_data[0][1]) self._summary_data[0][0] += ":" sum = self._summary_data[0] self._summary_set = True self._summary = rich_string(" ".join(map(str,sum)).replace("×", "x"), render_table(self._summary_data, html=("size", "axes", "res"), labels=("name", "size", "res", "axes", "modified"), styles=dict(name="font-weight: bold"), header=False, numbering=False, actions=actions, preamble=preamble, postscript=postscript, div_id=div_id)) ssum = [(sum[0], sum[1])] self._short_summary = rich_string(" ".join(map(str, ssum[0])).replace("×", "x"), render_table(ssum, html=("size", "axes", "res"), labels=("name", "size"), styles=dict(name="font-weight: bold"), header=False, numbering=False, div_id=div_id)) desc = [self._summary_data[0][1:]] self._description = rich_string(" ".join(map(str, desc[0])).replace("×", "x"), render_table(desc, html=("size", "axes", "res"), labels=("size", "res", "axes", "modified"), header=False, numbering=False, actions=actions, preamble=preamble, postscript=postscript, div_id=div_id))
def __init__(self, path, load=False, title=None): """Construct a datafile and set up standard attributes. Args: path: path to the file load: if True, will "load" detailed file content by calling self._load(). The meaning of this depends on the subclass. For example, when a DataDir loads, it will scan its content. In general, __init__ is meant to be fast, while slower operations are deferred to _load(). """ self.fullpath = path self.path = FileBase.get_display_path(path) if title is None: if os.path.isdir(self.fullpath): title = rich_string(self.path, bold=True) else: title = rich_string(self.path, "<A HREF='{}' target='_blank'><B>{}</B></A>".format(render_url(self.fullpath), self.path)) ItemBase.__init__(self, title=title) self.name = os.path.basename(self.fullpath) self.basepath, self.ext = os.path.splitext(self.path) self.basename = os.path.basename(self.basepath) # directory key set up for sorting purposes # directories sort themselves before files isdir = int(os.path.isdir(self.fullpath)) self._dirkey = 1-isdir, os.path.dirname(self.fullpath) self._scan_impl() # timestamp of file last time content was loaded self._loaded_mtime = None if load: self._load()
def _header_html(self, title=None, subtitle=None): """Helper method, returns standard header line based on title, subtitle and description. title=False to omit title, else != None to override title """ if title is not False: title = rich_string(title if title is not None else self.title, div_class="rp-item-title") subtitle = rich_string( subtitle if subtitle is not None else self.description, div_class="rp-item-subtitle") return f"""<div class='rp-item-header'> {": ".join([x.html for x in (title, subtitle) if x])} </div>""" return ""
def _header_html(self, subtitle=None): if self.title or self.description: if self.title: return "{}{}: {}\n".format(self.title.html, rich_string(subtitle).html, self.description.html) else: return "{}\n".format(self.description.html) return ""
def _auto_update_summary(self): if not self._summary_set: self._summary = self._title if self._description: self._summary = self._summary + rich_string( ": {}".format(self._description.text), ": {}".format( self._description.html))
def __init__(self, title=None): self._summary_set = None self._message = None self._summary = self._info = self._description = self._size = rich_string( None) # use setter method for this, since it'll update the summary self.title = title
def extract(self, regexp, groups=slice(None)): regexp = re.compile(regexp) if type(groups) is int: groups = slice(groups, groups + 1) elif type(groups) not in (list, tuple, slice): raise TypeError("invalid groups argument of type {}".format( type(groups))) rows = [] for _, line in self.lines: match = regexp.search(line) if not match: continue grps = match.groups() if type(groups) is slice: rows.append([rich_string(txt) for txt in grps[groups]]) else: rows.append([rich_string(grps[i]) for i in groups]) self.message("{} lines match".format(len(rows)), timeout=2) return tabulate(rows)
def _scan_impl(self): """ "Scans" file, i.e. performs the faster (read disk) operations to get overall file information. This is meant to be augmented by subclasses. Default version just gets filesize and mtime. """ self.update_mtime() # get filesize size = self._byte_size = os.path.getsize(self.fullpath) # human-friendly size if size > 0: exponent = min(int(math.log(size, 1024)), len(self._unit_list) - 1) quotient = float(size) / 1024 ** exponent unit, num_decimals = self._unit_list[exponent] format_string = '{:.%sf}{}' % (num_decimals) self._size = rich_string(format_string.format(quotient, unit)) else: self._size = rich_string('0') self.description = rich_string("{} {}".format(self.size, self.mtime_str))
def _scan_impl(self): """ "Scans" file, i.e. performs the faster (read disk) operations to get overall file information. This is meant to be augmented by subclasses. Default version just gets filesize and mtime. """ self.update_mtime() # get filesize size = self._byte_size = os.path.getsize(self.fullpath) # human-friendly size if size > 0: exponent = min(int(math.log(size, 1024)), len(self._unit_list) - 1) quotient = float(size) / 1024**exponent unit, num_decimals = self._unit_list[exponent] format_string = '{:.%sf}{}' % (num_decimals) self._size = rich_string(format_string.format(quotient, unit)) else: self._size = rich_string('0') self.description = rich_string("{} {}".format(self.size, self.mtime_str))
def __init__(self, path, load=False, title=None): """Construct a datafile and set up standard attributes. Args: path: path to the file load: if True, will "load" detailed file content by calling self._load(). The meaning of this depends on the subclass. For example, when a DataDir loads, it will scan its content. In general, __init__ is meant to be fast, while slower operations are deferred to _load(). """ self.fullpath = path self.path = FileBase.get_display_path(path) if title is None: if os.path.isdir(self.fullpath): title = rich_string(self.path, bold=True) else: title = rich_string( self.path, "<A HREF='{}' target='_blank'><B>{}</B></A>".format( render_url(self.fullpath), self.path)) ItemBase.__init__(self, title=title) self.name = os.path.basename(self.fullpath) self.basepath, self.ext = os.path.splitext(self.path) self.basename = os.path.basename(self.basepath) self._subproduct_cache = {} # directory key set up for sorting purposes # directories sort themselves before files isdir = int(os.path.isdir(self.fullpath)) self._dirkey = 1 - isdir, os.path.dirname(self.fullpath) self._scan_impl() # timestamp of file last time content was loaded self._loaded_mtime = None if load: self._load()
def _scan_impl(self): radiopadre.file.FileBase._scan_impl(self) if is_svg_file(self.fullpath): self.description = "SVG" else: try: img = PIL.Image.open(self.fullpath) except Exception as exc: print(f"Error opening image {self.fullpath}: {exc}") self.size = self.description = "(error)" return size = "{} {}×{}".format(img.format, img.width, img.height) self.size = self.description = rich_string( size.replace("×", "x"), size)
def title(self, value): self._title = rich_string(value, div_class="rp-item-title") self._auto_update_summary()
def description(self, value): self._description = rich_string(value) self._auto_update_summary()
def __init__(self, title=None): self._summary_set = None self._message = None self._summary = self._info = self._description = self._size = rich_string(None) # use setter method for this, since it'll update the summary self.title = title
from IPython.display import HTML, Image, display from radiopadre.render import RenderableElement, rich_string from collections import OrderedDict import itertools _NULL_CELL = rich_string("") class Table(RenderableElement): def __init__(self, items, ncol=0, zebra=True, align="left", cw="auto", tw="auto", fs=None, lh=1.5, styles={}): """ ncol: if set, fixes number of columns """ self._data = {} self._nrow = len(items) self._ncol = ncol self._styles = styles.copy() if zebra: self.set_style("table-row-even", "background", "#D0D0D0") self.set_style("table-row-odd", "background", "#FFFFFF")
def __init__(self, items, ncol=0, zebra=True, align="left", cw="auto", tw="auto", fs=None, lh=1.5, styles={}): """ ncol: if set, fixes number of columns """ self._data = {} self._nrow = len(items) self._ncol = ncol self._styles = styles.copy() if zebra: self.set_style("table-row-even", "background", "#D0D0D0") self.set_style("table-row-odd", "background", "#FFFFFF") elif zebra is False: self.set_style("table-row-even", "background", "transparent") self.set_style("table-row-odd", "background", "transparent") if align: self.set_style("table-cell", "align", align) self.set_style("table-cell", "text-align", align) if fs is not None: self.set_style("table", "font-size", "{}em".format(fs)) if lh is not None: self.set_style("table", "line-height", "{}em".format(lh * (fs or 1))) for irow, row in enumerate(items): self._ncol = max(len(row), self._ncol) for icol, item in enumerate(row): if item is None: item = _NULL_CELL elif type(item) is str: item = rich_string(item) elif not isinstance(item, RenderableElement): item = rich_string(str(item)) self._data[irow, icol] = item # work out column widths if cw is not None: if cw is "auto": cw = {} elif cw is "equal": cw = {i: 1 / float(ncol) for i in range(ncol)} elif type(cw) in (list, tuple): cw = {i: w for i, w in enumerate(cw)} # set styles for icol in range(self._ncol): width = cw.get(icol, "auto") if type(width) in (float, int): width = "{:.2%}".format(width) self.set_style("col{}".format(icol), "width", width) # if any column widths are set, set table width if tw is not None: if tw is "auto": # set to 100% if any column width is set explicitly to a string if any([type(w) is str for w in cw.values()]): tw = 1 # else set to sum of fractional widths elif cw and all([type(w) is float for w in cw.values()]): tw = sum(cw.values()) else: tw = "auto" if type(tw) in (int, float): self.set_style("table", "width", "{:.1%}".format(tw)) elif tw is not None: self.set_style("table", "width", tw) self.set_style("table", "border", "0px") self.set_style("table-cell", "vertical-align", "top") self.set_style("table-cell", "padding-left", "2px") self.set_style("table-cell", "padding-right", "2px")
def description(self, value): self._description = rich_string(value) self._auto_update_summary()
def title(self, value): self._title = rich_string(value, bold=True) self._auto_update_summary()
def info(self, value): self._info = rich_string(value)
def _scan_impl(self): radiopadre.file.FileBase._scan_impl(self) img = PIL.Image.open(self.fullpath) size = "{} {}×{}".format(img.format, img.width, img.height) self.size = self.description = rich_string(size.replace("×", "x"), size)
def size(self, value): self._size = rich_string(value)
def summary(self, value): self._summary_set = True self._summary = rich_string(value)
def size(self, value): self._size = rich_string(value)
def _auto_update_summary(self): if not self._summary_set: self._summary = self._title if self._description: self._summary = self._summary + rich_string(": {}".format(self._description.text), ": {}".format(self._description.html))
def summary(self, value): self._summary_set = True self._summary = rich_string(value)
def info(self, value): self._info = rich_string(value)
def _render_title_link(self, title=None, **kw): """Renders the name of the item and/or link""" return self.title if title is None else rich_string(title).html
def _render(self, head=0, tail=0, full=None, grep=None, fs=None, slicer=None, title=None): self.rescan(load=True) head, tail = self._get_lines(head, tail, full, grep, slicer) return rich_string(self.render_text(head, tail, title=title), self.render_html(head, tail, fs=fs, title=title))
def render_html(self, *args, **kw): """ Method to be implemented by subclasses. Default version falls back to summary(). :return: HTML rendering of file content """ return rich_string(self.summary).html