id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
229,800
saulpw/visidata
visidata/canvas.py
Canvas.fixPoint
def fixPoint(self, plotterPoint, canvasPoint): 'adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint' self.visibleBox.xmin = canvasPoint.x - self.canvasW(plotterPoint.x-self.plotviewBox.xmin) self.visibleBox.ymin = canvasPoint.y - self.canvasH(plotterPoint.y-self.plotviewBox.ymin) self.refresh()
python
def fixPoint(self, plotterPoint, canvasPoint): 'adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint' self.visibleBox.xmin = canvasPoint.x - self.canvasW(plotterPoint.x-self.plotviewBox.xmin) self.visibleBox.ymin = canvasPoint.y - self.canvasH(plotterPoint.y-self.plotviewBox.ymin) self.refresh()
[ "def", "fixPoint", "(", "self", ",", "plotterPoint", ",", "canvasPoint", ")", ":", "self", ".", "visibleBox", ".", "xmin", "=", "canvasPoint", ".", "x", "-", "self", ".", "canvasW", "(", "plotterPoint", ".", "x", "-", "self", ".", "plotviewBox", ".", "...
adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint
[ "adjust", "visibleBox", ".", "xymin", "so", "that", "canvasPoint", "is", "plotted", "at", "plotterPoint" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L485-L489
229,801
saulpw/visidata
visidata/canvas.py
Canvas.zoomTo
def zoomTo(self, bbox): 'set visible area to bbox, maintaining aspectRatio if applicable' self.fixPoint(self.plotviewBox.xymin, bbox.xymin) self.zoomlevel=max(bbox.w/self.canvasBox.w, bbox.h/self.canvasBox.h)
python
def zoomTo(self, bbox): 'set visible area to bbox, maintaining aspectRatio if applicable' self.fixPoint(self.plotviewBox.xymin, bbox.xymin) self.zoomlevel=max(bbox.w/self.canvasBox.w, bbox.h/self.canvasBox.h)
[ "def", "zoomTo", "(", "self", ",", "bbox", ")", ":", "self", ".", "fixPoint", "(", "self", ".", "plotviewBox", ".", "xymin", ",", "bbox", ".", "xymin", ")", "self", ".", "zoomlevel", "=", "max", "(", "bbox", ".", "w", "/", "self", ".", "canvasBox",...
set visible area to bbox, maintaining aspectRatio if applicable
[ "set", "visible", "area", "to", "bbox", "maintaining", "aspectRatio", "if", "applicable" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L491-L494
229,802
saulpw/visidata
visidata/canvas.py
Canvas.checkCursor
def checkCursor(self): 'override Sheet.checkCursor' if self.cursorBox: if self.cursorBox.h < self.canvasCharHeight: self.cursorBox.h = self.canvasCharHeight*3/4 if self.cursorBox.w < self.canvasCharWidth: self.cursorBox.w = self.canvasCharWidth*3/4 return False
python
def checkCursor(self): 'override Sheet.checkCursor' if self.cursorBox: if self.cursorBox.h < self.canvasCharHeight: self.cursorBox.h = self.canvasCharHeight*3/4 if self.cursorBox.w < self.canvasCharWidth: self.cursorBox.w = self.canvasCharWidth*3/4 return False
[ "def", "checkCursor", "(", "self", ")", ":", "if", "self", ".", "cursorBox", ":", "if", "self", ".", "cursorBox", ".", "h", "<", "self", ".", "canvasCharHeight", ":", "self", ".", "cursorBox", ".", "h", "=", "self", ".", "canvasCharHeight", "*", "3", ...
override Sheet.checkCursor
[ "override", "Sheet", ".", "checkCursor" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L534-L542
229,803
saulpw/visidata
visidata/canvas.py
Canvas.scaleX
def scaleX(self, x): 'returns plotter x coordinate' return round(self.plotviewBox.xmin+(x-self.visibleBox.xmin)*self.xScaler)
python
def scaleX(self, x): 'returns plotter x coordinate' return round(self.plotviewBox.xmin+(x-self.visibleBox.xmin)*self.xScaler)
[ "def", "scaleX", "(", "self", ",", "x", ")", ":", "return", "round", "(", "self", ".", "plotviewBox", ".", "xmin", "+", "(", "x", "-", "self", ".", "visibleBox", ".", "xmin", ")", "*", "self", ".", "xScaler", ")" ]
returns plotter x coordinate
[ "returns", "plotter", "x", "coordinate" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L562-L564
229,804
saulpw/visidata
visidata/canvas.py
Canvas.scaleY
def scaleY(self, y): 'returns plotter y coordinate' return round(self.plotviewBox.ymin+(y-self.visibleBox.ymin)*self.yScaler)
python
def scaleY(self, y): 'returns plotter y coordinate' return round(self.plotviewBox.ymin+(y-self.visibleBox.ymin)*self.yScaler)
[ "def", "scaleY", "(", "self", ",", "y", ")", ":", "return", "round", "(", "self", ".", "plotviewBox", ".", "ymin", "+", "(", "y", "-", "self", ".", "visibleBox", ".", "ymin", ")", "*", "self", ".", "yScaler", ")" ]
returns plotter y coordinate
[ "returns", "plotter", "y", "coordinate" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L566-L568
229,805
saulpw/visidata
visidata/canvas.py
Canvas.render
def render(self, h, w): 'resets plotter, cancels previous render threads, spawns a new render' self.needsRefresh = False cancelThread(*(t for t in self.currentThreads if t.name == 'plotAll_async')) self.labels.clear() self.resetCanvasDimensions(h, w) self.render_async()
python
def render(self, h, w): 'resets plotter, cancels previous render threads, spawns a new render' self.needsRefresh = False cancelThread(*(t for t in self.currentThreads if t.name == 'plotAll_async')) self.labels.clear() self.resetCanvasDimensions(h, w) self.render_async()
[ "def", "render", "(", "self", ",", "h", ",", "w", ")", ":", "self", ".", "needsRefresh", "=", "False", "cancelThread", "(", "*", "(", "t", "for", "t", "in", "self", ".", "currentThreads", "if", "t", ".", "name", "==", "'plotAll_async'", ")", ")", "...
resets plotter, cancels previous render threads, spawns a new render
[ "resets", "plotter", "cancels", "previous", "render", "threads", "spawns", "a", "new", "render" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L582-L588
229,806
saulpw/visidata
visidata/canvas.py
Canvas.render_sync
def render_sync(self): 'plots points and lines and text onto the Plotter' self.setZoom() bb = self.visibleBox xmin, ymin, xmax, ymax = bb.xmin, bb.ymin, bb.xmax, bb.ymax xfactor, yfactor = self.xScaler, self.yScaler plotxmin, plotymin = self.plotviewBox.xmin, self.plotviewBox.ymin for vertexes, attr, row in Progress(self.polylines, 'rendering'): if len(vertexes) == 1: # single point x1, y1 = vertexes[0] x1, y1 = float(x1), float(y1) if xmin <= x1 <= xmax and ymin <= y1 <= ymax: x = plotxmin+(x1-xmin)*xfactor y = plotymin+(y1-ymin)*yfactor self.plotpixel(round(x), round(y), attr, row) continue prev_x, prev_y = vertexes[0] for x, y in vertexes[1:]: r = clipline(prev_x, prev_y, x, y, xmin, ymin, xmax, ymax) if r: x1, y1, x2, y2 = r x1 = plotxmin+float(x1-xmin)*xfactor y1 = plotymin+float(y1-ymin)*yfactor x2 = plotxmin+float(x2-xmin)*xfactor y2 = plotymin+float(y2-ymin)*yfactor self.plotline(x1, y1, x2, y2, attr, row) prev_x, prev_y = x, y for x, y, text, attr, row in Progress(self.gridlabels, 'labeling'): self.plotlabel(self.scaleX(x), self.scaleY(y), text, attr, row)
python
def render_sync(self): 'plots points and lines and text onto the Plotter' self.setZoom() bb = self.visibleBox xmin, ymin, xmax, ymax = bb.xmin, bb.ymin, bb.xmax, bb.ymax xfactor, yfactor = self.xScaler, self.yScaler plotxmin, plotymin = self.plotviewBox.xmin, self.plotviewBox.ymin for vertexes, attr, row in Progress(self.polylines, 'rendering'): if len(vertexes) == 1: # single point x1, y1 = vertexes[0] x1, y1 = float(x1), float(y1) if xmin <= x1 <= xmax and ymin <= y1 <= ymax: x = plotxmin+(x1-xmin)*xfactor y = plotymin+(y1-ymin)*yfactor self.plotpixel(round(x), round(y), attr, row) continue prev_x, prev_y = vertexes[0] for x, y in vertexes[1:]: r = clipline(prev_x, prev_y, x, y, xmin, ymin, xmax, ymax) if r: x1, y1, x2, y2 = r x1 = plotxmin+float(x1-xmin)*xfactor y1 = plotymin+float(y1-ymin)*yfactor x2 = plotxmin+float(x2-xmin)*xfactor y2 = plotymin+float(y2-ymin)*yfactor self.plotline(x1, y1, x2, y2, attr, row) prev_x, prev_y = x, y for x, y, text, attr, row in Progress(self.gridlabels, 'labeling'): self.plotlabel(self.scaleX(x), self.scaleY(y), text, attr, row)
[ "def", "render_sync", "(", "self", ")", ":", "self", ".", "setZoom", "(", ")", "bb", "=", "self", ".", "visibleBox", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", "=", "bb", ".", "xmin", ",", "bb", ".", "ymin", ",", "bb", ".", "xmax", ",", "bb...
plots points and lines and text onto the Plotter
[ "plots", "points", "and", "lines", "and", "text", "onto", "the", "Plotter" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/canvas.py#L594-L626
229,807
saulpw/visidata
visidata/movement.py
nextColRegex
def nextColRegex(sheet, colregex): 'Go to first visible column after the cursor matching `colregex`.' pivot = sheet.cursorVisibleColIndex for i in itertools.chain(range(pivot+1, len(sheet.visibleCols)), range(0, pivot+1)): c = sheet.visibleCols[i] if re.search(colregex, c.name, regex_flags()): return i fail('no column name matches /%s/' % colregex)
python
def nextColRegex(sheet, colregex): 'Go to first visible column after the cursor matching `colregex`.' pivot = sheet.cursorVisibleColIndex for i in itertools.chain(range(pivot+1, len(sheet.visibleCols)), range(0, pivot+1)): c = sheet.visibleCols[i] if re.search(colregex, c.name, regex_flags()): return i fail('no column name matches /%s/' % colregex)
[ "def", "nextColRegex", "(", "sheet", ",", "colregex", ")", ":", "pivot", "=", "sheet", ".", "cursorVisibleColIndex", "for", "i", "in", "itertools", ".", "chain", "(", "range", "(", "pivot", "+", "1", ",", "len", "(", "sheet", ".", "visibleCols", ")", "...
Go to first visible column after the cursor matching `colregex`.
[ "Go", "to", "first", "visible", "column", "after", "the", "cursor", "matching", "colregex", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/movement.py#L47-L55
229,808
saulpw/visidata
visidata/movement.py
searchRegex
def searchRegex(vd, sheet, moveCursor=False, reverse=False, **kwargs): 'Set row index if moveCursor, otherwise return list of row indexes.' def findMatchingColumn(sheet, row, columns, func): 'Find column for which func matches the displayed value in this row' for c in columns: if func(c.getDisplayValue(row)): return c vd.searchContext.update(kwargs) regex = kwargs.get("regex") if regex: vd.searchContext["regex"] = re.compile(regex, regex_flags()) or error('invalid regex: %s' % regex) regex = vd.searchContext.get("regex") or fail("no regex") columns = vd.searchContext.get("columns") if columns == "cursorCol": columns = [sheet.cursorCol] elif columns == "visibleCols": columns = tuple(sheet.visibleCols) elif isinstance(columns, Column): columns = [columns] if not columns: error('bad columns') searchBackward = vd.searchContext.get("backward") if reverse: searchBackward = not searchBackward matchingRowIndexes = 0 for r in rotate_range(len(sheet.rows), sheet.cursorRowIndex, reverse=searchBackward): c = findMatchingColumn(sheet, sheet.rows[r], columns, regex.search) if c: if moveCursor: sheet.cursorRowIndex = r sheet.cursorVisibleColIndex = sheet.visibleCols.index(c) return else: matchingRowIndexes += 1 yield r status('%s matches for /%s/' % (matchingRowIndexes, regex.pattern))
python
def searchRegex(vd, sheet, moveCursor=False, reverse=False, **kwargs): 'Set row index if moveCursor, otherwise return list of row indexes.' def findMatchingColumn(sheet, row, columns, func): 'Find column for which func matches the displayed value in this row' for c in columns: if func(c.getDisplayValue(row)): return c vd.searchContext.update(kwargs) regex = kwargs.get("regex") if regex: vd.searchContext["regex"] = re.compile(regex, regex_flags()) or error('invalid regex: %s' % regex) regex = vd.searchContext.get("regex") or fail("no regex") columns = vd.searchContext.get("columns") if columns == "cursorCol": columns = [sheet.cursorCol] elif columns == "visibleCols": columns = tuple(sheet.visibleCols) elif isinstance(columns, Column): columns = [columns] if not columns: error('bad columns') searchBackward = vd.searchContext.get("backward") if reverse: searchBackward = not searchBackward matchingRowIndexes = 0 for r in rotate_range(len(sheet.rows), sheet.cursorRowIndex, reverse=searchBackward): c = findMatchingColumn(sheet, sheet.rows[r], columns, regex.search) if c: if moveCursor: sheet.cursorRowIndex = r sheet.cursorVisibleColIndex = sheet.visibleCols.index(c) return else: matchingRowIndexes += 1 yield r status('%s matches for /%s/' % (matchingRowIndexes, regex.pattern))
[ "def", "searchRegex", "(", "vd", ",", "sheet", ",", "moveCursor", "=", "False", ",", "reverse", "=", "False", ",", "*", "*", "kwargs", ")", ":", "def", "findMatchingColumn", "(", "sheet", ",", "row", ",", "columns", ",", "func", ")", ":", "'Find column...
Set row index if moveCursor, otherwise return list of row indexes.
[ "Set", "row", "index", "if", "moveCursor", "otherwise", "return", "list", "of", "row", "indexes", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/movement.py#L64-L107
229,809
saulpw/visidata
visidata/vdtui.py
clipstr
def clipstr(s, dispw): '''Return clipped string and width in terminal display characters. Note: width may differ from len(s) if East Asian chars are 'fullwidth'.''' w = 0 ret = '' ambig_width = options.disp_ambig_width for c in s: if c != ' ' and unicodedata.category(c) in ('Cc', 'Zs', 'Zl'): # control char, space, line sep c = options.disp_oddspace if c: c = c[0] # multi-char disp_oddspace just uses the first char ret += c eaw = unicodedata.east_asian_width(c) if eaw == 'A': # ambiguous w += ambig_width elif eaw in 'WF': # wide/full w += 2 elif not unicodedata.combining(c): w += 1 if w > dispw-len(options.disp_truncator)+1: ret = ret[:-2] + options.disp_truncator # replace final char with ellipsis w += len(options.disp_truncator) break return ret, w
python
def clipstr(s, dispw): '''Return clipped string and width in terminal display characters. Note: width may differ from len(s) if East Asian chars are 'fullwidth'.''' w = 0 ret = '' ambig_width = options.disp_ambig_width for c in s: if c != ' ' and unicodedata.category(c) in ('Cc', 'Zs', 'Zl'): # control char, space, line sep c = options.disp_oddspace if c: c = c[0] # multi-char disp_oddspace just uses the first char ret += c eaw = unicodedata.east_asian_width(c) if eaw == 'A': # ambiguous w += ambig_width elif eaw in 'WF': # wide/full w += 2 elif not unicodedata.combining(c): w += 1 if w > dispw-len(options.disp_truncator)+1: ret = ret[:-2] + options.disp_truncator # replace final char with ellipsis w += len(options.disp_truncator) break return ret, w
[ "def", "clipstr", "(", "s", ",", "dispw", ")", ":", "w", "=", "0", "ret", "=", "''", "ambig_width", "=", "options", ".", "disp_ambig_width", "for", "c", "in", "s", ":", "if", "c", "!=", "' '", "and", "unicodedata", ".", "category", "(", "c", ")", ...
Return clipped string and width in terminal display characters. Note: width may differ from len(s) if East Asian chars are 'fullwidth'.
[ "Return", "clipped", "string", "and", "width", "in", "terminal", "display", "characters", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2430-L2457
229,810
saulpw/visidata
visidata/vdtui.py
cursesMain
def cursesMain(_scr, sheetlist): 'Populate VisiData object with sheets from a given list.' colors.setup() for vs in sheetlist: vd().push(vs) # first push does a reload status('Ctrl+H opens help') return vd().run(_scr)
python
def cursesMain(_scr, sheetlist): 'Populate VisiData object with sheets from a given list.' colors.setup() for vs in sheetlist: vd().push(vs) # first push does a reload status('Ctrl+H opens help') return vd().run(_scr)
[ "def", "cursesMain", "(", "_scr", ",", "sheetlist", ")", ":", "colors", ".", "setup", "(", ")", "for", "vs", "in", "sheetlist", ":", "vd", "(", ")", ".", "push", "(", "vs", ")", "# first push does a reload", "status", "(", "'Ctrl+H opens help'", ")", "re...
Populate VisiData object with sheets from a given list.
[ "Populate", "VisiData", "object", "with", "sheets", "from", "a", "given", "list", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2845-L2854
229,811
saulpw/visidata
visidata/vdtui.py
SettingsMgr.iter
def iter(self, obj=None): 'Iterate through all keys considering context of obj. If obj is None, uses the context of the top sheet.' if obj is None and vd: obj = vd.sheet for o in self._mappings(obj): for k in self.keys(): for o2 in self[k]: if o == o2: yield (k, o), self[k][o2]
python
def iter(self, obj=None): 'Iterate through all keys considering context of obj. If obj is None, uses the context of the top sheet.' if obj is None and vd: obj = vd.sheet for o in self._mappings(obj): for k in self.keys(): for o2 in self[k]: if o == o2: yield (k, o), self[k][o2]
[ "def", "iter", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", "and", "vd", ":", "obj", "=", "vd", ".", "sheet", "for", "o", "in", "self", ".", "_mappings", "(", "obj", ")", ":", "for", "k", "in", "self", ".", "keys...
Iterate through all keys considering context of obj. If obj is None, uses the context of the top sheet.
[ "Iterate", "through", "all", "keys", "considering", "context", "of", "obj", ".", "If", "obj", "is", "None", "uses", "the", "context", "of", "the", "top", "sheet", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L123-L132
229,812
saulpw/visidata
visidata/vdtui.py
VisiData.status
def status(self, *args, priority=0): 'Add status message to be shown until next action.' k = (priority, args) self.statuses[k] = self.statuses.get(k, 0) + 1 if self.statusHistory: prevpri, prevargs, prevn = self.statusHistory[-1] if prevpri == priority and prevargs == args: self.statusHistory[-1][2] += 1 return True self.statusHistory.append([priority, args, 1]) return True
python
def status(self, *args, priority=0): 'Add status message to be shown until next action.' k = (priority, args) self.statuses[k] = self.statuses.get(k, 0) + 1 if self.statusHistory: prevpri, prevargs, prevn = self.statusHistory[-1] if prevpri == priority and prevargs == args: self.statusHistory[-1][2] += 1 return True self.statusHistory.append([priority, args, 1]) return True
[ "def", "status", "(", "self", ",", "*", "args", ",", "priority", "=", "0", ")", ":", "k", "=", "(", "priority", ",", "args", ")", "self", ".", "statuses", "[", "k", "]", "=", "self", ".", "statuses", ".", "get", "(", "k", ",", "0", ")", "+", ...
Add status message to be shown until next action.
[ "Add", "status", "message", "to", "be", "shown", "until", "next", "action", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L590-L602
229,813
saulpw/visidata
visidata/vdtui.py
VisiData.callHook
def callHook(self, hookname, *args, **kwargs): 'Call all functions registered with `addHook` for the given hookname.' r = [] for f in self.hooks[hookname]: try: r.append(f(*args, **kwargs)) except Exception as e: exceptionCaught(e) return r
python
def callHook(self, hookname, *args, **kwargs): 'Call all functions registered with `addHook` for the given hookname.' r = [] for f in self.hooks[hookname]: try: r.append(f(*args, **kwargs)) except Exception as e: exceptionCaught(e) return r
[ "def", "callHook", "(", "self", ",", "hookname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "r", "=", "[", "]", "for", "f", "in", "self", ".", "hooks", "[", "hookname", "]", ":", "try", ":", "r", ".", "append", "(", "f", "(", "*", ...
Call all functions registered with `addHook` for the given hookname.
[ "Call", "all", "functions", "registered", "with", "addHook", "for", "the", "given", "hookname", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L608-L616
229,814
saulpw/visidata
visidata/vdtui.py
VisiData.checkForFinishedThreads
def checkForFinishedThreads(self): 'Mark terminated threads with endTime.' for t in self.unfinishedThreads: if not t.is_alive(): t.endTime = time.process_time() if getattr(t, 'status', None) is None: t.status = 'ended'
python
def checkForFinishedThreads(self): 'Mark terminated threads with endTime.' for t in self.unfinishedThreads: if not t.is_alive(): t.endTime = time.process_time() if getattr(t, 'status', None) is None: t.status = 'ended'
[ "def", "checkForFinishedThreads", "(", "self", ")", ":", "for", "t", "in", "self", ".", "unfinishedThreads", ":", "if", "not", "t", ".", "is_alive", "(", ")", ":", "t", ".", "endTime", "=", "time", ".", "process_time", "(", ")", "if", "getattr", "(", ...
Mark terminated threads with endTime.
[ "Mark", "terminated", "threads", "with", "endTime", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L667-L673
229,815
saulpw/visidata
visidata/vdtui.py
VisiData.sync
def sync(self, expectedThreads=0): 'Wait for all but expectedThreads async threads to finish.' while len(self.unfinishedThreads) > expectedThreads: time.sleep(.3) self.checkForFinishedThreads()
python
def sync(self, expectedThreads=0): 'Wait for all but expectedThreads async threads to finish.' while len(self.unfinishedThreads) > expectedThreads: time.sleep(.3) self.checkForFinishedThreads()
[ "def", "sync", "(", "self", ",", "expectedThreads", "=", "0", ")", ":", "while", "len", "(", "self", ".", "unfinishedThreads", ")", ">", "expectedThreads", ":", "time", ".", "sleep", "(", ".3", ")", "self", ".", "checkForFinishedThreads", "(", ")" ]
Wait for all but expectedThreads async threads to finish.
[ "Wait", "for", "all", "but", "expectedThreads", "async", "threads", "to", "finish", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L675-L679
229,816
saulpw/visidata
visidata/vdtui.py
VisiData.editText
def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: v = v[0] if kwargs.get('display', True): status('"%s"' % v) self.callHook('postedit', v) if record else None return v
python
def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: v = v[0] if kwargs.get('display', True): status('"%s"' % v) self.callHook('postedit', v) if record else None return v
[ "def", "editText", "(", "self", ",", "y", ",", "x", ",", "w", ",", "record", "=", "True", ",", "*", "*", "kwargs", ")", ":", "v", "=", "self", ".", "callHook", "(", "'preedit'", ")", "if", "record", "else", "None", "if", "not", "v", "or", "v", ...
Wrap global editText with `preedit` and `postedit` hooks.
[ "Wrap", "global", "editText", "with", "preedit", "and", "postedit", "hooks", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L687-L699
229,817
saulpw/visidata
visidata/vdtui.py
VisiData.input
def input(self, prompt, type='', defaultLast=False, **kwargs): 'Get user input, with history of `type`, defaulting to last history item if no input and defaultLast is True.' if type: histlist = list(self.lastInputs[type].keys()) ret = self._inputLine(prompt, history=histlist, **kwargs) if ret: self.lastInputs[type][ret] = ret elif defaultLast: histlist or fail("no previous input") ret = histlist[-1] else: ret = self._inputLine(prompt, **kwargs) return ret
python
def input(self, prompt, type='', defaultLast=False, **kwargs): 'Get user input, with history of `type`, defaulting to last history item if no input and defaultLast is True.' if type: histlist = list(self.lastInputs[type].keys()) ret = self._inputLine(prompt, history=histlist, **kwargs) if ret: self.lastInputs[type][ret] = ret elif defaultLast: histlist or fail("no previous input") ret = histlist[-1] else: ret = self._inputLine(prompt, **kwargs) return ret
[ "def", "input", "(", "self", ",", "prompt", ",", "type", "=", "''", ",", "defaultLast", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "type", ":", "histlist", "=", "list", "(", "self", ".", "lastInputs", "[", "type", "]", ".", "keys", "(...
Get user input, with history of `type`, defaulting to last history item if no input and defaultLast is True.
[ "Get", "user", "input", "with", "history", "of", "type", "defaulting", "to", "last", "history", "item", "if", "no", "input", "and", "defaultLast", "is", "True", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L701-L714
229,818
saulpw/visidata
visidata/vdtui.py
VisiData._inputLine
def _inputLine(self, prompt, **kwargs): 'Add prompt to bottom of screen and get line of input from user.' self.inInput = True rstatuslen = self.drawRightStatus(self.scr, self.sheets[0]) attr = 0 promptlen = clipdraw(self.scr, self.windowHeight-1, 0, prompt, attr, w=self.windowWidth-rstatuslen-1) ret = self.editText(self.windowHeight-1, promptlen, self.windowWidth-promptlen-rstatuslen-2, attr=colors.color_edit_cell, unprintablechar=options.disp_unprintable, truncchar=options.disp_truncator, **kwargs) self.inInput = False return ret
python
def _inputLine(self, prompt, **kwargs): 'Add prompt to bottom of screen and get line of input from user.' self.inInput = True rstatuslen = self.drawRightStatus(self.scr, self.sheets[0]) attr = 0 promptlen = clipdraw(self.scr, self.windowHeight-1, 0, prompt, attr, w=self.windowWidth-rstatuslen-1) ret = self.editText(self.windowHeight-1, promptlen, self.windowWidth-promptlen-rstatuslen-2, attr=colors.color_edit_cell, unprintablechar=options.disp_unprintable, truncchar=options.disp_truncator, **kwargs) self.inInput = False return ret
[ "def", "_inputLine", "(", "self", ",", "prompt", ",", "*", "*", "kwargs", ")", ":", "self", ".", "inInput", "=", "True", "rstatuslen", "=", "self", ".", "drawRightStatus", "(", "self", ".", "scr", ",", "self", ".", "sheets", "[", "0", "]", ")", "at...
Add prompt to bottom of screen and get line of input from user.
[ "Add", "prompt", "to", "bottom", "of", "screen", "and", "get", "line", "of", "input", "from", "user", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L716-L728
229,819
saulpw/visidata
visidata/vdtui.py
VisiData.getkeystroke
def getkeystroke(self, scr, vs=None): 'Get keystroke and display it on status bar.' k = None try: k = scr.get_wch() self.drawRightStatus(scr, vs or self.sheets[0]) # continue to display progress % except curses.error: return '' # curses timeout if isinstance(k, str): if ord(k) >= 32 and ord(k) != 127: # 127 == DEL or ^? return k k = ord(k) return curses.keyname(k).decode('utf-8')
python
def getkeystroke(self, scr, vs=None): 'Get keystroke and display it on status bar.' k = None try: k = scr.get_wch() self.drawRightStatus(scr, vs or self.sheets[0]) # continue to display progress % except curses.error: return '' # curses timeout if isinstance(k, str): if ord(k) >= 32 and ord(k) != 127: # 127 == DEL or ^? return k k = ord(k) return curses.keyname(k).decode('utf-8')
[ "def", "getkeystroke", "(", "self", ",", "scr", ",", "vs", "=", "None", ")", ":", "k", "=", "None", "try", ":", "k", "=", "scr", ".", "get_wch", "(", ")", "self", ".", "drawRightStatus", "(", "scr", ",", "vs", "or", "self", ".", "sheets", "[", ...
Get keystroke and display it on status bar.
[ "Get", "keystroke", "and", "display", "it", "on", "status", "bar", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L730-L743
229,820
saulpw/visidata
visidata/vdtui.py
VisiData.exceptionCaught
def exceptionCaught(self, exc=None, **kwargs): 'Maintain list of most recent errors and return most recent one.' if isinstance(exc, ExpectedException): # already reported, don't log return self.lastErrors.append(stacktrace()) if kwargs.get('status', True): status(self.lastErrors[-1][-1], priority=2) # last line of latest error if options.debug: raise
python
def exceptionCaught(self, exc=None, **kwargs): 'Maintain list of most recent errors and return most recent one.' if isinstance(exc, ExpectedException): # already reported, don't log return self.lastErrors.append(stacktrace()) if kwargs.get('status', True): status(self.lastErrors[-1][-1], priority=2) # last line of latest error if options.debug: raise
[ "def", "exceptionCaught", "(", "self", ",", "exc", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "exc", ",", "ExpectedException", ")", ":", "# already reported, don't log", "return", "self", ".", "lastErrors", ".", "append", "(", ...
Maintain list of most recent errors and return most recent one.
[ "Maintain", "list", "of", "most", "recent", "errors", "and", "return", "most", "recent", "one", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L745-L753
229,821
saulpw/visidata
visidata/vdtui.py
VisiData.drawLeftStatus
def drawLeftStatus(self, scr, vs): 'Draw left side of status bar.' cattr = CursesAttr(colors.color_status) attr = cattr.attr error_attr = cattr.update_attr(colors.color_error, 1).attr warn_attr = cattr.update_attr(colors.color_warning, 2).attr sep = options.disp_status_sep try: lstatus = vs.leftStatus() maxwidth = options.disp_lstatus_max if maxwidth > 0: lstatus = middleTruncate(lstatus, maxwidth//2) y = self.windowHeight-1 x = clipdraw(scr, y, 0, lstatus, attr) self.onMouse(scr, y, 0, 1, x, BUTTON1_PRESSED='sheets', BUTTON3_PRESSED='rename-sheet', BUTTON3_CLICKED='rename-sheet') one = False for (pri, msgparts), n in sorted(self.statuses.items(), key=lambda k: -k[0][0]): if x > self.windowWidth: break if one: # any messages already: x += clipdraw(scr, y, x, sep, attr, self.windowWidth) one = True msg = composeStatus(msgparts, n) if pri == 3: msgattr = error_attr elif pri == 2: msgattr = warn_attr elif pri == 1: msgattr = warn_attr else: msgattr = attr x += clipdraw(scr, y, x, msg, msgattr, self.windowWidth) except Exception as e: self.exceptionCaught(e)
python
def drawLeftStatus(self, scr, vs): 'Draw left side of status bar.' cattr = CursesAttr(colors.color_status) attr = cattr.attr error_attr = cattr.update_attr(colors.color_error, 1).attr warn_attr = cattr.update_attr(colors.color_warning, 2).attr sep = options.disp_status_sep try: lstatus = vs.leftStatus() maxwidth = options.disp_lstatus_max if maxwidth > 0: lstatus = middleTruncate(lstatus, maxwidth//2) y = self.windowHeight-1 x = clipdraw(scr, y, 0, lstatus, attr) self.onMouse(scr, y, 0, 1, x, BUTTON1_PRESSED='sheets', BUTTON3_PRESSED='rename-sheet', BUTTON3_CLICKED='rename-sheet') one = False for (pri, msgparts), n in sorted(self.statuses.items(), key=lambda k: -k[0][0]): if x > self.windowWidth: break if one: # any messages already: x += clipdraw(scr, y, x, sep, attr, self.windowWidth) one = True msg = composeStatus(msgparts, n) if pri == 3: msgattr = error_attr elif pri == 2: msgattr = warn_attr elif pri == 1: msgattr = warn_attr else: msgattr = attr x += clipdraw(scr, y, x, msg, msgattr, self.windowWidth) except Exception as e: self.exceptionCaught(e)
[ "def", "drawLeftStatus", "(", "self", ",", "scr", ",", "vs", ")", ":", "cattr", "=", "CursesAttr", "(", "colors", ".", "color_status", ")", "attr", "=", "cattr", ".", "attr", "error_attr", "=", "cattr", ".", "update_attr", "(", "colors", ".", "color_erro...
Draw left side of status bar.
[ "Draw", "left", "side", "of", "status", "bar", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L763-L799
229,822
saulpw/visidata
visidata/vdtui.py
VisiData.drawRightStatus
def drawRightStatus(self, scr, vs): 'Draw right side of status bar. Return length displayed.' rightx = self.windowWidth-1 ret = 0 for rstatcolor in self.callHook('rstatus', vs): if rstatcolor: try: rstatus, coloropt = rstatcolor rstatus = ' '+rstatus attr = colors.get_color(coloropt).attr statuslen = clipdraw(scr, self.windowHeight-1, rightx, rstatus, attr, rtl=True) rightx -= statuslen ret += statuslen except Exception as e: self.exceptionCaught(e) if scr: curses.doupdate() return ret
python
def drawRightStatus(self, scr, vs): 'Draw right side of status bar. Return length displayed.' rightx = self.windowWidth-1 ret = 0 for rstatcolor in self.callHook('rstatus', vs): if rstatcolor: try: rstatus, coloropt = rstatcolor rstatus = ' '+rstatus attr = colors.get_color(coloropt).attr statuslen = clipdraw(scr, self.windowHeight-1, rightx, rstatus, attr, rtl=True) rightx -= statuslen ret += statuslen except Exception as e: self.exceptionCaught(e) if scr: curses.doupdate() return ret
[ "def", "drawRightStatus", "(", "self", ",", "scr", ",", "vs", ")", ":", "rightx", "=", "self", ".", "windowWidth", "-", "1", "ret", "=", "0", "for", "rstatcolor", "in", "self", ".", "callHook", "(", "'rstatus'", ",", "vs", ")", ":", "if", "rstatcolor...
Draw right side of status bar. Return length displayed.
[ "Draw", "right", "side", "of", "status", "bar", ".", "Return", "length", "displayed", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L801-L820
229,823
saulpw/visidata
visidata/vdtui.py
VisiData.rightStatus
def rightStatus(self, sheet): 'Compose right side of status bar.' if sheet.currentThreads: gerund = (' '+sheet.progresses[0].gerund) if sheet.progresses else '' status = '%9d %2d%%%s' % (len(sheet), sheet.progressPct, gerund) else: status = '%9d %s' % (len(sheet), sheet.rowtype) return status, 'color_status'
python
def rightStatus(self, sheet): 'Compose right side of status bar.' if sheet.currentThreads: gerund = (' '+sheet.progresses[0].gerund) if sheet.progresses else '' status = '%9d %2d%%%s' % (len(sheet), sheet.progressPct, gerund) else: status = '%9d %s' % (len(sheet), sheet.rowtype) return status, 'color_status'
[ "def", "rightStatus", "(", "self", ",", "sheet", ")", ":", "if", "sheet", ".", "currentThreads", ":", "gerund", "=", "(", "' '", "+", "sheet", ".", "progresses", "[", "0", "]", ".", "gerund", ")", "if", "sheet", ".", "progresses", "else", "''", "stat...
Compose right side of status bar.
[ "Compose", "right", "side", "of", "status", "bar", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L822-L829
229,824
saulpw/visidata
visidata/vdtui.py
VisiData.run
def run(self, scr): 'Manage execution of keystrokes and subsequent redrawing of screen.' global sheet scr.timeout(int(options.curses_timeout)) with suppress(curses.error): curses.curs_set(0) self.scr = scr numTimeouts = 0 self.keystrokes = '' while True: if not self.sheets: # if no more sheets, exit return sheet = self.sheets[0] threading.current_thread().sheet = sheet try: sheet.draw(scr) except Exception as e: self.exceptionCaught(e) self.drawLeftStatus(scr, sheet) self.drawRightStatus(scr, sheet) # visible during this getkeystroke keystroke = self.getkeystroke(scr, sheet) if keystroke: # wait until next keystroke to clear statuses and previous keystrokes numTimeouts = 0 if not self.prefixWaiting: self.keystrokes = '' self.statuses.clear() if keystroke == 'KEY_MOUSE': self.keystrokes = '' clicktype = '' try: devid, x, y, z, bstate = curses.getmouse() sheet.mouseX, sheet.mouseY = x, y if bstate & curses.BUTTON_CTRL: clicktype += "CTRL-" bstate &= ~curses.BUTTON_CTRL if bstate & curses.BUTTON_ALT: clicktype += "ALT-" bstate &= ~curses.BUTTON_ALT if bstate & curses.BUTTON_SHIFT: clicktype += "SHIFT-" bstate &= ~curses.BUTTON_SHIFT keystroke = clicktype + curses.mouseEvents.get(bstate, str(bstate)) f = self.getMouse(scr, x, y, keystroke) if f: if isinstance(f, str): for cmd in f.split(): sheet.exec_keystrokes(cmd) else: f(y, x, keystroke) self.keystrokes = keystroke keystroke = '' except curses.error: pass except Exception as e: exceptionCaught(e) self.keystrokes += keystroke self.drawRightStatus(scr, sheet) # visible for commands that wait for input if not keystroke: # timeout instead of keypress pass elif keystroke == '^Q': return self.lastErrors and '\n'.join(self.lastErrors[-1]) elif bindkeys._get(self.keystrokes): sheet.exec_keystrokes(self.keystrokes) self.prefixWaiting = False elif keystroke in self.allPrefixes: self.keystrokes = ''.join(sorted(set(self.keystrokes))) # prefix order/quantity does not matter self.prefixWaiting = True else: status('no command for "%s"' % (self.keystrokes)) self.prefixWaiting = False self.checkForFinishedThreads() self.callHook('predraw') catchapply(sheet.checkCursor) # no idle redraw unless background threads are running time.sleep(0) # yield to other threads which may not have started yet if vd.unfinishedThreads: scr.timeout(options.curses_timeout) else: numTimeouts += 1 if numTimeouts > 1: scr.timeout(-1) else: scr.timeout(options.curses_timeout)
python
def run(self, scr): 'Manage execution of keystrokes and subsequent redrawing of screen.' global sheet scr.timeout(int(options.curses_timeout)) with suppress(curses.error): curses.curs_set(0) self.scr = scr numTimeouts = 0 self.keystrokes = '' while True: if not self.sheets: # if no more sheets, exit return sheet = self.sheets[0] threading.current_thread().sheet = sheet try: sheet.draw(scr) except Exception as e: self.exceptionCaught(e) self.drawLeftStatus(scr, sheet) self.drawRightStatus(scr, sheet) # visible during this getkeystroke keystroke = self.getkeystroke(scr, sheet) if keystroke: # wait until next keystroke to clear statuses and previous keystrokes numTimeouts = 0 if not self.prefixWaiting: self.keystrokes = '' self.statuses.clear() if keystroke == 'KEY_MOUSE': self.keystrokes = '' clicktype = '' try: devid, x, y, z, bstate = curses.getmouse() sheet.mouseX, sheet.mouseY = x, y if bstate & curses.BUTTON_CTRL: clicktype += "CTRL-" bstate &= ~curses.BUTTON_CTRL if bstate & curses.BUTTON_ALT: clicktype += "ALT-" bstate &= ~curses.BUTTON_ALT if bstate & curses.BUTTON_SHIFT: clicktype += "SHIFT-" bstate &= ~curses.BUTTON_SHIFT keystroke = clicktype + curses.mouseEvents.get(bstate, str(bstate)) f = self.getMouse(scr, x, y, keystroke) if f: if isinstance(f, str): for cmd in f.split(): sheet.exec_keystrokes(cmd) else: f(y, x, keystroke) self.keystrokes = keystroke keystroke = '' except curses.error: pass except Exception as e: exceptionCaught(e) self.keystrokes += keystroke self.drawRightStatus(scr, sheet) # visible for commands that wait for input if not keystroke: # timeout instead of keypress pass elif keystroke == '^Q': return self.lastErrors and '\n'.join(self.lastErrors[-1]) elif bindkeys._get(self.keystrokes): sheet.exec_keystrokes(self.keystrokes) self.prefixWaiting = False elif keystroke in self.allPrefixes: self.keystrokes = ''.join(sorted(set(self.keystrokes))) # prefix order/quantity does not matter self.prefixWaiting = True else: status('no command for "%s"' % (self.keystrokes)) self.prefixWaiting = False self.checkForFinishedThreads() self.callHook('predraw') catchapply(sheet.checkCursor) # no idle redraw unless background threads are running time.sleep(0) # yield to other threads which may not have started yet if vd.unfinishedThreads: scr.timeout(options.curses_timeout) else: numTimeouts += 1 if numTimeouts > 1: scr.timeout(-1) else: scr.timeout(options.curses_timeout)
[ "def", "run", "(", "self", ",", "scr", ")", ":", "global", "sheet", "scr", ".", "timeout", "(", "int", "(", "options", ".", "curses_timeout", ")", ")", "with", "suppress", "(", "curses", ".", "error", ")", ":", "curses", ".", "curs_set", "(", "0", ...
Manage execution of keystrokes and subsequent redrawing of screen.
[ "Manage", "execution", "of", "keystrokes", "and", "subsequent", "redrawing", "of", "screen", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L839-L939
229,825
saulpw/visidata
visidata/vdtui.py
VisiData.push
def push(self, vs): 'Move given sheet `vs` to index 0 of list `sheets`.' if vs: vs.vd = self if vs in self.sheets: self.sheets.remove(vs) self.sheets.insert(0, vs) elif not vs.loaded: self.sheets.insert(0, vs) vs.reload() vs.recalc() # set up Columns else: self.sheets.insert(0, vs) if vs.precious and vs not in vs.vd.allSheets: vs.vd.allSheets[vs] = vs.name return vs
python
def push(self, vs): 'Move given sheet `vs` to index 0 of list `sheets`.' if vs: vs.vd = self if vs in self.sheets: self.sheets.remove(vs) self.sheets.insert(0, vs) elif not vs.loaded: self.sheets.insert(0, vs) vs.reload() vs.recalc() # set up Columns else: self.sheets.insert(0, vs) if vs.precious and vs not in vs.vd.allSheets: vs.vd.allSheets[vs] = vs.name return vs
[ "def", "push", "(", "self", ",", "vs", ")", ":", "if", "vs", ":", "vs", ".", "vd", "=", "self", "if", "vs", "in", "self", ".", "sheets", ":", "self", ".", "sheets", ".", "remove", "(", "vs", ")", "self", ".", "sheets", ".", "insert", "(", "0"...
Move given sheet `vs` to index 0 of list `sheets`.
[ "Move", "given", "sheet", "vs", "to", "index", "0", "of", "list", "sheets", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L952-L968
229,826
saulpw/visidata
visidata/vdtui.py
BaseSheet.exec_command
def exec_command(self, cmd, args='', vdglobals=None, keystrokes=None): "Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled." global sheet sheet = vd.sheets[0] if not cmd: debug('no command "%s"' % keystrokes) return True if isinstance(cmd, CommandLog): cmd.replay() return False escaped = False err = '' if vdglobals is None: vdglobals = getGlobals() if not self.vd: self.vd = vd() self.sheet = self try: self.vd.callHook('preexec', self, cmd, '', keystrokes) exec(cmd.execstr, vdglobals, LazyMap(self)) except EscapeException as e: # user aborted status('aborted') escaped = True except Exception as e: debug(cmd.execstr) err = self.vd.exceptionCaught(e) escaped = True try: self.vd.callHook('postexec', self.vd.sheets[0] if self.vd.sheets else None, escaped, err) except Exception: self.vd.exceptionCaught(e) catchapply(self.checkCursor) self.vd.refresh() return escaped
python
def exec_command(self, cmd, args='', vdglobals=None, keystrokes=None): "Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled." global sheet sheet = vd.sheets[0] if not cmd: debug('no command "%s"' % keystrokes) return True if isinstance(cmd, CommandLog): cmd.replay() return False escaped = False err = '' if vdglobals is None: vdglobals = getGlobals() if not self.vd: self.vd = vd() self.sheet = self try: self.vd.callHook('preexec', self, cmd, '', keystrokes) exec(cmd.execstr, vdglobals, LazyMap(self)) except EscapeException as e: # user aborted status('aborted') escaped = True except Exception as e: debug(cmd.execstr) err = self.vd.exceptionCaught(e) escaped = True try: self.vd.callHook('postexec', self.vd.sheets[0] if self.vd.sheets else None, escaped, err) except Exception: self.vd.exceptionCaught(e) catchapply(self.checkCursor) self.vd.refresh() return escaped
[ "def", "exec_command", "(", "self", ",", "cmd", ",", "args", "=", "''", ",", "vdglobals", "=", "None", ",", "keystrokes", "=", "None", ")", ":", "global", "sheet", "sheet", "=", "vd", ".", "sheets", "[", "0", "]", "if", "not", "cmd", ":", "debug", ...
Execute `cmd` tuple with `vdglobals` as globals and this sheet's attributes as locals. Returns True if user cancelled.
[ "Execute", "cmd", "tuple", "with", "vdglobals", "as", "globals", "and", "this", "sheet", "s", "attributes", "as", "locals", ".", "Returns", "True", "if", "user", "cancelled", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1089-L1132
229,827
saulpw/visidata
visidata/vdtui.py
Sheet.column
def column(self, colregex): 'Return first column whose Column.name matches colregex.' for c in self.columns: if re.search(colregex, c.name, regex_flags()): return c
python
def column(self, colregex): 'Return first column whose Column.name matches colregex.' for c in self.columns: if re.search(colregex, c.name, regex_flags()): return c
[ "def", "column", "(", "self", ",", "colregex", ")", ":", "for", "c", "in", "self", ".", "columns", ":", "if", "re", ".", "search", "(", "colregex", ",", "c", ".", "name", ",", "regex_flags", "(", ")", ")", ":", "return", "c" ]
Return first column whose Column.name matches colregex.
[ "Return", "first", "column", "whose", "Column", ".", "name", "matches", "colregex", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1306-L1310
229,828
saulpw/visidata
visidata/vdtui.py
Sheet.deleteSelected
def deleteSelected(self): 'Delete all selected rows.' ndeleted = self.deleteBy(self.isSelected) nselected = len(self._selectedRows) self._selectedRows.clear() if ndeleted != nselected: error('expected %s' % nselected)
python
def deleteSelected(self): 'Delete all selected rows.' ndeleted = self.deleteBy(self.isSelected) nselected = len(self._selectedRows) self._selectedRows.clear() if ndeleted != nselected: error('expected %s' % nselected)
[ "def", "deleteSelected", "(", "self", ")", ":", "ndeleted", "=", "self", ".", "deleteBy", "(", "self", ".", "isSelected", ")", "nselected", "=", "len", "(", "self", ".", "_selectedRows", ")", "self", ".", "_selectedRows", ".", "clear", "(", ")", "if", ...
Delete all selected rows.
[ "Delete", "all", "selected", "rows", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1377-L1383
229,829
saulpw/visidata
visidata/vdtui.py
Sheet.visibleRows
def visibleRows(self): # onscreen rows 'List of rows onscreen. ' return self.rows[self.topRowIndex:self.topRowIndex+self.nVisibleRows]
python
def visibleRows(self): # onscreen rows 'List of rows onscreen. ' return self.rows[self.topRowIndex:self.topRowIndex+self.nVisibleRows]
[ "def", "visibleRows", "(", "self", ")", ":", "# onscreen rows", "return", "self", ".", "rows", "[", "self", ".", "topRowIndex", ":", "self", ".", "topRowIndex", "+", "self", ".", "nVisibleRows", "]" ]
List of rows onscreen.
[ "List", "of", "rows", "onscreen", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1418-L1420
229,830
saulpw/visidata
visidata/vdtui.py
Sheet.visibleCols
def visibleCols(self): # non-hidden cols 'List of `Column` which are not hidden.' return self.keyCols + [c for c in self.columns if not c.hidden and not c.keycol]
python
def visibleCols(self): # non-hidden cols 'List of `Column` which are not hidden.' return self.keyCols + [c for c in self.columns if not c.hidden and not c.keycol]
[ "def", "visibleCols", "(", "self", ")", ":", "# non-hidden cols", "return", "self", ".", "keyCols", "+", "[", "c", "for", "c", "in", "self", ".", "columns", "if", "not", "c", ".", "hidden", "and", "not", "c", ".", "keycol", "]" ]
List of `Column` which are not hidden.
[ "List", "of", "Column", "which", "are", "not", "hidden", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1424-L1426
229,831
saulpw/visidata
visidata/vdtui.py
Sheet.nonKeyVisibleCols
def nonKeyVisibleCols(self): 'All columns which are not keysList of unhidden non-key columns.' return [c for c in self.columns if not c.hidden and c not in self.keyCols]
python
def nonKeyVisibleCols(self): 'All columns which are not keysList of unhidden non-key columns.' return [c for c in self.columns if not c.hidden and c not in self.keyCols]
[ "def", "nonKeyVisibleCols", "(", "self", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "columns", "if", "not", "c", ".", "hidden", "and", "c", "not", "in", "self", ".", "keyCols", "]" ]
All columns which are not keysList of unhidden non-key columns.
[ "All", "columns", "which", "are", "not", "keysList", "of", "unhidden", "non", "-", "key", "columns", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1446-L1448
229,832
saulpw/visidata
visidata/vdtui.py
Sheet.statusLine
def statusLine(self): 'String of row and column stats.' rowinfo = 'row %d/%d (%d selected)' % (self.cursorRowIndex, self.nRows, len(self._selectedRows)) colinfo = 'col %d/%d (%d visible)' % (self.cursorColIndex, self.nCols, len(self.visibleCols)) return '%s %s' % (rowinfo, colinfo)
python
def statusLine(self): 'String of row and column stats.' rowinfo = 'row %d/%d (%d selected)' % (self.cursorRowIndex, self.nRows, len(self._selectedRows)) colinfo = 'col %d/%d (%d visible)' % (self.cursorColIndex, self.nCols, len(self.visibleCols)) return '%s %s' % (rowinfo, colinfo)
[ "def", "statusLine", "(", "self", ")", ":", "rowinfo", "=", "'row %d/%d (%d selected)'", "%", "(", "self", ".", "cursorRowIndex", ",", "self", ".", "nRows", ",", "len", "(", "self", ".", "_selectedRows", ")", ")", "colinfo", "=", "'col %d/%d (%d visible)'", ...
String of row and column stats.
[ "String", "of", "row", "and", "column", "stats", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1476-L1480
229,833
saulpw/visidata
visidata/vdtui.py
Sheet.toggle
def toggle(self, rows): 'Toggle selection of given `rows`.' for r in Progress(rows, 'toggling', total=len(self.rows)): if not self.unselectRow(r): self.selectRow(r)
python
def toggle(self, rows): 'Toggle selection of given `rows`.' for r in Progress(rows, 'toggling', total=len(self.rows)): if not self.unselectRow(r): self.selectRow(r)
[ "def", "toggle", "(", "self", ",", "rows", ")", ":", "for", "r", "in", "Progress", "(", "rows", ",", "'toggling'", ",", "total", "=", "len", "(", "self", ".", "rows", ")", ")", ":", "if", "not", "self", ".", "unselectRow", "(", "r", ")", ":", "...
Toggle selection of given `rows`.
[ "Toggle", "selection", "of", "given", "rows", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1503-L1507
229,834
saulpw/visidata
visidata/vdtui.py
Sheet.select
def select(self, rows, status=True, progress=True): "Bulk select given rows. Don't show progress if progress=False; don't show status if status=False." before = len(self._selectedRows) if options.bulk_select_clear: self._selectedRows.clear() for r in (Progress(rows, 'selecting') if progress else rows): self.selectRow(r) if status: if options.bulk_select_clear: msg = 'selected %s %s%s' % (len(self._selectedRows), self.rowtype, ' instead' if before > 0 else '') else: msg = 'selected %s%s %s' % (len(self._selectedRows)-before, ' more' if before > 0 else '', self.rowtype) vd.status(msg)
python
def select(self, rows, status=True, progress=True): "Bulk select given rows. Don't show progress if progress=False; don't show status if status=False." before = len(self._selectedRows) if options.bulk_select_clear: self._selectedRows.clear() for r in (Progress(rows, 'selecting') if progress else rows): self.selectRow(r) if status: if options.bulk_select_clear: msg = 'selected %s %s%s' % (len(self._selectedRows), self.rowtype, ' instead' if before > 0 else '') else: msg = 'selected %s%s %s' % (len(self._selectedRows)-before, ' more' if before > 0 else '', self.rowtype) vd.status(msg)
[ "def", "select", "(", "self", ",", "rows", ",", "status", "=", "True", ",", "progress", "=", "True", ")", ":", "before", "=", "len", "(", "self", ".", "_selectedRows", ")", "if", "options", ".", "bulk_select_clear", ":", "self", ".", "_selectedRows", "...
Bulk select given rows. Don't show progress if progress=False; don't show status if status=False.
[ "Bulk", "select", "given", "rows", ".", "Don", "t", "show", "progress", "if", "progress", "=", "False", ";", "don", "t", "show", "status", "if", "status", "=", "False", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1522-L1534
229,835
saulpw/visidata
visidata/vdtui.py
Sheet.unselect
def unselect(self, rows, status=True, progress=True): "Unselect given rows. Don't show progress if progress=False; don't show status if status=False." before = len(self._selectedRows) for r in (Progress(rows, 'unselecting') if progress else rows): self.unselectRow(r) if status: vd().status('unselected %s/%s %s' % (before-len(self._selectedRows), before, self.rowtype))
python
def unselect(self, rows, status=True, progress=True): "Unselect given rows. Don't show progress if progress=False; don't show status if status=False." before = len(self._selectedRows) for r in (Progress(rows, 'unselecting') if progress else rows): self.unselectRow(r) if status: vd().status('unselected %s/%s %s' % (before-len(self._selectedRows), before, self.rowtype))
[ "def", "unselect", "(", "self", ",", "rows", ",", "status", "=", "True", ",", "progress", "=", "True", ")", ":", "before", "=", "len", "(", "self", ".", "_selectedRows", ")", "for", "r", "in", "(", "Progress", "(", "rows", ",", "'unselecting'", ")", ...
Unselect given rows. Don't show progress if progress=False; don't show status if status=False.
[ "Unselect", "given", "rows", ".", "Don", "t", "show", "progress", "if", "progress", "=", "False", ";", "don", "t", "show", "status", "if", "status", "=", "False", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1537-L1543
229,836
saulpw/visidata
visidata/vdtui.py
Sheet.selectByIdx
def selectByIdx(self, rowIdxs): 'Select given row indexes, without progress bar.' self.select((self.rows[i] for i in rowIdxs), progress=False)
python
def selectByIdx(self, rowIdxs): 'Select given row indexes, without progress bar.' self.select((self.rows[i] for i in rowIdxs), progress=False)
[ "def", "selectByIdx", "(", "self", ",", "rowIdxs", ")", ":", "self", ".", "select", "(", "(", "self", ".", "rows", "[", "i", "]", "for", "i", "in", "rowIdxs", ")", ",", "progress", "=", "False", ")" ]
Select given row indexes, without progress bar.
[ "Select", "given", "row", "indexes", "without", "progress", "bar", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1545-L1547
229,837
saulpw/visidata
visidata/vdtui.py
Sheet.unselectByIdx
def unselectByIdx(self, rowIdxs): 'Unselect given row indexes, without progress bar.' self.unselect((self.rows[i] for i in rowIdxs), progress=False)
python
def unselectByIdx(self, rowIdxs): 'Unselect given row indexes, without progress bar.' self.unselect((self.rows[i] for i in rowIdxs), progress=False)
[ "def", "unselectByIdx", "(", "self", ",", "rowIdxs", ")", ":", "self", ".", "unselect", "(", "(", "self", ".", "rows", "[", "i", "]", "for", "i", "in", "rowIdxs", ")", ",", "progress", "=", "False", ")" ]
Unselect given row indexes, without progress bar.
[ "Unselect", "given", "row", "indexes", "without", "progress", "bar", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1549-L1551
229,838
saulpw/visidata
visidata/vdtui.py
Sheet.gatherBy
def gatherBy(self, func): 'Generate only rows for which the given func returns True.' for i in rotate_range(len(self.rows), self.cursorRowIndex): try: r = self.rows[i] if func(r): yield r except Exception: pass
python
def gatherBy(self, func): 'Generate only rows for which the given func returns True.' for i in rotate_range(len(self.rows), self.cursorRowIndex): try: r = self.rows[i] if func(r): yield r except Exception: pass
[ "def", "gatherBy", "(", "self", ",", "func", ")", ":", "for", "i", "in", "rotate_range", "(", "len", "(", "self", ".", "rows", ")", ",", "self", ".", "cursorRowIndex", ")", ":", "try", ":", "r", "=", "self", ".", "rows", "[", "i", "]", "if", "f...
Generate only rows for which the given func returns True.
[ "Generate", "only", "rows", "for", "which", "the", "given", "func", "returns", "True", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1553-L1561
229,839
saulpw/visidata
visidata/vdtui.py
Sheet.pageLeft
def pageLeft(self): '''Redraw page one screen to the left. Note: keep the column cursor in the same general relative position: - if it is on the furthest right column, then it should stay on the furthest right column if possible - likewise on the left or in the middle So really both the `leftIndex` and the `cursorIndex` should move in tandem until things are correct.''' targetIdx = self.leftVisibleColIndex # for rightmost column firstNonKeyVisibleColIndex = self.visibleCols.index(self.nonKeyVisibleCols[0]) while self.rightVisibleColIndex != targetIdx and self.leftVisibleColIndex > firstNonKeyVisibleColIndex: self.cursorVisibleColIndex -= 1 self.leftVisibleColIndex -= 1 self.calcColLayout() # recompute rightVisibleColIndex # in case that rightmost column is last column, try to squeeze maximum real estate from screen if self.rightVisibleColIndex == self.nVisibleCols-1: # try to move further left while right column is still full width while self.leftVisibleColIndex > 0: rightcol = self.visibleCols[self.rightVisibleColIndex] if rightcol.width > self.visibleColLayout[self.rightVisibleColIndex][1]: # went too far self.cursorVisibleColIndex += 1 self.leftVisibleColIndex += 1 break else: self.cursorVisibleColIndex -= 1 self.leftVisibleColIndex -= 1 self.calcColLayout()
python
def pageLeft(self): '''Redraw page one screen to the left. Note: keep the column cursor in the same general relative position: - if it is on the furthest right column, then it should stay on the furthest right column if possible - likewise on the left or in the middle So really both the `leftIndex` and the `cursorIndex` should move in tandem until things are correct.''' targetIdx = self.leftVisibleColIndex # for rightmost column firstNonKeyVisibleColIndex = self.visibleCols.index(self.nonKeyVisibleCols[0]) while self.rightVisibleColIndex != targetIdx and self.leftVisibleColIndex > firstNonKeyVisibleColIndex: self.cursorVisibleColIndex -= 1 self.leftVisibleColIndex -= 1 self.calcColLayout() # recompute rightVisibleColIndex # in case that rightmost column is last column, try to squeeze maximum real estate from screen if self.rightVisibleColIndex == self.nVisibleCols-1: # try to move further left while right column is still full width while self.leftVisibleColIndex > 0: rightcol = self.visibleCols[self.rightVisibleColIndex] if rightcol.width > self.visibleColLayout[self.rightVisibleColIndex][1]: # went too far self.cursorVisibleColIndex += 1 self.leftVisibleColIndex += 1 break else: self.cursorVisibleColIndex -= 1 self.leftVisibleColIndex -= 1 self.calcColLayout()
[ "def", "pageLeft", "(", "self", ")", ":", "targetIdx", "=", "self", ".", "leftVisibleColIndex", "# for rightmost column", "firstNonKeyVisibleColIndex", "=", "self", ".", "visibleCols", ".", "index", "(", "self", ".", "nonKeyVisibleCols", "[", "0", "]", ")", "whi...
Redraw page one screen to the left. Note: keep the column cursor in the same general relative position: - if it is on the furthest right column, then it should stay on the furthest right column if possible - likewise on the left or in the middle So really both the `leftIndex` and the `cursorIndex` should move in tandem until things are correct.
[ "Redraw", "page", "one", "screen", "to", "the", "left", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1591-L1624
229,840
saulpw/visidata
visidata/vdtui.py
Sheet.addColumn
def addColumn(self, col, index=None): 'Insert column at given index or after all columns.' if col: if index is None: index = len(self.columns) col.sheet = self self.columns.insert(index, col) return col
python
def addColumn(self, col, index=None): 'Insert column at given index or after all columns.' if col: if index is None: index = len(self.columns) col.sheet = self self.columns.insert(index, col) return col
[ "def", "addColumn", "(", "self", ",", "col", ",", "index", "=", "None", ")", ":", "if", "col", ":", "if", "index", "is", "None", ":", "index", "=", "len", "(", "self", ".", "columns", ")", "col", ".", "sheet", "=", "self", "self", ".", "columns",...
Insert column at given index or after all columns.
[ "Insert", "column", "at", "given", "index", "or", "after", "all", "columns", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1626-L1633
229,841
saulpw/visidata
visidata/vdtui.py
Sheet.rowkey
def rowkey(self, row): 'returns a tuple of the key for the given row' return tuple(c.getTypedValueOrException(row) for c in self.keyCols)
python
def rowkey(self, row): 'returns a tuple of the key for the given row' return tuple(c.getTypedValueOrException(row) for c in self.keyCols)
[ "def", "rowkey", "(", "self", ",", "row", ")", ":", "return", "tuple", "(", "c", ".", "getTypedValueOrException", "(", "row", ")", "for", "c", "in", "self", ".", "keyCols", ")" ]
returns a tuple of the key for the given row
[ "returns", "a", "tuple", "of", "the", "key", "for", "the", "given", "row" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1647-L1649
229,842
saulpw/visidata
visidata/vdtui.py
Sheet.checkCursor
def checkCursor(self): 'Keep cursor in bounds of data and screen.' # keep cursor within actual available rowset if self.nRows == 0 or self.cursorRowIndex <= 0: self.cursorRowIndex = 0 elif self.cursorRowIndex >= self.nRows: self.cursorRowIndex = self.nRows-1 if self.cursorVisibleColIndex <= 0: self.cursorVisibleColIndex = 0 elif self.cursorVisibleColIndex >= self.nVisibleCols: self.cursorVisibleColIndex = self.nVisibleCols-1 if self.topRowIndex <= 0: self.topRowIndex = 0 elif self.topRowIndex > self.nRows-1: self.topRowIndex = self.nRows-1 # (x,y) is relative cell within screen viewport x = self.cursorVisibleColIndex - self.leftVisibleColIndex y = self.cursorRowIndex - self.topRowIndex + 1 # header # check bounds, scroll if necessary if y < 1: self.topRowIndex = self.cursorRowIndex elif y > self.nVisibleRows: self.topRowIndex = self.cursorRowIndex-self.nVisibleRows+1 if x <= 0: self.leftVisibleColIndex = self.cursorVisibleColIndex else: while True: if self.leftVisibleColIndex == self.cursorVisibleColIndex: # not much more we can do break self.calcColLayout() mincolidx, maxcolidx = min(self.visibleColLayout.keys()), max(self.visibleColLayout.keys()) if self.cursorVisibleColIndex < mincolidx: self.leftVisibleColIndex -= max((self.cursorVisibleColIndex - mincolid)//2, 1) continue elif self.cursorVisibleColIndex > maxcolidx: self.leftVisibleColIndex += max((maxcolidx - self.cursorVisibleColIndex)//2, 1) continue cur_x, cur_w = self.visibleColLayout[self.cursorVisibleColIndex] if cur_x+cur_w < self.vd.windowWidth: # current columns fit entirely on screen break self.leftVisibleColIndex += 1
python
def checkCursor(self): 'Keep cursor in bounds of data and screen.' # keep cursor within actual available rowset if self.nRows == 0 or self.cursorRowIndex <= 0: self.cursorRowIndex = 0 elif self.cursorRowIndex >= self.nRows: self.cursorRowIndex = self.nRows-1 if self.cursorVisibleColIndex <= 0: self.cursorVisibleColIndex = 0 elif self.cursorVisibleColIndex >= self.nVisibleCols: self.cursorVisibleColIndex = self.nVisibleCols-1 if self.topRowIndex <= 0: self.topRowIndex = 0 elif self.topRowIndex > self.nRows-1: self.topRowIndex = self.nRows-1 # (x,y) is relative cell within screen viewport x = self.cursorVisibleColIndex - self.leftVisibleColIndex y = self.cursorRowIndex - self.topRowIndex + 1 # header # check bounds, scroll if necessary if y < 1: self.topRowIndex = self.cursorRowIndex elif y > self.nVisibleRows: self.topRowIndex = self.cursorRowIndex-self.nVisibleRows+1 if x <= 0: self.leftVisibleColIndex = self.cursorVisibleColIndex else: while True: if self.leftVisibleColIndex == self.cursorVisibleColIndex: # not much more we can do break self.calcColLayout() mincolidx, maxcolidx = min(self.visibleColLayout.keys()), max(self.visibleColLayout.keys()) if self.cursorVisibleColIndex < mincolidx: self.leftVisibleColIndex -= max((self.cursorVisibleColIndex - mincolid)//2, 1) continue elif self.cursorVisibleColIndex > maxcolidx: self.leftVisibleColIndex += max((maxcolidx - self.cursorVisibleColIndex)//2, 1) continue cur_x, cur_w = self.visibleColLayout[self.cursorVisibleColIndex] if cur_x+cur_w < self.vd.windowWidth: # current columns fit entirely on screen break self.leftVisibleColIndex += 1
[ "def", "checkCursor", "(", "self", ")", ":", "# keep cursor within actual available rowset", "if", "self", ".", "nRows", "==", "0", "or", "self", ".", "cursorRowIndex", "<=", "0", ":", "self", ".", "cursorRowIndex", "=", "0", "elif", "self", ".", "cursorRowInd...
Keep cursor in bounds of data and screen.
[ "Keep", "cursor", "in", "bounds", "of", "data", "and", "screen", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1651-L1697
229,843
saulpw/visidata
visidata/vdtui.py
Sheet.calcColLayout
def calcColLayout(self): 'Set right-most visible column, based on calculation.' minColWidth = len(options.disp_more_left)+len(options.disp_more_right) sepColWidth = len(options.disp_column_sep) winWidth = self.vd.windowWidth self.visibleColLayout = {} x = 0 vcolidx = 0 for vcolidx in range(0, self.nVisibleCols): col = self.visibleCols[vcolidx] if col.width is None and len(self.visibleRows) > 0: # handle delayed column width-finding col.width = col.getMaxWidth(self.visibleRows)+minColWidth if vcolidx != self.nVisibleCols-1: # let last column fill up the max width col.width = min(col.width, options.default_width) width = col.width if col.width is not None else options.default_width if col in self.keyCols: width = max(width, 1) # keycols must all be visible if col in self.keyCols or vcolidx >= self.leftVisibleColIndex: # visible columns self.visibleColLayout[vcolidx] = [x, min(width, winWidth-x)] x += width+sepColWidth if x > winWidth-1: break self.rightVisibleColIndex = vcolidx
python
def calcColLayout(self): 'Set right-most visible column, based on calculation.' minColWidth = len(options.disp_more_left)+len(options.disp_more_right) sepColWidth = len(options.disp_column_sep) winWidth = self.vd.windowWidth self.visibleColLayout = {} x = 0 vcolidx = 0 for vcolidx in range(0, self.nVisibleCols): col = self.visibleCols[vcolidx] if col.width is None and len(self.visibleRows) > 0: # handle delayed column width-finding col.width = col.getMaxWidth(self.visibleRows)+minColWidth if vcolidx != self.nVisibleCols-1: # let last column fill up the max width col.width = min(col.width, options.default_width) width = col.width if col.width is not None else options.default_width if col in self.keyCols: width = max(width, 1) # keycols must all be visible if col in self.keyCols or vcolidx >= self.leftVisibleColIndex: # visible columns self.visibleColLayout[vcolidx] = [x, min(width, winWidth-x)] x += width+sepColWidth if x > winWidth-1: break self.rightVisibleColIndex = vcolidx
[ "def", "calcColLayout", "(", "self", ")", ":", "minColWidth", "=", "len", "(", "options", ".", "disp_more_left", ")", "+", "len", "(", "options", ".", "disp_more_right", ")", "sepColWidth", "=", "len", "(", "options", ".", "disp_column_sep", ")", "winWidth",...
Set right-most visible column, based on calculation.
[ "Set", "right", "-", "most", "visible", "column", "based", "on", "calculation", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1699-L1723
229,844
saulpw/visidata
visidata/vdtui.py
Sheet.drawColHeader
def drawColHeader(self, scr, y, vcolidx): 'Compose and draw column header for given vcolidx.' col = self.visibleCols[vcolidx] # hdrattr highlights whole column header # sepattr is for header separators and indicators sepattr = colors.color_column_sep hdrattr = self.colorize(col, None) if vcolidx == self.cursorVisibleColIndex: hdrattr = hdrattr.update_attr(colors.color_current_hdr, 2) C = options.disp_column_sep if (self.keyCols and col is self.keyCols[-1]) or vcolidx == self.rightVisibleColIndex: C = options.disp_keycol_sep x, colwidth = self.visibleColLayout[vcolidx] # ANameTC T = getType(col.type).icon if T is None: # still allow icon to be explicitly non-displayed '' T = '?' N = ' ' + col.name # save room at front for LeftMore if len(N) > colwidth-1: N = N[:colwidth-len(options.disp_truncator)] + options.disp_truncator clipdraw(scr, y, x, N, hdrattr.attr, colwidth) clipdraw(scr, y, x+colwidth-len(T), T, hdrattr.attr, len(T)) vd.onMouse(scr, y, x, 1, colwidth, BUTTON3_RELEASED='rename-col') if vcolidx == self.leftVisibleColIndex and col not in self.keyCols and self.nonKeyVisibleCols.index(col) > 0: A = options.disp_more_left scr.addstr(y, x, A, sepattr) if C and x+colwidth+len(C) < self.vd.windowWidth: scr.addstr(y, x+colwidth, C, sepattr)
python
def drawColHeader(self, scr, y, vcolidx): 'Compose and draw column header for given vcolidx.' col = self.visibleCols[vcolidx] # hdrattr highlights whole column header # sepattr is for header separators and indicators sepattr = colors.color_column_sep hdrattr = self.colorize(col, None) if vcolidx == self.cursorVisibleColIndex: hdrattr = hdrattr.update_attr(colors.color_current_hdr, 2) C = options.disp_column_sep if (self.keyCols and col is self.keyCols[-1]) or vcolidx == self.rightVisibleColIndex: C = options.disp_keycol_sep x, colwidth = self.visibleColLayout[vcolidx] # ANameTC T = getType(col.type).icon if T is None: # still allow icon to be explicitly non-displayed '' T = '?' N = ' ' + col.name # save room at front for LeftMore if len(N) > colwidth-1: N = N[:colwidth-len(options.disp_truncator)] + options.disp_truncator clipdraw(scr, y, x, N, hdrattr.attr, colwidth) clipdraw(scr, y, x+colwidth-len(T), T, hdrattr.attr, len(T)) vd.onMouse(scr, y, x, 1, colwidth, BUTTON3_RELEASED='rename-col') if vcolidx == self.leftVisibleColIndex and col not in self.keyCols and self.nonKeyVisibleCols.index(col) > 0: A = options.disp_more_left scr.addstr(y, x, A, sepattr) if C and x+colwidth+len(C) < self.vd.windowWidth: scr.addstr(y, x+colwidth, C, sepattr)
[ "def", "drawColHeader", "(", "self", ",", "scr", ",", "y", ",", "vcolidx", ")", ":", "col", "=", "self", ".", "visibleCols", "[", "vcolidx", "]", "# hdrattr highlights whole column header", "# sepattr is for header separators and indicators", "sepattr", "=", "colors",...
Compose and draw column header for given vcolidx.
[ "Compose", "and", "draw", "column", "header", "for", "given", "vcolidx", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1725-L1759
229,845
saulpw/visidata
visidata/vdtui.py
Sheet.editCell
def editCell(self, vcolidx=None, rowidx=None, **kwargs): 'Call `editText` at its place on the screen. Returns the new value, properly typed' if vcolidx is None: vcolidx = self.cursorVisibleColIndex x, w = self.visibleColLayout.get(vcolidx, (0, 0)) col = self.visibleCols[vcolidx] if rowidx is None: rowidx = self.cursorRowIndex if rowidx < 0: # header y = 0 currentValue = col.name else: y = self.rowLayout.get(rowidx, 0) currentValue = col.getDisplayValue(self.rows[self.cursorRowIndex]) editargs = dict(value=currentValue, fillchar=options.disp_edit_fill, truncchar=options.disp_truncator) editargs.update(kwargs) # update with user-specified args r = self.vd.editText(y, x, w, **editargs) if rowidx >= 0: # if not header r = col.type(r) # convert input to column type, let exceptions be raised return r
python
def editCell(self, vcolidx=None, rowidx=None, **kwargs): 'Call `editText` at its place on the screen. Returns the new value, properly typed' if vcolidx is None: vcolidx = self.cursorVisibleColIndex x, w = self.visibleColLayout.get(vcolidx, (0, 0)) col = self.visibleCols[vcolidx] if rowidx is None: rowidx = self.cursorRowIndex if rowidx < 0: # header y = 0 currentValue = col.name else: y = self.rowLayout.get(rowidx, 0) currentValue = col.getDisplayValue(self.rows[self.cursorRowIndex]) editargs = dict(value=currentValue, fillchar=options.disp_edit_fill, truncchar=options.disp_truncator) editargs.update(kwargs) # update with user-specified args r = self.vd.editText(y, x, w, **editargs) if rowidx >= 0: # if not header r = col.type(r) # convert input to column type, let exceptions be raised return r
[ "def", "editCell", "(", "self", ",", "vcolidx", "=", "None", ",", "rowidx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "vcolidx", "is", "None", ":", "vcolidx", "=", "self", ".", "cursorVisibleColIndex", "x", ",", "w", "=", "self", ".", "...
Call `editText` at its place on the screen. Returns the new value, properly typed
[ "Call", "editText", "at", "its", "place", "on", "the", "screen", ".", "Returns", "the", "new", "value", "properly", "typed" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1846-L1871
229,846
saulpw/visidata
visidata/vdtui.py
Column.recalc
def recalc(self, sheet=None): 'reset column cache, attach to sheet, and reify name' if self._cachedValues: self._cachedValues.clear() if sheet: self.sheet = sheet self.name = self._name
python
def recalc(self, sheet=None): 'reset column cache, attach to sheet, and reify name' if self._cachedValues: self._cachedValues.clear() if sheet: self.sheet = sheet self.name = self._name
[ "def", "recalc", "(", "self", ",", "sheet", "=", "None", ")", ":", "if", "self", ".", "_cachedValues", ":", "self", ".", "_cachedValues", ".", "clear", "(", ")", "if", "sheet", ":", "self", ".", "sheet", "=", "sheet", "self", ".", "name", "=", "sel...
reset column cache, attach to sheet, and reify name
[ "reset", "column", "cache", "attach", "to", "sheet", "and", "reify", "name" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2055-L2061
229,847
saulpw/visidata
visidata/vdtui.py
Column.format
def format(self, typedval): 'Return displayable string of `typedval` according to `Column.fmtstr`' if typedval is None: return None if isinstance(typedval, (list, tuple)): return '[%s]' % len(typedval) if isinstance(typedval, dict): return '{%s}' % len(typedval) if isinstance(typedval, bytes): typedval = typedval.decode(options.encoding, options.encoding_errors) return getType(self.type).formatter(self.fmtstr, typedval)
python
def format(self, typedval): 'Return displayable string of `typedval` according to `Column.fmtstr`' if typedval is None: return None if isinstance(typedval, (list, tuple)): return '[%s]' % len(typedval) if isinstance(typedval, dict): return '{%s}' % len(typedval) if isinstance(typedval, bytes): typedval = typedval.decode(options.encoding, options.encoding_errors) return getType(self.type).formatter(self.fmtstr, typedval)
[ "def", "format", "(", "self", ",", "typedval", ")", ":", "if", "typedval", "is", "None", ":", "return", "None", "if", "isinstance", "(", "typedval", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "'[%s]'", "%", "len", "(", "typedval", ")", ...
Return displayable string of `typedval` according to `Column.fmtstr`
[ "Return", "displayable", "string", "of", "typedval", "according", "to", "Column", ".", "fmtstr" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2083-L2095
229,848
saulpw/visidata
visidata/vdtui.py
Column.getTypedValue
def getTypedValue(self, row): 'Returns the properly-typed value for the given row at this column.' return wrapply(self.type, wrapply(self.getValue, row))
python
def getTypedValue(self, row): 'Returns the properly-typed value for the given row at this column.' return wrapply(self.type, wrapply(self.getValue, row))
[ "def", "getTypedValue", "(", "self", ",", "row", ")", ":", "return", "wrapply", "(", "self", ".", "type", ",", "wrapply", "(", "self", ".", "getValue", ",", "row", ")", ")" ]
Returns the properly-typed value for the given row at this column.
[ "Returns", "the", "properly", "-", "typed", "value", "for", "the", "given", "row", "at", "this", "column", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2129-L2131
229,849
saulpw/visidata
visidata/vdtui.py
Column.getTypedValueOrException
def getTypedValueOrException(self, row): 'Returns the properly-typed value for the given row at this column, or an Exception object.' return wrapply(self.type, wrapply(self.getValue, row))
python
def getTypedValueOrException(self, row): 'Returns the properly-typed value for the given row at this column, or an Exception object.' return wrapply(self.type, wrapply(self.getValue, row))
[ "def", "getTypedValueOrException", "(", "self", ",", "row", ")", ":", "return", "wrapply", "(", "self", ".", "type", ",", "wrapply", "(", "self", ".", "getValue", ",", "row", ")", ")" ]
Returns the properly-typed value for the given row at this column, or an Exception object.
[ "Returns", "the", "properly", "-", "typed", "value", "for", "the", "given", "row", "at", "this", "column", "or", "an", "Exception", "object", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2133-L2135
229,850
saulpw/visidata
visidata/vdtui.py
Column.getTypedValueNoExceptions
def getTypedValueNoExceptions(self, row): '''Returns the properly-typed value for the given row at this column. Returns the type's default value if either the getter or the type conversion fails.''' return wrapply(self.type, wrapply(self.getValue, row))
python
def getTypedValueNoExceptions(self, row): '''Returns the properly-typed value for the given row at this column. Returns the type's default value if either the getter or the type conversion fails.''' return wrapply(self.type, wrapply(self.getValue, row))
[ "def", "getTypedValueNoExceptions", "(", "self", ",", "row", ")", ":", "return", "wrapply", "(", "self", ".", "type", ",", "wrapply", "(", "self", ".", "getValue", ",", "row", ")", ")" ]
Returns the properly-typed value for the given row at this column. Returns the type's default value if either the getter or the type conversion fails.
[ "Returns", "the", "properly", "-", "typed", "value", "for", "the", "given", "row", "at", "this", "column", ".", "Returns", "the", "type", "s", "default", "value", "if", "either", "the", "getter", "or", "the", "type", "conversion", "fails", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2137-L2140
229,851
saulpw/visidata
visidata/vdtui.py
Column.getCell
def getCell(self, row, width=None): 'Return DisplayWrapper for displayable cell value.' cellval = wrapply(self.getValue, row) typedval = wrapply(self.type, cellval) if isinstance(typedval, TypedWrapper): if isinstance(cellval, TypedExceptionWrapper): # calc failed exc = cellval.exception if cellval.forwarded: dispval = str(cellval) # traceback.format_exception_only(type(exc), exc)[-1].strip() else: dispval = options.disp_error_val return DisplayWrapper(cellval.val, error=exc.stacktrace, display=dispval, note=options.note_getter_exc, notecolor='color_error') elif typedval.val is None: # early out for strict None return DisplayWrapper(None, display='', # force empty display for None note=options.disp_note_none, notecolor='color_note_type') elif isinstance(typedval, TypedExceptionWrapper): # calc succeeded, type failed return DisplayWrapper(typedval.val, display=str(cellval), error=typedval.exception.stacktrace, note=options.note_type_exc, notecolor='color_warning') else: return DisplayWrapper(typedval.val, display=str(typedval.val), note=options.note_type_exc, notecolor='color_warning') elif isinstance(typedval, threading.Thread): return DisplayWrapper(None, display=options.disp_pending, note=options.note_pending, notecolor='color_note_pending') dw = DisplayWrapper(cellval) try: dw.display = self.format(typedval) or '' if width and isNumeric(self): dw.display = dw.display.rjust(width-1) # annotate cells with raw value type in anytype columns, except for strings if self.type is anytype and type(cellval) is not str: typedesc = typemap.get(type(cellval), None) dw.note = typedesc.icon if typedesc else options.note_unknown_type dw.notecolor = 'color_note_type' except Exception as e: # formatting failure e.stacktrace = stacktrace() dw.error = e try: dw.display = str(cellval) except Exception as e: dw.display = str(e) dw.note = options.note_format_exc dw.notecolor = 'color_warning' return dw
python
def getCell(self, row, width=None): 'Return DisplayWrapper for displayable cell value.' cellval = wrapply(self.getValue, row) typedval = wrapply(self.type, cellval) if isinstance(typedval, TypedWrapper): if isinstance(cellval, TypedExceptionWrapper): # calc failed exc = cellval.exception if cellval.forwarded: dispval = str(cellval) # traceback.format_exception_only(type(exc), exc)[-1].strip() else: dispval = options.disp_error_val return DisplayWrapper(cellval.val, error=exc.stacktrace, display=dispval, note=options.note_getter_exc, notecolor='color_error') elif typedval.val is None: # early out for strict None return DisplayWrapper(None, display='', # force empty display for None note=options.disp_note_none, notecolor='color_note_type') elif isinstance(typedval, TypedExceptionWrapper): # calc succeeded, type failed return DisplayWrapper(typedval.val, display=str(cellval), error=typedval.exception.stacktrace, note=options.note_type_exc, notecolor='color_warning') else: return DisplayWrapper(typedval.val, display=str(typedval.val), note=options.note_type_exc, notecolor='color_warning') elif isinstance(typedval, threading.Thread): return DisplayWrapper(None, display=options.disp_pending, note=options.note_pending, notecolor='color_note_pending') dw = DisplayWrapper(cellval) try: dw.display = self.format(typedval) or '' if width and isNumeric(self): dw.display = dw.display.rjust(width-1) # annotate cells with raw value type in anytype columns, except for strings if self.type is anytype and type(cellval) is not str: typedesc = typemap.get(type(cellval), None) dw.note = typedesc.icon if typedesc else options.note_unknown_type dw.notecolor = 'color_note_type' except Exception as e: # formatting failure e.stacktrace = stacktrace() dw.error = e try: dw.display = str(cellval) except Exception as e: dw.display = str(e) dw.note = options.note_format_exc dw.notecolor = 'color_warning' return dw
[ "def", "getCell", "(", "self", ",", "row", ",", "width", "=", "None", ")", ":", "cellval", "=", "wrapply", "(", "self", ".", "getValue", ",", "row", ")", "typedval", "=", "wrapply", "(", "self", ".", "type", ",", "cellval", ")", "if", "isinstance", ...
Return DisplayWrapper for displayable cell value.
[ "Return", "DisplayWrapper", "for", "displayable", "cell", "value", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2160-L2220
229,852
saulpw/visidata
visidata/vdtui.py
Column.setValueSafe
def setValueSafe(self, row, value): 'setValue and ignore exceptions' try: return self.setValue(row, value) except Exception as e: exceptionCaught(e)
python
def setValueSafe(self, row, value): 'setValue and ignore exceptions' try: return self.setValue(row, value) except Exception as e: exceptionCaught(e)
[ "def", "setValueSafe", "(", "self", ",", "row", ",", "value", ")", ":", "try", ":", "return", "self", ".", "setValue", "(", "row", ",", "value", ")", "except", "Exception", "as", "e", ":", "exceptionCaught", "(", "e", ")" ]
setValue and ignore exceptions
[ "setValue", "and", "ignore", "exceptions" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2229-L2234
229,853
saulpw/visidata
visidata/vdtui.py
Column.setValues
def setValues(self, rows, *values): 'Set our column value for given list of rows to `value`.' for r, v in zip(rows, itertools.cycle(values)): self.setValueSafe(r, v) self.recalc() return status('set %d cells to %d values' % (len(rows), len(values)))
python
def setValues(self, rows, *values): 'Set our column value for given list of rows to `value`.' for r, v in zip(rows, itertools.cycle(values)): self.setValueSafe(r, v) self.recalc() return status('set %d cells to %d values' % (len(rows), len(values)))
[ "def", "setValues", "(", "self", ",", "rows", ",", "*", "values", ")", ":", "for", "r", ",", "v", "in", "zip", "(", "rows", ",", "itertools", ".", "cycle", "(", "values", ")", ")", ":", "self", ".", "setValueSafe", "(", "r", ",", "v", ")", "sel...
Set our column value for given list of rows to `value`.
[ "Set", "our", "column", "value", "for", "given", "list", "of", "rows", "to", "value", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2236-L2241
229,854
saulpw/visidata
visidata/vdtui.py
Column.getMaxWidth
def getMaxWidth(self, rows): 'Return the maximum length of any cell in column or its header.' w = 0 if len(rows) > 0: w = max(max(len(self.getDisplayValue(r)) for r in rows), len(self.name))+2 return max(w, len(self.name))
python
def getMaxWidth(self, rows): 'Return the maximum length of any cell in column or its header.' w = 0 if len(rows) > 0: w = max(max(len(self.getDisplayValue(r)) for r in rows), len(self.name))+2 return max(w, len(self.name))
[ "def", "getMaxWidth", "(", "self", ",", "rows", ")", ":", "w", "=", "0", "if", "len", "(", "rows", ")", ">", "0", ":", "w", "=", "max", "(", "max", "(", "len", "(", "self", ".", "getDisplayValue", "(", "r", ")", ")", "for", "r", "in", "rows",...
Return the maximum length of any cell in column or its header.
[ "Return", "the", "maximum", "length", "of", "any", "cell", "in", "column", "or", "its", "header", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2258-L2263
229,855
saulpw/visidata
visidata/vdtui.py
Column.toggleWidth
def toggleWidth(self, width): 'Change column width to either given `width` or default value.' if self.width != width: self.width = width else: self.width = int(options.default_width)
python
def toggleWidth(self, width): 'Change column width to either given `width` or default value.' if self.width != width: self.width = width else: self.width = int(options.default_width)
[ "def", "toggleWidth", "(", "self", ",", "width", ")", ":", "if", "self", ".", "width", "!=", "width", ":", "self", ".", "width", "=", "width", "else", ":", "self", ".", "width", "=", "int", "(", "options", ".", "default_width", ")" ]
Change column width to either given `width` or default value.
[ "Change", "column", "width", "to", "either", "given", "width", "or", "default", "value", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2265-L2270
229,856
saulpw/visidata
visidata/vdtui.py
ColorMaker.resolve_colors
def resolve_colors(self, colorstack): 'Returns the curses attribute for the colorstack, a list of color option names sorted highest-precedence color first.' attr = CursesAttr() for coloropt in colorstack: c = self.get_color(coloropt) attr = attr.update_attr(c) return attr
python
def resolve_colors(self, colorstack): 'Returns the curses attribute for the colorstack, a list of color option names sorted highest-precedence color first.' attr = CursesAttr() for coloropt in colorstack: c = self.get_color(coloropt) attr = attr.update_attr(c) return attr
[ "def", "resolve_colors", "(", "self", ",", "colorstack", ")", ":", "attr", "=", "CursesAttr", "(", ")", "for", "coloropt", "in", "colorstack", ":", "c", "=", "self", ".", "get_color", "(", "coloropt", ")", "attr", "=", "attr", ".", "update_attr", "(", ...
Returns the curses attribute for the colorstack, a list of color option names sorted highest-precedence color first.
[ "Returns", "the", "curses", "attribute", "for", "the", "colorstack", "a", "list", "of", "color", "option", "names", "sorted", "highest", "-", "precedence", "color", "first", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L2788-L2794
229,857
saulpw/visidata
visidata/aggregators.py
addAggregators
def addAggregators(cols, aggrnames): 'add aggregator for each aggrname to each of cols' for aggrname in aggrnames: aggrs = aggregators.get(aggrname) aggrs = aggrs if isinstance(aggrs, list) else [aggrs] for aggr in aggrs: for c in cols: if not hasattr(c, 'aggregators'): c.aggregators = [] if aggr and aggr not in c.aggregators: c.aggregators += [aggr]
python
def addAggregators(cols, aggrnames): 'add aggregator for each aggrname to each of cols' for aggrname in aggrnames: aggrs = aggregators.get(aggrname) aggrs = aggrs if isinstance(aggrs, list) else [aggrs] for aggr in aggrs: for c in cols: if not hasattr(c, 'aggregators'): c.aggregators = [] if aggr and aggr not in c.aggregators: c.aggregators += [aggr]
[ "def", "addAggregators", "(", "cols", ",", "aggrnames", ")", ":", "for", "aggrname", "in", "aggrnames", ":", "aggrs", "=", "aggregators", ".", "get", "(", "aggrname", ")", "aggrs", "=", "aggrs", "if", "isinstance", "(", "aggrs", ",", "list", ")", "else",...
add aggregator for each aggrname to each of cols
[ "add", "aggregator", "for", "each", "aggrname", "to", "each", "of", "cols" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/aggregators.py#L96-L106
229,858
saulpw/visidata
visidata/cmdlog.py
CommandLog.removeSheet
def removeSheet(self, vs): 'Remove all traces of sheets named vs.name from the cmdlog.' self.rows = [r for r in self.rows if r.sheet != vs.name] status('removed "%s" from cmdlog' % vs.name)
python
def removeSheet(self, vs): 'Remove all traces of sheets named vs.name from the cmdlog.' self.rows = [r for r in self.rows if r.sheet != vs.name] status('removed "%s" from cmdlog' % vs.name)
[ "def", "removeSheet", "(", "self", ",", "vs", ")", ":", "self", ".", "rows", "=", "[", "r", "for", "r", "in", "self", ".", "rows", "if", "r", ".", "sheet", "!=", "vs", ".", "name", "]", "status", "(", "'removed \"%s\" from cmdlog'", "%", "vs", ".",...
Remove all traces of sheets named vs.name from the cmdlog.
[ "Remove", "all", "traces", "of", "sheets", "named", "vs", ".", "name", "from", "the", "cmdlog", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/cmdlog.py#L96-L99
229,859
saulpw/visidata
visidata/cmdlog.py
CommandLog.delay
def delay(self, factor=1): 'returns True if delay satisfied' acquired = CommandLog.semaphore.acquire(timeout=options.replay_wait*factor if not self.paused else None) return acquired or not self.paused
python
def delay(self, factor=1): 'returns True if delay satisfied' acquired = CommandLog.semaphore.acquire(timeout=options.replay_wait*factor if not self.paused else None) return acquired or not self.paused
[ "def", "delay", "(", "self", ",", "factor", "=", "1", ")", ":", "acquired", "=", "CommandLog", ".", "semaphore", ".", "acquire", "(", "timeout", "=", "options", ".", "replay_wait", "*", "factor", "if", "not", "self", ".", "paused", "else", "None", ")",...
returns True if delay satisfied
[ "returns", "True", "if", "delay", "satisfied" ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/cmdlog.py#L220-L223
229,860
saulpw/visidata
visidata/cmdlog.py
CommandLog.replayOne
def replayOne(self, r): 'Replay the command in one given row.' CommandLog.currentReplayRow = r longname = getattr(r, 'longname', None) if longname == 'set-option': try: options.set(r.row, r.input, options._opts.getobj(r.col)) escaped = False except Exception as e: exceptionCaught(e) escaped = True else: vs = self.moveToReplayContext(r) vd().keystrokes = r.keystrokes # <=v1.2 used keystrokes in longname column; getCommand fetches both escaped = vs.exec_command(vs.getCommand(longname if longname else r.keystrokes), keystrokes=r.keystrokes) CommandLog.currentReplayRow = None if escaped: # escape during replay aborts replay warning('replay aborted') return escaped
python
def replayOne(self, r): 'Replay the command in one given row.' CommandLog.currentReplayRow = r longname = getattr(r, 'longname', None) if longname == 'set-option': try: options.set(r.row, r.input, options._opts.getobj(r.col)) escaped = False except Exception as e: exceptionCaught(e) escaped = True else: vs = self.moveToReplayContext(r) vd().keystrokes = r.keystrokes # <=v1.2 used keystrokes in longname column; getCommand fetches both escaped = vs.exec_command(vs.getCommand(longname if longname else r.keystrokes), keystrokes=r.keystrokes) CommandLog.currentReplayRow = None if escaped: # escape during replay aborts replay warning('replay aborted') return escaped
[ "def", "replayOne", "(", "self", ",", "r", ")", ":", "CommandLog", ".", "currentReplayRow", "=", "r", "longname", "=", "getattr", "(", "r", ",", "'longname'", ",", "None", ")", "if", "longname", "==", "'set-option'", ":", "try", ":", "options", ".", "s...
Replay the command in one given row.
[ "Replay", "the", "command", "in", "one", "given", "row", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/cmdlog.py#L225-L248
229,861
saulpw/visidata
visidata/cmdlog.py
CommandLog.replay_sync
def replay_sync(self, live=False): 'Replay all commands in log.' self.cursorRowIndex = 0 CommandLog.currentReplay = self with Progress(total=len(self.rows)) as prog: while self.cursorRowIndex < len(self.rows): if CommandLog.currentReplay is None: status('replay canceled') return vd().statuses.clear() try: if self.replayOne(self.cursorRow): self.cancel() return except Exception as e: self.cancel() exceptionCaught(e) status('replay canceled') return self.cursorRowIndex += 1 prog.addProgress(1) sync(1 if live else 0) # expect this thread also if playing live while not self.delay(): pass status('replay complete') CommandLog.currentReplay = None
python
def replay_sync(self, live=False): 'Replay all commands in log.' self.cursorRowIndex = 0 CommandLog.currentReplay = self with Progress(total=len(self.rows)) as prog: while self.cursorRowIndex < len(self.rows): if CommandLog.currentReplay is None: status('replay canceled') return vd().statuses.clear() try: if self.replayOne(self.cursorRow): self.cancel() return except Exception as e: self.cancel() exceptionCaught(e) status('replay canceled') return self.cursorRowIndex += 1 prog.addProgress(1) sync(1 if live else 0) # expect this thread also if playing live while not self.delay(): pass status('replay complete') CommandLog.currentReplay = None
[ "def", "replay_sync", "(", "self", ",", "live", "=", "False", ")", ":", "self", ".", "cursorRowIndex", "=", "0", "CommandLog", ".", "currentReplay", "=", "self", "with", "Progress", "(", "total", "=", "len", "(", "self", ".", "rows", ")", ")", "as", ...
Replay all commands in log.
[ "Replay", "all", "commands", "in", "log", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/cmdlog.py#L250-L279
229,862
saulpw/visidata
visidata/cmdlog.py
CommandLog.setLastArgs
def setLastArgs(self, args): 'Set user input on last command, if not already set.' # only set if not already set (second input usually confirmation) if self.currentActiveRow is not None: if not self.currentActiveRow.input: self.currentActiveRow.input = args
python
def setLastArgs(self, args): 'Set user input on last command, if not already set.' # only set if not already set (second input usually confirmation) if self.currentActiveRow is not None: if not self.currentActiveRow.input: self.currentActiveRow.input = args
[ "def", "setLastArgs", "(", "self", ",", "args", ")", ":", "# only set if not already set (second input usually confirmation)", "if", "self", ".", "currentActiveRow", "is", "not", "None", ":", "if", "not", "self", ".", "currentActiveRow", ".", "input", ":", "self", ...
Set user input on last command, if not already set.
[ "Set", "user", "input", "on", "last", "command", "if", "not", "already", "set", "." ]
32771e0cea6c24fc7902683d14558391395c591f
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/cmdlog.py#L292-L297
229,863
pydata/pandas-gbq
pandas_gbq/load.py
encode_chunk
def encode_chunk(dataframe): """Return a file-like object of CSV-encoded rows. Args: dataframe (pandas.DataFrame): A chunk of a dataframe to encode """ csv_buffer = six.StringIO() dataframe.to_csv( csv_buffer, index=False, header=False, encoding="utf-8", float_format="%.15g", date_format="%Y-%m-%d %H:%M:%S.%f", ) # Convert to a BytesIO buffer so that unicode text is properly handled. # See: https://github.com/pydata/pandas-gbq/issues/106 body = csv_buffer.getvalue() if isinstance(body, bytes): body = body.decode("utf-8") body = body.encode("utf-8") return six.BytesIO(body)
python
def encode_chunk(dataframe): csv_buffer = six.StringIO() dataframe.to_csv( csv_buffer, index=False, header=False, encoding="utf-8", float_format="%.15g", date_format="%Y-%m-%d %H:%M:%S.%f", ) # Convert to a BytesIO buffer so that unicode text is properly handled. # See: https://github.com/pydata/pandas-gbq/issues/106 body = csv_buffer.getvalue() if isinstance(body, bytes): body = body.decode("utf-8") body = body.encode("utf-8") return six.BytesIO(body)
[ "def", "encode_chunk", "(", "dataframe", ")", ":", "csv_buffer", "=", "six", ".", "StringIO", "(", ")", "dataframe", ".", "to_csv", "(", "csv_buffer", ",", "index", "=", "False", ",", "header", "=", "False", ",", "encoding", "=", "\"utf-8\"", ",", "float...
Return a file-like object of CSV-encoded rows. Args: dataframe (pandas.DataFrame): A chunk of a dataframe to encode
[ "Return", "a", "file", "-", "like", "object", "of", "CSV", "-", "encoded", "rows", "." ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/load.py#L9-L31
229,864
pydata/pandas-gbq
pandas_gbq/gbq.py
_bqschema_to_nullsafe_dtypes
def _bqschema_to_nullsafe_dtypes(schema_fields): """Specify explicit dtypes based on BigQuery schema. This function only specifies a dtype when the dtype allows nulls. Otherwise, use pandas's default dtype choice. See: http://pandas.pydata.org/pandas-docs/dev/missing_data.html #missing-data-casting-rules-and-indexing """ # If you update this mapping, also update the table at # `docs/source/reading.rst`. dtype_map = { "FLOAT": np.dtype(float), # pandas doesn't support timezone-aware dtype in DataFrame/Series # constructors. It's more idiomatic to localize after construction. # https://github.com/pandas-dev/pandas/issues/25843 "TIMESTAMP": "datetime64[ns]", "TIME": "datetime64[ns]", "DATE": "datetime64[ns]", "DATETIME": "datetime64[ns]", } dtypes = {} for field in schema_fields: name = str(field["name"]) if field["mode"].upper() == "REPEATED": continue dtype = dtype_map.get(field["type"].upper()) if dtype: dtypes[name] = dtype return dtypes
python
def _bqschema_to_nullsafe_dtypes(schema_fields): # If you update this mapping, also update the table at # `docs/source/reading.rst`. dtype_map = { "FLOAT": np.dtype(float), # pandas doesn't support timezone-aware dtype in DataFrame/Series # constructors. It's more idiomatic to localize after construction. # https://github.com/pandas-dev/pandas/issues/25843 "TIMESTAMP": "datetime64[ns]", "TIME": "datetime64[ns]", "DATE": "datetime64[ns]", "DATETIME": "datetime64[ns]", } dtypes = {} for field in schema_fields: name = str(field["name"]) if field["mode"].upper() == "REPEATED": continue dtype = dtype_map.get(field["type"].upper()) if dtype: dtypes[name] = dtype return dtypes
[ "def", "_bqschema_to_nullsafe_dtypes", "(", "schema_fields", ")", ":", "# If you update this mapping, also update the table at", "# `docs/source/reading.rst`.", "dtype_map", "=", "{", "\"FLOAT\"", ":", "np", ".", "dtype", "(", "float", ")", ",", "# pandas doesn't support time...
Specify explicit dtypes based on BigQuery schema. This function only specifies a dtype when the dtype allows nulls. Otherwise, use pandas's default dtype choice. See: http://pandas.pydata.org/pandas-docs/dev/missing_data.html #missing-data-casting-rules-and-indexing
[ "Specify", "explicit", "dtypes", "based", "on", "BigQuery", "schema", "." ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L662-L694
229,865
pydata/pandas-gbq
pandas_gbq/gbq.py
_cast_empty_df_dtypes
def _cast_empty_df_dtypes(schema_fields, df): """Cast any columns in an empty dataframe to correct type. In an empty dataframe, pandas cannot choose a dtype unless one is explicitly provided. The _bqschema_to_nullsafe_dtypes() function only provides dtypes when the dtype safely handles null values. This means that empty int64 and boolean columns are incorrectly classified as ``object``. """ if not df.empty: raise ValueError( "DataFrame must be empty in order to cast non-nullsafe dtypes" ) dtype_map = {"BOOLEAN": bool, "INTEGER": np.int64} for field in schema_fields: column = str(field["name"]) if field["mode"].upper() == "REPEATED": continue dtype = dtype_map.get(field["type"].upper()) if dtype: df[column] = df[column].astype(dtype) return df
python
def _cast_empty_df_dtypes(schema_fields, df): if not df.empty: raise ValueError( "DataFrame must be empty in order to cast non-nullsafe dtypes" ) dtype_map = {"BOOLEAN": bool, "INTEGER": np.int64} for field in schema_fields: column = str(field["name"]) if field["mode"].upper() == "REPEATED": continue dtype = dtype_map.get(field["type"].upper()) if dtype: df[column] = df[column].astype(dtype) return df
[ "def", "_cast_empty_df_dtypes", "(", "schema_fields", ",", "df", ")", ":", "if", "not", "df", ".", "empty", ":", "raise", "ValueError", "(", "\"DataFrame must be empty in order to cast non-nullsafe dtypes\"", ")", "dtype_map", "=", "{", "\"BOOLEAN\"", ":", "bool", "...
Cast any columns in an empty dataframe to correct type. In an empty dataframe, pandas cannot choose a dtype unless one is explicitly provided. The _bqschema_to_nullsafe_dtypes() function only provides dtypes when the dtype safely handles null values. This means that empty int64 and boolean columns are incorrectly classified as ``object``.
[ "Cast", "any", "columns", "in", "an", "empty", "dataframe", "to", "correct", "type", "." ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L697-L722
229,866
pydata/pandas-gbq
pandas_gbq/gbq.py
_localize_df
def _localize_df(schema_fields, df): """Localize any TIMESTAMP columns to tz-aware type. In pandas versions before 0.24.0, DatetimeTZDtype cannot be used as the dtype in Series/DataFrame construction, so localize those columns after the DataFrame is constructed. """ for field in schema_fields: column = str(field["name"]) if field["mode"].upper() == "REPEATED": continue if field["type"].upper() == "TIMESTAMP" and df[column].dt.tz is None: df[column] = df[column].dt.tz_localize("UTC") return df
python
def _localize_df(schema_fields, df): for field in schema_fields: column = str(field["name"]) if field["mode"].upper() == "REPEATED": continue if field["type"].upper() == "TIMESTAMP" and df[column].dt.tz is None: df[column] = df[column].dt.tz_localize("UTC") return df
[ "def", "_localize_df", "(", "schema_fields", ",", "df", ")", ":", "for", "field", "in", "schema_fields", ":", "column", "=", "str", "(", "field", "[", "\"name\"", "]", ")", "if", "field", "[", "\"mode\"", "]", ".", "upper", "(", ")", "==", "\"REPEATED\...
Localize any TIMESTAMP columns to tz-aware type. In pandas versions before 0.24.0, DatetimeTZDtype cannot be used as the dtype in Series/DataFrame construction, so localize those columns after the DataFrame is constructed.
[ "Localize", "any", "TIMESTAMP", "columns", "to", "tz", "-", "aware", "type", "." ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L725-L740
229,867
pydata/pandas-gbq
pandas_gbq/gbq.py
read_gbq
def read_gbq( query, project_id=None, index_col=None, col_order=None, reauth=False, auth_local_webserver=False, dialect=None, location=None, configuration=None, credentials=None, use_bqstorage_api=False, verbose=None, private_key=None, ): r"""Load data from Google BigQuery using google-cloud-python The main method a user calls to execute a Query in Google BigQuery and read results into a pandas DataFrame. This method uses the Google Cloud client library to make requests to Google BigQuery, documented `here <https://google-cloud-python.readthedocs.io/en/latest/bigquery/usage.html>`__. See the :ref:`How to authenticate with Google BigQuery <authentication>` guide for authentication instructions. Parameters ---------- query : str SQL-Like Query to return data values. project_id : str, optional Google BigQuery Account project ID. Optional when available from the environment. index_col : str, optional Name of result column to use for index in results DataFrame. col_order : list(str), optional List of BigQuery column names in the desired order for results DataFrame. reauth : boolean, default False Force Google BigQuery to re-authenticate the user. This is useful if multiple accounts are used. auth_local_webserver : boolean, default False Use the `local webserver flow`_ instead of the `console flow`_ when getting user credentials. .. _local webserver flow: http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server .. _console flow: http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console .. versionadded:: 0.2.0 dialect : str, default 'standard' Note: The default value changed to 'standard' in version 0.10.0. SQL syntax dialect to use. Value can be one of: ``'legacy'`` Use BigQuery's legacy SQL dialect. For more information see `BigQuery Legacy SQL Reference <https://cloud.google.com/bigquery/docs/reference/legacy-sql>`__. ``'standard'`` Use BigQuery's standard SQL, which is compliant with the SQL 2011 standard. For more information see `BigQuery Standard SQL Reference <https://cloud.google.com/bigquery/docs/reference/standard-sql/>`__. location : str, optional Location where the query job should run. See the `BigQuery locations documentation <https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a list of available locations. The location must match that of any datasets used in the query. .. versionadded:: 0.5.0 configuration : dict, optional Query config parameters for job processing. For example: configuration = {'query': {'useQueryCache': False}} For more information see `BigQuery REST API Reference <https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query>`__. credentials : google.auth.credentials.Credentials, optional Credentials for accessing Google APIs. Use this parameter to override default credentials, such as to use Compute Engine :class:`google.auth.compute_engine.Credentials` or Service Account :class:`google.oauth2.service_account.Credentials` directly. .. versionadded:: 0.8.0 use_bqstorage_api : bool, default False Use the `BigQuery Storage API <https://cloud.google.com/bigquery/docs/reference/storage/>`__ to download query results quickly, but at an increased cost. To use this API, first `enable it in the Cloud Console <https://console.cloud.google.com/apis/library/bigquerystorage.googleapis.com>`__. You must also have the `bigquery.readsessions.create <https://cloud.google.com/bigquery/docs/access-control#roles>`__ permission on the project you are billing queries to. **Note:** Due to a `known issue in the ``google-cloud-bigquery`` package <https://github.com/googleapis/google-cloud-python/pull/7633>`__ (fixed in version 1.11.0), you must write your query results to a destination table. To do this with ``read_gbq``, supply a ``configuration`` dictionary. This feature requires the ``google-cloud-bigquery-storage`` and ``fastavro`` packages. .. versionadded:: 0.10.0 verbose : None, deprecated Deprecated in Pandas-GBQ 0.4.0. Use the `logging module to adjust verbosity instead <https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__. private_key : str, deprecated Deprecated in pandas-gbq version 0.8.0. Use the ``credentials`` parameter and :func:`google.oauth2.service_account.Credentials.from_service_account_info` or :func:`google.oauth2.service_account.Credentials.from_service_account_file` instead. Service account private key in JSON format. Can be file path or string contents. This is useful for remote server authentication (eg. Jupyter/IPython notebook on remote host). Returns ------- df: DataFrame DataFrame representing results of query. """ global context if dialect is None: dialect = context.dialect if dialect is None: dialect = "standard" _test_google_api_imports() if verbose is not None and SHOW_VERBOSE_DEPRECATION: warnings.warn( "verbose is deprecated and will be removed in " "a future version. Set logging level in order to vary " "verbosity", FutureWarning, stacklevel=2, ) if private_key is not None and SHOW_PRIVATE_KEY_DEPRECATION: warnings.warn( PRIVATE_KEY_DEPRECATION_MESSAGE, FutureWarning, stacklevel=2 ) if dialect not in ("legacy", "standard"): raise ValueError("'{0}' is not valid for dialect".format(dialect)) connector = GbqConnector( project_id, reauth=reauth, dialect=dialect, auth_local_webserver=auth_local_webserver, location=location, credentials=credentials, private_key=private_key, use_bqstorage_api=use_bqstorage_api, ) final_df = connector.run_query(query, configuration=configuration) # Reindex the DataFrame on the provided column if index_col is not None: if index_col in final_df.columns: final_df.set_index(index_col, inplace=True) else: raise InvalidIndexColumn( 'Index column "{0}" does not exist in DataFrame.'.format( index_col ) ) # Change the order of columns in the DataFrame based on provided list if col_order is not None: if sorted(col_order) == sorted(final_df.columns): final_df = final_df[col_order] else: raise InvalidColumnOrder( "Column order does not match this DataFrame." ) connector.log_elapsed_seconds( "Total time taken", datetime.now().strftime("s.\nFinished at %Y-%m-%d %H:%M:%S."), ) return final_df
python
def read_gbq( query, project_id=None, index_col=None, col_order=None, reauth=False, auth_local_webserver=False, dialect=None, location=None, configuration=None, credentials=None, use_bqstorage_api=False, verbose=None, private_key=None, ): r"""Load data from Google BigQuery using google-cloud-python The main method a user calls to execute a Query in Google BigQuery and read results into a pandas DataFrame. This method uses the Google Cloud client library to make requests to Google BigQuery, documented `here <https://google-cloud-python.readthedocs.io/en/latest/bigquery/usage.html>`__. See the :ref:`How to authenticate with Google BigQuery <authentication>` guide for authentication instructions. Parameters ---------- query : str SQL-Like Query to return data values. project_id : str, optional Google BigQuery Account project ID. Optional when available from the environment. index_col : str, optional Name of result column to use for index in results DataFrame. col_order : list(str), optional List of BigQuery column names in the desired order for results DataFrame. reauth : boolean, default False Force Google BigQuery to re-authenticate the user. This is useful if multiple accounts are used. auth_local_webserver : boolean, default False Use the `local webserver flow`_ instead of the `console flow`_ when getting user credentials. .. _local webserver flow: http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server .. _console flow: http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console .. versionadded:: 0.2.0 dialect : str, default 'standard' Note: The default value changed to 'standard' in version 0.10.0. SQL syntax dialect to use. Value can be one of: ``'legacy'`` Use BigQuery's legacy SQL dialect. For more information see `BigQuery Legacy SQL Reference <https://cloud.google.com/bigquery/docs/reference/legacy-sql>`__. ``'standard'`` Use BigQuery's standard SQL, which is compliant with the SQL 2011 standard. For more information see `BigQuery Standard SQL Reference <https://cloud.google.com/bigquery/docs/reference/standard-sql/>`__. location : str, optional Location where the query job should run. See the `BigQuery locations documentation <https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a list of available locations. The location must match that of any datasets used in the query. .. versionadded:: 0.5.0 configuration : dict, optional Query config parameters for job processing. For example: configuration = {'query': {'useQueryCache': False}} For more information see `BigQuery REST API Reference <https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query>`__. credentials : google.auth.credentials.Credentials, optional Credentials for accessing Google APIs. Use this parameter to override default credentials, such as to use Compute Engine :class:`google.auth.compute_engine.Credentials` or Service Account :class:`google.oauth2.service_account.Credentials` directly. .. versionadded:: 0.8.0 use_bqstorage_api : bool, default False Use the `BigQuery Storage API <https://cloud.google.com/bigquery/docs/reference/storage/>`__ to download query results quickly, but at an increased cost. To use this API, first `enable it in the Cloud Console <https://console.cloud.google.com/apis/library/bigquerystorage.googleapis.com>`__. You must also have the `bigquery.readsessions.create <https://cloud.google.com/bigquery/docs/access-control#roles>`__ permission on the project you are billing queries to. **Note:** Due to a `known issue in the ``google-cloud-bigquery`` package <https://github.com/googleapis/google-cloud-python/pull/7633>`__ (fixed in version 1.11.0), you must write your query results to a destination table. To do this with ``read_gbq``, supply a ``configuration`` dictionary. This feature requires the ``google-cloud-bigquery-storage`` and ``fastavro`` packages. .. versionadded:: 0.10.0 verbose : None, deprecated Deprecated in Pandas-GBQ 0.4.0. Use the `logging module to adjust verbosity instead <https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__. private_key : str, deprecated Deprecated in pandas-gbq version 0.8.0. Use the ``credentials`` parameter and :func:`google.oauth2.service_account.Credentials.from_service_account_info` or :func:`google.oauth2.service_account.Credentials.from_service_account_file` instead. Service account private key in JSON format. Can be file path or string contents. This is useful for remote server authentication (eg. Jupyter/IPython notebook on remote host). Returns ------- df: DataFrame DataFrame representing results of query. """ global context if dialect is None: dialect = context.dialect if dialect is None: dialect = "standard" _test_google_api_imports() if verbose is not None and SHOW_VERBOSE_DEPRECATION: warnings.warn( "verbose is deprecated and will be removed in " "a future version. Set logging level in order to vary " "verbosity", FutureWarning, stacklevel=2, ) if private_key is not None and SHOW_PRIVATE_KEY_DEPRECATION: warnings.warn( PRIVATE_KEY_DEPRECATION_MESSAGE, FutureWarning, stacklevel=2 ) if dialect not in ("legacy", "standard"): raise ValueError("'{0}' is not valid for dialect".format(dialect)) connector = GbqConnector( project_id, reauth=reauth, dialect=dialect, auth_local_webserver=auth_local_webserver, location=location, credentials=credentials, private_key=private_key, use_bqstorage_api=use_bqstorage_api, ) final_df = connector.run_query(query, configuration=configuration) # Reindex the DataFrame on the provided column if index_col is not None: if index_col in final_df.columns: final_df.set_index(index_col, inplace=True) else: raise InvalidIndexColumn( 'Index column "{0}" does not exist in DataFrame.'.format( index_col ) ) # Change the order of columns in the DataFrame based on provided list if col_order is not None: if sorted(col_order) == sorted(final_df.columns): final_df = final_df[col_order] else: raise InvalidColumnOrder( "Column order does not match this DataFrame." ) connector.log_elapsed_seconds( "Total time taken", datetime.now().strftime("s.\nFinished at %Y-%m-%d %H:%M:%S."), ) return final_df
[ "def", "read_gbq", "(", "query", ",", "project_id", "=", "None", ",", "index_col", "=", "None", ",", "col_order", "=", "None", ",", "reauth", "=", "False", ",", "auth_local_webserver", "=", "False", ",", "dialect", "=", "None", ",", "location", "=", "Non...
r"""Load data from Google BigQuery using google-cloud-python The main method a user calls to execute a Query in Google BigQuery and read results into a pandas DataFrame. This method uses the Google Cloud client library to make requests to Google BigQuery, documented `here <https://google-cloud-python.readthedocs.io/en/latest/bigquery/usage.html>`__. See the :ref:`How to authenticate with Google BigQuery <authentication>` guide for authentication instructions. Parameters ---------- query : str SQL-Like Query to return data values. project_id : str, optional Google BigQuery Account project ID. Optional when available from the environment. index_col : str, optional Name of result column to use for index in results DataFrame. col_order : list(str), optional List of BigQuery column names in the desired order for results DataFrame. reauth : boolean, default False Force Google BigQuery to re-authenticate the user. This is useful if multiple accounts are used. auth_local_webserver : boolean, default False Use the `local webserver flow`_ instead of the `console flow`_ when getting user credentials. .. _local webserver flow: http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server .. _console flow: http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console .. versionadded:: 0.2.0 dialect : str, default 'standard' Note: The default value changed to 'standard' in version 0.10.0. SQL syntax dialect to use. Value can be one of: ``'legacy'`` Use BigQuery's legacy SQL dialect. For more information see `BigQuery Legacy SQL Reference <https://cloud.google.com/bigquery/docs/reference/legacy-sql>`__. ``'standard'`` Use BigQuery's standard SQL, which is compliant with the SQL 2011 standard. For more information see `BigQuery Standard SQL Reference <https://cloud.google.com/bigquery/docs/reference/standard-sql/>`__. location : str, optional Location where the query job should run. See the `BigQuery locations documentation <https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a list of available locations. The location must match that of any datasets used in the query. .. versionadded:: 0.5.0 configuration : dict, optional Query config parameters for job processing. For example: configuration = {'query': {'useQueryCache': False}} For more information see `BigQuery REST API Reference <https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query>`__. credentials : google.auth.credentials.Credentials, optional Credentials for accessing Google APIs. Use this parameter to override default credentials, such as to use Compute Engine :class:`google.auth.compute_engine.Credentials` or Service Account :class:`google.oauth2.service_account.Credentials` directly. .. versionadded:: 0.8.0 use_bqstorage_api : bool, default False Use the `BigQuery Storage API <https://cloud.google.com/bigquery/docs/reference/storage/>`__ to download query results quickly, but at an increased cost. To use this API, first `enable it in the Cloud Console <https://console.cloud.google.com/apis/library/bigquerystorage.googleapis.com>`__. You must also have the `bigquery.readsessions.create <https://cloud.google.com/bigquery/docs/access-control#roles>`__ permission on the project you are billing queries to. **Note:** Due to a `known issue in the ``google-cloud-bigquery`` package <https://github.com/googleapis/google-cloud-python/pull/7633>`__ (fixed in version 1.11.0), you must write your query results to a destination table. To do this with ``read_gbq``, supply a ``configuration`` dictionary. This feature requires the ``google-cloud-bigquery-storage`` and ``fastavro`` packages. .. versionadded:: 0.10.0 verbose : None, deprecated Deprecated in Pandas-GBQ 0.4.0. Use the `logging module to adjust verbosity instead <https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__. private_key : str, deprecated Deprecated in pandas-gbq version 0.8.0. Use the ``credentials`` parameter and :func:`google.oauth2.service_account.Credentials.from_service_account_info` or :func:`google.oauth2.service_account.Credentials.from_service_account_file` instead. Service account private key in JSON format. Can be file path or string contents. This is useful for remote server authentication (eg. Jupyter/IPython notebook on remote host). Returns ------- df: DataFrame DataFrame representing results of query.
[ "r", "Load", "data", "from", "Google", "BigQuery", "using", "google", "-", "cloud", "-", "python" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L758-L954
229,868
pydata/pandas-gbq
pandas_gbq/gbq.py
GbqConnector.schema
def schema(self, dataset_id, table_id): """Retrieve the schema of the table Obtain from BigQuery the field names and field types for the table defined by the parameters Parameters ---------- dataset_id : str Name of the BigQuery dataset for the table table_id : str Name of the BigQuery table Returns ------- list of dicts Fields representing the schema """ table_ref = self.client.dataset(dataset_id).table(table_id) try: table = self.client.get_table(table_ref) remote_schema = table.schema remote_fields = [ field_remote.to_api_repr() for field_remote in remote_schema ] for field in remote_fields: field["type"] = field["type"].upper() field["mode"] = field["mode"].upper() return remote_fields except self.http_error as ex: self.process_http_error(ex)
python
def schema(self, dataset_id, table_id): table_ref = self.client.dataset(dataset_id).table(table_id) try: table = self.client.get_table(table_ref) remote_schema = table.schema remote_fields = [ field_remote.to_api_repr() for field_remote in remote_schema ] for field in remote_fields: field["type"] = field["type"].upper() field["mode"] = field["mode"].upper() return remote_fields except self.http_error as ex: self.process_http_error(ex)
[ "def", "schema", "(", "self", ",", "dataset_id", ",", "table_id", ")", ":", "table_ref", "=", "self", ".", "client", ".", "dataset", "(", "dataset_id", ")", ".", "table", "(", "table_id", ")", "try", ":", "table", "=", "self", ".", "client", ".", "ge...
Retrieve the schema of the table Obtain from BigQuery the field names and field types for the table defined by the parameters Parameters ---------- dataset_id : str Name of the BigQuery dataset for the table table_id : str Name of the BigQuery table Returns ------- list of dicts Fields representing the schema
[ "Retrieve", "the", "schema", "of", "the", "table" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L550-L583
229,869
pydata/pandas-gbq
pandas_gbq/gbq.py
GbqConnector._clean_schema_fields
def _clean_schema_fields(self, fields): """Return a sanitized version of the schema for comparisons.""" fields_sorted = sorted(fields, key=lambda field: field["name"]) # Ignore mode and description when comparing schemas. return [ {"name": field["name"], "type": field["type"]} for field in fields_sorted ]
python
def _clean_schema_fields(self, fields): fields_sorted = sorted(fields, key=lambda field: field["name"]) # Ignore mode and description when comparing schemas. return [ {"name": field["name"], "type": field["type"]} for field in fields_sorted ]
[ "def", "_clean_schema_fields", "(", "self", ",", "fields", ")", ":", "fields_sorted", "=", "sorted", "(", "fields", ",", "key", "=", "lambda", "field", ":", "field", "[", "\"name\"", "]", ")", "# Ignore mode and description when comparing schemas.", "return", "[",...
Return a sanitized version of the schema for comparisons.
[ "Return", "a", "sanitized", "version", "of", "the", "schema", "for", "comparisons", "." ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L585-L592
229,870
pydata/pandas-gbq
pandas_gbq/gbq.py
GbqConnector.verify_schema
def verify_schema(self, dataset_id, table_id, schema): """Indicate whether schemas match exactly Compare the BigQuery table identified in the parameters with the schema passed in and indicate whether all fields in the former are present in the latter. Order is not considered. Parameters ---------- dataset_id :str Name of the BigQuery dataset for the table table_id : str Name of the BigQuery table schema : list(dict) Schema for comparison. Each item should have a 'name' and a 'type' Returns ------- bool Whether the schemas match """ fields_remote = self._clean_schema_fields( self.schema(dataset_id, table_id) ) fields_local = self._clean_schema_fields(schema["fields"]) return fields_remote == fields_local
python
def verify_schema(self, dataset_id, table_id, schema): fields_remote = self._clean_schema_fields( self.schema(dataset_id, table_id) ) fields_local = self._clean_schema_fields(schema["fields"]) return fields_remote == fields_local
[ "def", "verify_schema", "(", "self", ",", "dataset_id", ",", "table_id", ",", "schema", ")", ":", "fields_remote", "=", "self", ".", "_clean_schema_fields", "(", "self", ".", "schema", "(", "dataset_id", ",", "table_id", ")", ")", "fields_local", "=", "self"...
Indicate whether schemas match exactly Compare the BigQuery table identified in the parameters with the schema passed in and indicate whether all fields in the former are present in the latter. Order is not considered. Parameters ---------- dataset_id :str Name of the BigQuery dataset for the table table_id : str Name of the BigQuery table schema : list(dict) Schema for comparison. Each item should have a 'name' and a 'type' Returns ------- bool Whether the schemas match
[ "Indicate", "whether", "schemas", "match", "exactly" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L594-L622
229,871
pydata/pandas-gbq
pandas_gbq/gbq.py
GbqConnector.schema_is_subset
def schema_is_subset(self, dataset_id, table_id, schema): """Indicate whether the schema to be uploaded is a subset Compare the BigQuery table identified in the parameters with the schema passed in and indicate whether a subset of the fields in the former are present in the latter. Order is not considered. Parameters ---------- dataset_id : str Name of the BigQuery dataset for the table table_id : str Name of the BigQuery table schema : list(dict) Schema for comparison. Each item should have a 'name' and a 'type' Returns ------- bool Whether the passed schema is a subset """ fields_remote = self._clean_schema_fields( self.schema(dataset_id, table_id) ) fields_local = self._clean_schema_fields(schema["fields"]) return all(field in fields_remote for field in fields_local)
python
def schema_is_subset(self, dataset_id, table_id, schema): fields_remote = self._clean_schema_fields( self.schema(dataset_id, table_id) ) fields_local = self._clean_schema_fields(schema["fields"]) return all(field in fields_remote for field in fields_local)
[ "def", "schema_is_subset", "(", "self", ",", "dataset_id", ",", "table_id", ",", "schema", ")", ":", "fields_remote", "=", "self", ".", "_clean_schema_fields", "(", "self", ".", "schema", "(", "dataset_id", ",", "table_id", ")", ")", "fields_local", "=", "se...
Indicate whether the schema to be uploaded is a subset Compare the BigQuery table identified in the parameters with the schema passed in and indicate whether a subset of the fields in the former are present in the latter. Order is not considered. Parameters ---------- dataset_id : str Name of the BigQuery dataset for the table table_id : str Name of the BigQuery table schema : list(dict) Schema for comparison. Each item should have a 'name' and a 'type' Returns ------- bool Whether the passed schema is a subset
[ "Indicate", "whether", "the", "schema", "to", "be", "uploaded", "is", "a", "subset" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L624-L652
229,872
pydata/pandas-gbq
pandas_gbq/gbq.py
_Table.exists
def exists(self, table_id): """ Check if a table exists in Google BigQuery Parameters ---------- table : str Name of table to be verified Returns ------- boolean true if table exists, otherwise false """ from google.api_core.exceptions import NotFound table_ref = self.client.dataset(self.dataset_id).table(table_id) try: self.client.get_table(table_ref) return True except NotFound: return False except self.http_error as ex: self.process_http_error(ex)
python
def exists(self, table_id): from google.api_core.exceptions import NotFound table_ref = self.client.dataset(self.dataset_id).table(table_id) try: self.client.get_table(table_ref) return True except NotFound: return False except self.http_error as ex: self.process_http_error(ex)
[ "def", "exists", "(", "self", ",", "table_id", ")", ":", "from", "google", ".", "api_core", ".", "exceptions", "import", "NotFound", "table_ref", "=", "self", ".", "client", ".", "dataset", "(", "self", ".", "dataset_id", ")", ".", "table", "(", "table_i...
Check if a table exists in Google BigQuery Parameters ---------- table : str Name of table to be verified Returns ------- boolean true if table exists, otherwise false
[ "Check", "if", "a", "table", "exists", "in", "Google", "BigQuery" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1217-L1239
229,873
pydata/pandas-gbq
pandas_gbq/gbq.py
_Table.create
def create(self, table_id, schema): """ Create a table in Google BigQuery given a table and schema Parameters ---------- table : str Name of table to be written schema : str Use the generate_bq_schema to generate your table schema from a dataframe. """ from google.cloud.bigquery import SchemaField from google.cloud.bigquery import Table if self.exists(table_id): raise TableCreationError( "Table {0} already " "exists".format(table_id) ) if not _Dataset(self.project_id, credentials=self.credentials).exists( self.dataset_id ): _Dataset( self.project_id, credentials=self.credentials, location=self.location, ).create(self.dataset_id) table_ref = self.client.dataset(self.dataset_id).table(table_id) table = Table(table_ref) # Manually create the schema objects, adding NULLABLE mode # as a workaround for # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4456 for field in schema["fields"]: if "mode" not in field: field["mode"] = "NULLABLE" table.schema = [ SchemaField.from_api_repr(field) for field in schema["fields"] ] try: self.client.create_table(table) except self.http_error as ex: self.process_http_error(ex)
python
def create(self, table_id, schema): from google.cloud.bigquery import SchemaField from google.cloud.bigquery import Table if self.exists(table_id): raise TableCreationError( "Table {0} already " "exists".format(table_id) ) if not _Dataset(self.project_id, credentials=self.credentials).exists( self.dataset_id ): _Dataset( self.project_id, credentials=self.credentials, location=self.location, ).create(self.dataset_id) table_ref = self.client.dataset(self.dataset_id).table(table_id) table = Table(table_ref) # Manually create the schema objects, adding NULLABLE mode # as a workaround for # https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4456 for field in schema["fields"]: if "mode" not in field: field["mode"] = "NULLABLE" table.schema = [ SchemaField.from_api_repr(field) for field in schema["fields"] ] try: self.client.create_table(table) except self.http_error as ex: self.process_http_error(ex)
[ "def", "create", "(", "self", ",", "table_id", ",", "schema", ")", ":", "from", "google", ".", "cloud", ".", "bigquery", "import", "SchemaField", "from", "google", ".", "cloud", ".", "bigquery", "import", "Table", "if", "self", ".", "exists", "(", "table...
Create a table in Google BigQuery given a table and schema Parameters ---------- table : str Name of table to be written schema : str Use the generate_bq_schema to generate your table schema from a dataframe.
[ "Create", "a", "table", "in", "Google", "BigQuery", "given", "a", "table", "and", "schema" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1241-L1286
229,874
pydata/pandas-gbq
pandas_gbq/gbq.py
_Table.delete
def delete(self, table_id): """ Delete a table in Google BigQuery Parameters ---------- table : str Name of table to be deleted """ from google.api_core.exceptions import NotFound if not self.exists(table_id): raise NotFoundException("Table does not exist") table_ref = self.client.dataset(self.dataset_id).table(table_id) try: self.client.delete_table(table_ref) except NotFound: # Ignore 404 error which may occur if table already deleted pass except self.http_error as ex: self.process_http_error(ex)
python
def delete(self, table_id): from google.api_core.exceptions import NotFound if not self.exists(table_id): raise NotFoundException("Table does not exist") table_ref = self.client.dataset(self.dataset_id).table(table_id) try: self.client.delete_table(table_ref) except NotFound: # Ignore 404 error which may occur if table already deleted pass except self.http_error as ex: self.process_http_error(ex)
[ "def", "delete", "(", "self", ",", "table_id", ")", ":", "from", "google", ".", "api_core", ".", "exceptions", "import", "NotFound", "if", "not", "self", ".", "exists", "(", "table_id", ")", ":", "raise", "NotFoundException", "(", "\"Table does not exist\"", ...
Delete a table in Google BigQuery Parameters ---------- table : str Name of table to be deleted
[ "Delete", "a", "table", "in", "Google", "BigQuery" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1288-L1308
229,875
pydata/pandas-gbq
pandas_gbq/gbq.py
_Dataset.exists
def exists(self, dataset_id): """ Check if a dataset exists in Google BigQuery Parameters ---------- dataset_id : str Name of dataset to be verified Returns ------- boolean true if dataset exists, otherwise false """ from google.api_core.exceptions import NotFound try: self.client.get_dataset(self.client.dataset(dataset_id)) return True except NotFound: return False except self.http_error as ex: self.process_http_error(ex)
python
def exists(self, dataset_id): from google.api_core.exceptions import NotFound try: self.client.get_dataset(self.client.dataset(dataset_id)) return True except NotFound: return False except self.http_error as ex: self.process_http_error(ex)
[ "def", "exists", "(", "self", ",", "dataset_id", ")", ":", "from", "google", ".", "api_core", ".", "exceptions", "import", "NotFound", "try", ":", "self", ".", "client", ".", "get_dataset", "(", "self", ".", "client", ".", "dataset", "(", "dataset_id", "...
Check if a dataset exists in Google BigQuery Parameters ---------- dataset_id : str Name of dataset to be verified Returns ------- boolean true if dataset exists, otherwise false
[ "Check", "if", "a", "dataset", "exists", "in", "Google", "BigQuery" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1328-L1349
229,876
pydata/pandas-gbq
pandas_gbq/gbq.py
_Dataset.create
def create(self, dataset_id): """ Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written """ from google.cloud.bigquery import Dataset if self.exists(dataset_id): raise DatasetCreationError( "Dataset {0} already " "exists".format(dataset_id) ) dataset = Dataset(self.client.dataset(dataset_id)) if self.location is not None: dataset.location = self.location try: self.client.create_dataset(dataset) except self.http_error as ex: self.process_http_error(ex)
python
def create(self, dataset_id): from google.cloud.bigquery import Dataset if self.exists(dataset_id): raise DatasetCreationError( "Dataset {0} already " "exists".format(dataset_id) ) dataset = Dataset(self.client.dataset(dataset_id)) if self.location is not None: dataset.location = self.location try: self.client.create_dataset(dataset) except self.http_error as ex: self.process_http_error(ex)
[ "def", "create", "(", "self", ",", "dataset_id", ")", ":", "from", "google", ".", "cloud", ".", "bigquery", "import", "Dataset", "if", "self", ".", "exists", "(", "dataset_id", ")", ":", "raise", "DatasetCreationError", "(", "\"Dataset {0} already \"", "\"exis...
Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written
[ "Create", "a", "dataset", "in", "Google", "BigQuery" ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1351-L1374
229,877
pydata/pandas-gbq
pandas_gbq/schema.py
update_schema
def update_schema(schema_old, schema_new): """ Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_new: the new schema which will overwrite/extend the old """ old_fields = schema_old["fields"] new_fields = schema_new["fields"] output_fields = list(old_fields) field_indices = {field["name"]: i for i, field in enumerate(output_fields)} for field in new_fields: name = field["name"] if name in field_indices: # replace old field with new field of same name output_fields[field_indices[name]] = field else: # add new field output_fields.append(field) return {"fields": output_fields}
python
def update_schema(schema_old, schema_new): old_fields = schema_old["fields"] new_fields = schema_new["fields"] output_fields = list(old_fields) field_indices = {field["name"]: i for i, field in enumerate(output_fields)} for field in new_fields: name = field["name"] if name in field_indices: # replace old field with new field of same name output_fields[field_indices[name]] = field else: # add new field output_fields.append(field) return {"fields": output_fields}
[ "def", "update_schema", "(", "schema_old", ",", "schema_new", ")", ":", "old_fields", "=", "schema_old", "[", "\"fields\"", "]", "new_fields", "=", "schema_new", "[", "\"fields\"", "]", "output_fields", "=", "list", "(", "old_fields", ")", "field_indices", "=", ...
Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_new: the new schema which will overwrite/extend the old
[ "Given", "an", "old", "BigQuery", "schema", "update", "it", "with", "a", "new", "one", "." ]
e590317b3325939ede7563f49aa6b163bb803b77
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/schema.py#L38-L64
229,878
openwisp/django-freeradius
django_freeradius/base/models.py
AutoUsernameMixin.clean
def clean(self): """ automatically sets username """ if self.user: self.username = self.user.username elif not self.username: raise ValidationError({ 'username': _NOT_BLANK_MESSAGE, 'user': _NOT_BLANK_MESSAGE })
python
def clean(self): if self.user: self.username = self.user.username elif not self.username: raise ValidationError({ 'username': _NOT_BLANK_MESSAGE, 'user': _NOT_BLANK_MESSAGE })
[ "def", "clean", "(", "self", ")", ":", "if", "self", ".", "user", ":", "self", ".", "username", "=", "self", ".", "user", ".", "username", "elif", "not", "self", ".", "username", ":", "raise", "ValidationError", "(", "{", "'username'", ":", "_NOT_BLANK...
automatically sets username
[ "automatically", "sets", "username" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/base/models.py#L129-L139
229,879
openwisp/django-freeradius
django_freeradius/base/models.py
AutoGroupnameMixin.clean
def clean(self): """ automatically sets groupname """ super().clean() if self.group: self.groupname = self.group.name elif not self.groupname: raise ValidationError({ 'groupname': _NOT_BLANK_MESSAGE, 'group': _NOT_BLANK_MESSAGE })
python
def clean(self): super().clean() if self.group: self.groupname = self.group.name elif not self.groupname: raise ValidationError({ 'groupname': _NOT_BLANK_MESSAGE, 'group': _NOT_BLANK_MESSAGE })
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "if", "self", ".", "group", ":", "self", ".", "groupname", "=", "self", ".", "group", ".", "name", "elif", "not", "self", ".", "groupname", ":", "raise", "ValidationE...
automatically sets groupname
[ "automatically", "sets", "groupname" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/base/models.py#L143-L154
229,880
openwisp/django-freeradius
django_freeradius/base/models.py
AbstractRadiusGroup.get_default_queryset
def get_default_queryset(self): """ looks for default groups excluding the current one overridable by openwisp-radius and other 3rd party apps """ return self.__class__.objects.exclude(pk=self.pk) \ .filter(default=True)
python
def get_default_queryset(self): return self.__class__.objects.exclude(pk=self.pk) \ .filter(default=True)
[ "def", "get_default_queryset", "(", "self", ")", ":", "return", "self", ".", "__class__", ".", "objects", ".", "exclude", "(", "pk", "=", "self", ".", "pk", ")", ".", "filter", "(", "default", "=", "True", ")" ]
looks for default groups excluding the current one overridable by openwisp-radius and other 3rd party apps
[ "looks", "for", "default", "groups", "excluding", "the", "current", "one", "overridable", "by", "openwisp", "-", "radius", "and", "other", "3rd", "party", "apps" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/base/models.py#L543-L549
229,881
openwisp/django-freeradius
django_freeradius/api/views.py
AuthorizeView.get_user
def get_user(self, request): """ return active user or ``None`` """ try: return User.objects.get(username=request.data.get('username'), is_active=True) except User.DoesNotExist: return None
python
def get_user(self, request): try: return User.objects.get(username=request.data.get('username'), is_active=True) except User.DoesNotExist: return None
[ "def", "get_user", "(", "self", ",", "request", ")", ":", "try", ":", "return", "User", ".", "objects", ".", "get", "(", "username", "=", "request", ".", "data", ".", "get", "(", "'username'", ")", ",", "is_active", "=", "True", ")", "except", "User"...
return active user or ``None``
[ "return", "active", "user", "or", "None" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/api/views.py#L62-L70
229,882
openwisp/django-freeradius
django_freeradius/api/views.py
AuthorizeView.authenticate_user
def authenticate_user(self, request, user): """ returns ``True`` if the password value supplied is a valid user password or a valid user token can be overridden to implement more complex checks """ return user.check_password(request.data.get('password')) or \ self.check_user_token(request, user)
python
def authenticate_user(self, request, user): return user.check_password(request.data.get('password')) or \ self.check_user_token(request, user)
[ "def", "authenticate_user", "(", "self", ",", "request", ",", "user", ")", ":", "return", "user", ".", "check_password", "(", "request", ".", "data", ".", "get", "(", "'password'", ")", ")", "or", "self", ".", "check_user_token", "(", "request", ",", "us...
returns ``True`` if the password value supplied is a valid user password or a valid user token can be overridden to implement more complex checks
[ "returns", "True", "if", "the", "password", "value", "supplied", "is", "a", "valid", "user", "password", "or", "a", "valid", "user", "token", "can", "be", "overridden", "to", "implement", "more", "complex", "checks" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/api/views.py#L72-L79
229,883
openwisp/django-freeradius
django_freeradius/api/views.py
AuthorizeView.check_user_token
def check_user_token(self, request, user): """ if user has no password set and has at least 1 social account this is probably a social login, the password field is the user's personal auth token """ if not app_settings.REST_USER_TOKEN_ENABLED: return False try: token = Token.objects.get( user=user, key=request.data.get('password') ) except Token.DoesNotExist: token = None else: if app_settings.DISPOSABLE_USER_TOKEN: token.delete() finally: return token is not None
python
def check_user_token(self, request, user): if not app_settings.REST_USER_TOKEN_ENABLED: return False try: token = Token.objects.get( user=user, key=request.data.get('password') ) except Token.DoesNotExist: token = None else: if app_settings.DISPOSABLE_USER_TOKEN: token.delete() finally: return token is not None
[ "def", "check_user_token", "(", "self", ",", "request", ",", "user", ")", ":", "if", "not", "app_settings", ".", "REST_USER_TOKEN_ENABLED", ":", "return", "False", "try", ":", "token", "=", "Token", ".", "objects", ".", "get", "(", "user", "=", "user", "...
if user has no password set and has at least 1 social account this is probably a social login, the password field is the user's personal auth token
[ "if", "user", "has", "no", "password", "set", "and", "has", "at", "least", "1", "social", "account", "this", "is", "probably", "a", "social", "login", "the", "password", "field", "is", "the", "user", "s", "personal", "auth", "token" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/api/views.py#L81-L100
229,884
openwisp/django-freeradius
django_freeradius/api/views.py
PostAuthView.post
def post(self, request, *args, **kwargs): """ Sets the response data to None in order to instruct FreeRADIUS to avoid processing the response body """ response = self.create(request, *args, **kwargs) response.data = None return response
python
def post(self, request, *args, **kwargs): response = self.create(request, *args, **kwargs) response.data = None return response
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "create", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "response", ".", "data", "=", "None", "return...
Sets the response data to None in order to instruct FreeRADIUS to avoid processing the response body
[ "Sets", "the", "response", "data", "to", "None", "in", "order", "to", "instruct", "FreeRADIUS", "to", "avoid", "processing", "the", "response", "body" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/api/views.py#L110-L117
229,885
openwisp/django-freeradius
django_freeradius/social/views.py
RedirectCaptivePageView.authorize
def authorize(self, request, *args, **kwargs): """ authorization logic raises PermissionDenied if user is not authorized """ user = request.user if not user.is_authenticated or not user.socialaccount_set.exists(): raise PermissionDenied()
python
def authorize(self, request, *args, **kwargs): user = request.user if not user.is_authenticated or not user.socialaccount_set.exists(): raise PermissionDenied()
[ "def", "authorize", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user", "=", "request", ".", "user", "if", "not", "user", ".", "is_authenticated", "or", "not", "user", ".", "socialaccount_set", ".", "exists", "(", ...
authorization logic raises PermissionDenied if user is not authorized
[ "authorization", "logic", "raises", "PermissionDenied", "if", "user", "is", "not", "authorized" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/social/views.py#L22-L29
229,886
openwisp/django-freeradius
django_freeradius/social/views.py
RedirectCaptivePageView.get_redirect_url
def get_redirect_url(self, request): """ refreshes token and returns the captive page URL """ cp = request.GET.get('cp') user = request.user Token.objects.filter(user=user).delete() token = Token.objects.create(user=user) return '{0}?username={1}&token={2}'.format(cp, user.username, token.key)
python
def get_redirect_url(self, request): cp = request.GET.get('cp') user = request.user Token.objects.filter(user=user).delete() token = Token.objects.create(user=user) return '{0}?username={1}&token={2}'.format(cp, user.username, token.key)
[ "def", "get_redirect_url", "(", "self", ",", "request", ")", ":", "cp", "=", "request", ".", "GET", ".", "get", "(", "'cp'", ")", "user", "=", "request", ".", "user", "Token", ".", "objects", ".", "filter", "(", "user", "=", "user", ")", ".", "dele...
refreshes token and returns the captive page URL
[ "refreshes", "token", "and", "returns", "the", "captive", "page", "URL" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/social/views.py#L31-L39
229,887
openwisp/django-freeradius
setup.py
get_install_requires
def get_install_requires(): """ parse requirements.txt, ignore links, exclude comments """ requirements = [] for line in open('requirements.txt').readlines(): # skip to next iteration if comment or empty line if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'): continue # add line to requirements requirements.append(line) return requirements
python
def get_install_requires(): requirements = [] for line in open('requirements.txt').readlines(): # skip to next iteration if comment or empty line if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'): continue # add line to requirements requirements.append(line) return requirements
[ "def", "get_install_requires", "(", ")", ":", "requirements", "=", "[", "]", "for", "line", "in", "open", "(", "'requirements.txt'", ")", ".", "readlines", "(", ")", ":", "# skip to next iteration if comment or empty line", "if", "line", ".", "startswith", "(", ...
parse requirements.txt, ignore links, exclude comments
[ "parse", "requirements", ".", "txt", "ignore", "links", "exclude", "comments" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/setup.py#L10-L21
229,888
openwisp/django-freeradius
django_freeradius/base/admin.py
AbstractUserAdmin.get_inline_instances
def get_inline_instances(self, request, obj=None): """ Adds RadiusGroupInline only for existing objects """ inlines = super().get_inline_instances(request, obj) if obj: usergroup = RadiusUserGroupInline(self.model, self.admin_site) inlines.append(usergroup) return inlines
python
def get_inline_instances(self, request, obj=None): inlines = super().get_inline_instances(request, obj) if obj: usergroup = RadiusUserGroupInline(self.model, self.admin_site) inlines.append(usergroup) return inlines
[ "def", "get_inline_instances", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "inlines", "=", "super", "(", ")", ".", "get_inline_instances", "(", "request", ",", "obj", ")", "if", "obj", ":", "usergroup", "=", "RadiusUserGroupInline", "("...
Adds RadiusGroupInline only for existing objects
[ "Adds", "RadiusGroupInline", "only", "for", "existing", "objects" ]
a9dd0710327eb33b49dd01097fc3b76048894963
https://github.com/openwisp/django-freeradius/blob/a9dd0710327eb33b49dd01097fc3b76048894963/django_freeradius/base/admin.py#L296-L305
229,889
HazyResearch/fonduer
src/fonduer/parser/models/utils.py
construct_stable_id
def construct_stable_id( parent_context, polymorphic_type, relative_char_offset_start, relative_char_offset_end, ): """ Contruct a stable ID for a Context given its parent and its character offsets relative to the parent. """ doc_id, _, parent_doc_char_start, _ = split_stable_id(parent_context.stable_id) start = parent_doc_char_start + relative_char_offset_start end = parent_doc_char_start + relative_char_offset_end return f"{doc_id}::{polymorphic_type}:{start}:{end}"
python
def construct_stable_id( parent_context, polymorphic_type, relative_char_offset_start, relative_char_offset_end, ): doc_id, _, parent_doc_char_start, _ = split_stable_id(parent_context.stable_id) start = parent_doc_char_start + relative_char_offset_start end = parent_doc_char_start + relative_char_offset_end return f"{doc_id}::{polymorphic_type}:{start}:{end}"
[ "def", "construct_stable_id", "(", "parent_context", ",", "polymorphic_type", ",", "relative_char_offset_start", ",", "relative_char_offset_end", ",", ")", ":", "doc_id", ",", "_", ",", "parent_doc_char_start", ",", "_", "=", "split_stable_id", "(", "parent_context", ...
Contruct a stable ID for a Context given its parent and its character offsets relative to the parent.
[ "Contruct", "a", "stable", "ID", "for", "a", "Context", "given", "its", "parent", "and", "its", "character", "offsets", "relative", "to", "the", "parent", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/parser/models/utils.py#L4-L17
229,890
HazyResearch/fonduer
src/fonduer/features/feature_libs/visual_features.py
vizlib_unary_features
def vizlib_unary_features(span): """ Visual-related features for a single span """ if not span.sentence.is_visual(): return for f in get_visual_aligned_lemmas(span): yield f"ALIGNED_{f}", DEF_VALUE for page in set(span.get_attrib_tokens("page")): yield f"PAGE_[{page}]", DEF_VALUE
python
def vizlib_unary_features(span): if not span.sentence.is_visual(): return for f in get_visual_aligned_lemmas(span): yield f"ALIGNED_{f}", DEF_VALUE for page in set(span.get_attrib_tokens("page")): yield f"PAGE_[{page}]", DEF_VALUE
[ "def", "vizlib_unary_features", "(", "span", ")", ":", "if", "not", "span", ".", "sentence", ".", "is_visual", "(", ")", ":", "return", "for", "f", "in", "get_visual_aligned_lemmas", "(", "span", ")", ":", "yield", "f\"ALIGNED_{f}\"", ",", "DEF_VALUE", "for"...
Visual-related features for a single span
[ "Visual", "-", "related", "features", "for", "a", "single", "span" ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/features/feature_libs/visual_features.py#L69-L80
229,891
HazyResearch/fonduer
src/fonduer/features/feature_libs/visual_features.py
vizlib_binary_features
def vizlib_binary_features(span1, span2): """ Visual-related features for a pair of spans """ if same_page((span1, span2)): yield "SAME_PAGE", DEF_VALUE if is_horz_aligned((span1, span2)): yield "HORZ_ALIGNED", DEF_VALUE if is_vert_aligned((span1, span2)): yield "VERT_ALIGNED", DEF_VALUE if is_vert_aligned_left((span1, span2)): yield "VERT_ALIGNED_LEFT", DEF_VALUE if is_vert_aligned_right((span1, span2)): yield "VERT_ALIGNED_RIGHT", DEF_VALUE if is_vert_aligned_center((span1, span2)): yield "VERT_ALIGNED_CENTER", DEF_VALUE
python
def vizlib_binary_features(span1, span2): if same_page((span1, span2)): yield "SAME_PAGE", DEF_VALUE if is_horz_aligned((span1, span2)): yield "HORZ_ALIGNED", DEF_VALUE if is_vert_aligned((span1, span2)): yield "VERT_ALIGNED", DEF_VALUE if is_vert_aligned_left((span1, span2)): yield "VERT_ALIGNED_LEFT", DEF_VALUE if is_vert_aligned_right((span1, span2)): yield "VERT_ALIGNED_RIGHT", DEF_VALUE if is_vert_aligned_center((span1, span2)): yield "VERT_ALIGNED_CENTER", DEF_VALUE
[ "def", "vizlib_binary_features", "(", "span1", ",", "span2", ")", ":", "if", "same_page", "(", "(", "span1", ",", "span2", ")", ")", ":", "yield", "\"SAME_PAGE\"", ",", "DEF_VALUE", "if", "is_horz_aligned", "(", "(", "span1", ",", "span2", ")", ")", ":",...
Visual-related features for a pair of spans
[ "Visual", "-", "related", "features", "for", "a", "pair", "of", "spans" ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/features/feature_libs/visual_features.py#L83-L103
229,892
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionNgrams.apply
def apply(self, doc): """Generate MentionNgrams from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionNgrams.apply() must be of type Document" ) for sentence in doc.sentences: for ts in Ngrams.apply(self, sentence): yield ts
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionNgrams.apply() must be of type Document" ) for sentence in doc.sentences: for ts in Ngrams.apply(self, sentence): yield ts
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionNgrams.apply() must be of type Document\"", ")", "for", "sentence", "in", "doc", ".", "sen...
Generate MentionNgrams from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionNgrams", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Sentences", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L136-L150
229,893
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionFigures.apply
def apply(self, doc): """ Generate MentionFigures from a Document by parsing all of its Figures. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionFigures.apply() must be of type Document" ) for figure in doc.figures: if self.types is None or any( figure.url.lower().endswith(type) for type in self.types ): yield TemporaryFigureMention(figure)
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionFigures.apply() must be of type Document" ) for figure in doc.figures: if self.types is None or any( figure.url.lower().endswith(type) for type in self.types ): yield TemporaryFigureMention(figure)
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionFigures.apply() must be of type Document\"", ")", "for", "figure", "in", "doc", ".", "figu...
Generate MentionFigures from a Document by parsing all of its Figures. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionFigures", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Figures", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L169-L186
229,894
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionSentences.apply
def apply(self, doc): """ Generate MentionSentences from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionSentences.apply() must be of type Document" ) for sentence in doc.sentences: yield TemporarySpanMention( char_start=0, char_end=len(sentence.text) - 1, sentence=sentence )
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionSentences.apply() must be of type Document" ) for sentence in doc.sentences: yield TemporarySpanMention( char_start=0, char_end=len(sentence.text) - 1, sentence=sentence )
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionSentences.apply() must be of type Document\"", ")", "for", "sentence", "in", "doc", ".", "...
Generate MentionSentences from a Document by parsing all of its Sentences. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionSentences", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Sentences", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L196-L212
229,895
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionParagraphs.apply
def apply(self, doc): """ Generate MentionParagraphs from a Document by parsing all of its Paragraphs. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionParagraphs.apply() must be of type Document" ) for paragraph in doc.paragraphs: yield TemporaryParagraphMention(paragraph)
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionParagraphs.apply() must be of type Document" ) for paragraph in doc.paragraphs: yield TemporaryParagraphMention(paragraph)
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionParagraphs.apply() must be of type Document\"", ")", "for", "paragraph", "in", "doc", ".", ...
Generate MentionParagraphs from a Document by parsing all of its Paragraphs. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionParagraphs", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Paragraphs", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L222-L236
229,896
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionCaptions.apply
def apply(self, doc): """ Generate MentionCaptions from a Document by parsing all of its Captions. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionCaptions.apply() must be of type Document" ) for caption in doc.captions: yield TemporaryCaptionMention(caption)
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionCaptions.apply() must be of type Document" ) for caption in doc.captions: yield TemporaryCaptionMention(caption)
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionCaptions.apply() must be of type Document\"", ")", "for", "caption", "in", "doc", ".", "ca...
Generate MentionCaptions from a Document by parsing all of its Captions. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionCaptions", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Captions", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L246-L260
229,897
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionCells.apply
def apply(self, doc): """ Generate MentionCells from a Document by parsing all of its Cells. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionCells.apply() must be of type Document" ) for cell in doc.cells: yield TemporaryCellMention(cell)
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionCells.apply() must be of type Document" ) for cell in doc.cells: yield TemporaryCellMention(cell)
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionCells.apply() must be of type Document\"", ")", "for", "cell", "in", "doc", ".", "cells", ...
Generate MentionCells from a Document by parsing all of its Cells. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionCells", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Cells", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L270-L284
229,898
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionTables.apply
def apply(self, doc): """ Generate MentionTables from a Document by parsing all of its Tables. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionTables.apply() must be of type Document" ) for table in doc.tables: yield TemporaryTableMention(table)
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionTables.apply() must be of type Document" ) for table in doc.tables: yield TemporaryTableMention(table)
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionTables.apply() must be of type Document\"", ")", "for", "table", "in", "doc", ".", "tables...
Generate MentionTables from a Document by parsing all of its Tables. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionTables", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Tables", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L294-L308
229,899
HazyResearch/fonduer
src/fonduer/candidates/mentions.py
MentionSections.apply
def apply(self, doc): """ Generate MentionSections from a Document by parsing all of its Sections. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``. """ if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionSections.apply() must be of type Document" ) for section in doc.sections: yield TemporarySectionMention(section)
python
def apply(self, doc): if not isinstance(doc, Document): raise TypeError( "Input Contexts to MentionSections.apply() must be of type Document" ) for section in doc.sections: yield TemporarySectionMention(section)
[ "def", "apply", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "Document", ")", ":", "raise", "TypeError", "(", "\"Input Contexts to MentionSections.apply() must be of type Document\"", ")", "for", "section", "in", "doc", ".", "se...
Generate MentionSections from a Document by parsing all of its Sections. :param doc: The ``Document`` to parse. :type doc: ``Document`` :raises TypeError: If the input doc is not of type ``Document``.
[ "Generate", "MentionSections", "from", "a", "Document", "by", "parsing", "all", "of", "its", "Sections", "." ]
4520f86a716f03dcca458a9f4bddac75b4e7068f
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/mentions.py#L318-L332