text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def selectByIdx(self, rowIdxs): 'Select given row indexes, without progress bar.' self.select((self.rows[i] for i in rowIdxs), progress=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unselectByIdx(self, rowIdxs): 'Unselect given row indexes, without progress bar.' self.unselect((self.rows[i] for i in rowIdxs), progress=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rowkey(self, row): 'returns a tuple of the key for the given row' return tuple(c.getTypedValueOrException(row) for c in self.keyCols)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getTypedValue(self, row): 'Returns the properly-typed value for the given row at this column.' return wrapply(self.type, wrapply(self.getValue, row))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setValueSafe(self, row, value): 'setValue and ignore exceptions' try: return self.setValue(row, value) except Exception as e: exceptionCaught(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_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 ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_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}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(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 })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(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 })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, docs, clear=True, parallelism=None, progress_bar=True): """Run the MentionExtractor. :Example: To extract mentions from a set of training documents using 4 cores:: mention_extractor.apply(train_docs, parallelism=4) :param docs: Set of documents to extract from. :param clear: Whether or not to clear the existing Mentions beforehand. :type clear: bool :param parallelism: How many threads to use for extraction. This will override the parallelism value used to initialize the MentionExtractor if it is provided. :type parallelism: int :param progress_bar: Whether or not to display a progress bar. The progress bar is measured per document. :type progress_bar: bool """
super(MentionExtractor, self).apply( docs, clear=clear, parallelism=parallelism, progress_bar=progress_bar )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """Delete Mentions of each class in the extractor from the given split."""
# Create set of candidate_subclasses associated with each mention_subclass cand_subclasses = set() for mentions, tablename in [ (_[1][0], _[1][1]) for _ in candidate_subclasses.values() ]: for mention in mentions: if mention in self.mention_classes: cand_subclasses.add(tablename) # First, clear all the Mentions. This will cascade and remove the # mention_subclasses and corresponding candidate_subclasses. for mention_class in self.mention_classes: logger.info(f"Clearing table: {mention_class.__tablename__}") self.session.query(Mention).filter_by( type=mention_class.__tablename__ ).delete(synchronize_session="fetch") # Next, clear the Candidates. This is done manually because we have # no cascading relationship from candidate_subclass to Candidate. for cand_subclass in cand_subclasses: logger.info(f"Cascading to clear table: {cand_subclass}") self.session.query(Candidate).filter_by(type=cand_subclass).delete( synchronize_session="fetch" )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_all(self): """Delete all Mentions from given split the database."""
logger.info("Clearing ALL Mentions.") self.session.query(Mention).delete(synchronize_session="fetch") # With no Mentions, there should be no Candidates also self.session.query(Candidate).delete(synchronize_session="fetch") logger.info("Cleared ALL Mentions (and Candidates).")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mentions(self, docs=None, sort=False): """Return a list of lists of the mentions associated with this extractor. Each list of the return will contain the Mentions for one of the mention classes associated with the MentionExtractor. :param docs: If provided, return Mentions from these documents. Else, return all Mentions. :param sort: If sort is True, then return all Mentions sorted by stable_id. :type sort: bool :return: Mentions for each mention_class. :rtype: List of lists. """
result = [] if docs: docs = docs if isinstance(docs, (list, tuple)) else [docs] # Get cands from all splits for mention_class in self.mention_classes: mentions = ( self.session.query(mention_class) .filter(mention_class.document_id.in_([doc.id for doc in docs])) .order_by(mention_class.id) .all() ) if sort: mentions = sorted(mentions, key=lambda x: x[0].get_stable_id()) result.append(mentions) else: for mention_class in self.mention_classes: mentions = ( self.session.query(mention_class).order_by(mention_class.id).all() ) if sort: mentions = sorted(mentions, key=lambda x: x[0].get_stable_id()) result.append(mentions) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, doc, clear, **kwargs): """Extract mentions from the given Document. :param doc: A document to process. :param clear: Whether or not to clear the existing database entries. """
# Reattach doc with the current session or DetachedInstanceError happens doc = self.session.merge(doc) # Iterate over each mention class for i, mention_class in enumerate(self.mention_classes): tc_to_insert = defaultdict(list) # Generate TemporaryContexts that are children of the context using # the mention_space and filtered by the Matcher self.child_context_set.clear() for tc in self.matchers[i].apply(self.mention_spaces[i].apply(doc)): rec = tc._load_id_or_insert(self.session) if rec: tc_to_insert[tc._get_table()].append(rec) self.child_context_set.add(tc) # Bulk insert temporary contexts for table, records in tc_to_insert.items(): stmt = insert(table.__table__).values(records) self.session.execute(stmt) # Generates and persists mentions mention_args = {"document_id": doc.id} for child_context in self.child_context_set: # Assemble mention arguments for arg_name in mention_class.__argnames__: mention_args[arg_name + "_id"] = child_context.id # Checking for existence if not clear: q = select([mention_class.id]) for key, value in list(mention_args.items()): q = q.where(getattr(mention_class, key) == value) mention_id = self.session.execute(q).first() if mention_id is not None: continue # Add Mention to session yield mention_class(**mention_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, contents): """Parse the document. :param contents: The text contents of the document. :rtype: a *generator* of tokenized text. """
i = 0 for text in contents.split(self.delim): if not len(text.strip()): continue words = text.split() char_offsets = [0] + [ int(_) for _ in np.cumsum([len(x) + 1 for x in words])[:-1] ] text = " ".join(words) yield { "text": text, "words": words, "pos_tags": [""] * len(words), "ner_tags": [""] * len(words), "lemmas": [""] * len(words), "dep_parents": [0] * len(words), "dep_labels": [""] * len(words), "char_offsets": char_offsets, "abs_char_offsets": char_offsets, } i += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strlib_unary_features(span): """ Structural-related features for a single span """
if not span.sentence.is_structural(): return yield f"TAG_{get_tag(span)}", DEF_VALUE for attr in get_attributes(span): yield f"HTML_ATTR_{attr}", DEF_VALUE yield f"PARENT_TAG_{get_parent_tag(span)}", DEF_VALUE prev_tags = get_prev_sibling_tags(span) if len(prev_tags): yield f"PREV_SIB_TAG_{prev_tags[-1]}", DEF_VALUE yield f"NODE_POS_{len(prev_tags) + 1}", DEF_VALUE else: yield "FIRST_NODE", DEF_VALUE next_tags = get_next_sibling_tags(span) if len(next_tags): yield f"NEXT_SIB_TAG_{next_tags[0]}", DEF_VALUE else: yield "LAST_NODE", DEF_VALUE yield f"ANCESTOR_CLASS_[{' '.join(get_ancestor_class_names(span))}]", DEF_VALUE yield f"ANCESTOR_TAG_[{' '.join(get_ancestor_tag_names(span))}]", DEF_VALUE yield f"ANCESTOR_ID_[{' '.join(get_ancestor_id_names(span))}]", DEF_VALUE
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_node(type, name, content): """ Wrap up content in to a html node. :param type: content type (e.g., doc, section, text, figure) :type path: str :param name: content name (e.g., the name of the section) :type path: str :param name: actual content :type path: str :return: new String with content in html format """
if type == "doc": return f"<html>{content}</html>" if type == "section": return f"<section name='{name}'>{content}</section>" if type == "text": return f"<p name='{name}'>{content}</p>" if type == "figure": return f"<img name='{name}' src='{content}'/>"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_span(x, idx=0): """Convert a Candidate, Mention, or Span to a span."""
if isinstance(x, Candidate): return x[idx].context elif isinstance(x, Mention): return x.context elif isinstance(x, TemporarySpanMention): return x else: raise ValueError(f"{type(x)} is an invalid argument type")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_spans(x): """Convert a Candidate, Mention, or Span to a list of spans."""
if isinstance(x, Candidate): return [_to_span(m) for m in x] elif isinstance(x, Mention): return [x.context] elif isinstance(x, TemporarySpanMention): return [x] else: raise ValueError(f"{type(x)} is an invalid argument type")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_matches(lf, candidate_set, match_values=[1, -1]): """Return a list of candidates that are matched by a particular LF. A simple helper function to see how many matches (non-zero by default) an LF gets. :param lf: The labeling function to apply to the candidate_set :param candidate_set: The set of candidates to evaluate :param match_values: An option list of the values to consider as matched. [1, -1] by default. :rtype: a list of candidates """
logger = logging.getLogger(__name__) matches = [] for c in candidate_set: label = lf(c) if label in match_values: matches.append(c) logger.info(f"{len(matches)} matches") return matches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, docs=None, split=0, parallelism=None, progress_bar=True): """Update the features of the specified candidates. :param docs: If provided, apply features to all the candidates in these documents. :param split: If docs is None, apply features to the candidates in this particular split. :type split: int :param parallelism: How many threads to use for extraction. This will override the parallelism value used to initialize the Featurizer if it is provided. :type parallelism: int :param progress_bar: Whether or not to display a progress bar. The progress bar is measured per document. :type progress_bar: bool """
self.apply( docs=docs, split=split, train=True, clear=False, parallelism=parallelism, progress_bar=progress_bar, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply( self, docs=None, split=0, train=False, clear=True, parallelism=None, progress_bar=True, ): """Apply features to the specified candidates. :param docs: If provided, apply features to all the candidates in these documents. :param split: If docs is None, apply features to the candidates in this particular split. :type split: int :param train: Whether or not to update the global key set of features and the features of candidates. :type train: bool :param clear: Whether or not to clear the features table before applying features. :type clear: bool :param parallelism: How many threads to use for extraction. This will override the parallelism value used to initialize the Featurizer if it is provided. :type parallelism: int :param progress_bar: Whether or not to display a progress bar. The progress bar is measured per document. :type progress_bar: bool """
if docs: # Call apply on the specified docs for all splits split = ALL_SPLITS super(Featurizer, self).apply( docs, split=split, train=train, clear=clear, parallelism=parallelism, progress_bar=progress_bar, ) # Needed to sync the bulk operations self.session.commit() else: # Only grab the docs containing candidates from the given split. split_docs = get_docs_from_split( self.session, self.candidate_classes, split ) super(Featurizer, self).apply( split_docs, split=split, train=train, clear=clear, parallelism=parallelism, progress_bar=progress_bar, ) # Needed to sync the bulk operations self.session.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop_keys(self, keys, candidate_classes=None): """Drop the specified keys from FeatureKeys. :param keys: A list of FeatureKey names to delete. :type keys: list, tuple :param candidate_classes: A list of the Candidates to drop the key for. If None, drops the keys for all candidate classes associated with this Featurizer. :type candidate_classes: list, tuple """
# Make sure keys is iterable keys = keys if isinstance(keys, (list, tuple)) else [keys] # Make sure candidate_classes is iterable if candidate_classes: candidate_classes = ( candidate_classes if isinstance(candidate_classes, (list, tuple)) else [candidate_classes] ) # Ensure only candidate classes associated with the featurizer # are used. candidate_classes = [ _.__tablename__ for _ in candidate_classes if _ in self.candidate_classes ] if len(candidate_classes) == 0: logger.warning( "You didn't specify valid candidate classes for this featurizer." ) return # If unspecified, just use all candidate classes else: candidate_classes = [_.__tablename__ for _ in self.candidate_classes] # build dict for use by utils key_map = dict() for key in keys: key_map[key] = set(candidate_classes) drop_keys(self.session, FeatureKey, key_map)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, train=False, split=0): """Delete Features of each class from the database. :param train: Whether or not to clear the FeatureKeys :type train: bool :param split: Which split of candidates to clear features from. :type split: int """
# Clear Features for the candidates in the split passed in. logger.info(f"Clearing Features (split {split})") sub_query = ( self.session.query(Candidate.id).filter(Candidate.split == split).subquery() ) query = self.session.query(Feature).filter(Feature.candidate_id.in_(sub_query)) query.delete(synchronize_session="fetch") # Delete all old annotation keys if train: logger.debug(f"Clearing all FeatureKeys from {self.candidate_classes}...") drop_all_keys(self.session, FeatureKey, self.candidate_classes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_all(self): """Delete all Features."""
logger.info("Clearing ALL Features and FeatureKeys.") self.session.query(Feature).delete(synchronize_session="fetch") self.session.query(FeatureKey).delete(synchronize_session="fetch")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge(x, y): """Merge two nested dictionaries. Overwrite values in x with values in y."""
merged = {**x, **y} xkeys = x.keys() for key in xkeys: if isinstance(x[key], dict) and key in y: merged[key] = _merge(x[key], y[key]) return merged
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(path=os.getcwd()): """Search for settings file in root of project and its parents."""
config = default tries = 0 current_dir = path while current_dir and tries < MAX_CONFIG_SEARCH_DEPTH: potential_path = os.path.join(current_dir, ".fonduer-config.yaml") if os.path.exists(potential_path): with open(potential_path, "r") as f: config = _merge(config, yaml.safe_load(f)) logger.debug(f"Loading Fonduer config from {potential_path}.") break new_dir = os.path.split(current_dir)[0] if current_dir == new_dir: logger.debug("Unable to find config file. Using defaults.") break current_dir = new_dir tries += 1 return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_id_or_insert(self, session): """Load the id of the temporary context if it exists or return insert args. As a side effect, this also inserts the Context object for the stableid. :return: The record of the temporary context to insert. :rtype: dict """
if self.id is None: stable_id = self.get_stable_id() # Check if exists id = session.execute( select([Context.id]).where(Context.stable_id == stable_id) ).first() # If not, insert if id is None: self.id = session.execute( Context.__table__.insert(), {"type": self._get_table().__tablename__, "stable_id": stable_id}, ).inserted_primary_key[0] insert_args = self._get_insert_args() insert_args["id"] = self.id return insert_args else: self.id = id[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_model(self): """ Build model. """
if "input_dim" not in self.settings: raise ValueError("Model parameter input_dim cannot be None.") self.linear = nn.Linear( self.settings["input_dim"], self.cardinality, self.settings["bias"] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply( self, doc_loader, pdf_path=None, clear=True, parallelism=None, progress_bar=True ): """Run the Parser. :param doc_loader: An iteratable of ``Documents`` to parse. Typically, one of Fonduer's document preprocessors. :param pdf_path: The path to the PDF documents, if any. This path will override the one used in initialization, if provided. :param clear: Whether or not to clear the labels table before applying these LFs. :type clear: bool :param parallelism: How many threads to use for extraction. This will override the parallelism value used to initialize the Labeler if it is provided. :type parallelism: int :param progress_bar: Whether or not to display a progress bar. The progress bar is measured per document. :type progress_bar: bool """
super(Parser, self).apply( doc_loader, pdf_path=pdf_path, clear=clear, parallelism=parallelism, progress_bar=progress_bar, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_documents(self): """Return the most recently parsed list of ``Documents``. :rtype: A list of the most recently parsed ``Documents`` ordered by name. """
return ( self.session.query(Document) .filter(Document.name.in_(self.last_docs)) .order_by(Document.name) .all() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_documents(self): """Return all the parsed ``Documents`` in the database. :rtype: A list of all ``Documents`` in the database ordered by name. """
return self.session.query(Document).order_by(Document.name).all()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _valid_pdf(self, path, filename): """Verify that the file exists and has a PDF extension."""
# If path is file, but not PDF. if os.path.isfile(path) and path.lower().endswith(".pdf"): return True else: full_path = os.path.join(path, filename) if os.path.isfile(full_path) and full_path.lower().endswith(".pdf"): return True elif os.path.isfile(os.path.join(path, filename + ".pdf")): return True elif os.path.isfile(os.path.join(path, filename + ".PDF")): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_figure(self, node, state): """Parse the figure node. :param node: The lxml img node to parse :param state: The global state necessary to place the node in context of the document as a whole. """
if node.tag not in ["img", "figure"]: return state # Process the Figure stable_id = ( f"{state['document'].name}" f"::" f"{'figure'}" f":" f"{state['figure']['idx']}" ) # Set name for Figure name = node.attrib["name"] if "name" in node.attrib else None # img within a Figure get's processed in the parent Figure if node.tag == "img" and isinstance(state["parent"][node], Figure): return state # NOTE: We currently do NOT support nested figures. parts = {} parent = state["parent"][node] if isinstance(parent, Section): parts["section"] = parent elif isinstance(parent, Cell): parts["section"] = parent.table.section parts["cell"] = parent else: logger.warning(f"Figure is nested within {state['parent'][node]}") return state parts["document"] = state["document"] parts["stable_id"] = stable_id parts["name"] = name parts["position"] = state["figure"]["idx"] # If processing a raw img if node.tag == "img": # Create the Figure entry in the DB parts["url"] = node.get("src") state["context"][node] = Figure(**parts) elif node.tag == "figure": # Pull the image from a child img node, if one exists imgs = [child for child in node if child.tag == "img"] if len(imgs) > 1: logger.warning("Figure contains multiple images.") # Right now we don't support multiple URLs in the Figure context # As a workaround, just ignore the outer Figure and allow processing # of the individual images. We ignore the accompanying figcaption # by marking it as visited. captions = [child for child in node if child.tag == "figcaption"] state["visited"].update(captions) return state img = imgs[0] state["visited"].add(img) # Create the Figure entry in the DB parts["url"] = img.get("src") state["context"][node] = Figure(**parts) state["figure"]["idx"] += 1 return state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_paragraph(self, node, state): """Parse a Paragraph of the node. :param node: The lxml node to parse :param state: The global state necessary to place the node in context of the document as a whole. """
# Both Paragraphs will share the same parent parent = ( state["context"][node] if node in state["context"] else state["parent"][node] ) # Set name for Paragraph name = node.attrib["name"] if "name" in node.attrib else None for field in ["text", "tail"]: text = getattr(node, field) text = text.strip() if text and self.strip else text # Skip if "" or None if not text: continue # Run RegEx replacements for (rgx, replace) in self.replacements: text = rgx.sub(replace, text) # Process the Paragraph stable_id = ( f"{state['document'].name}" f"::" f"{'paragraph'}" f":" f"{state['paragraph']['idx']}" ) parts = {} parts["stable_id"] = stable_id parts["name"] = name parts["document"] = state["document"] parts["position"] = state["paragraph"]["idx"] if isinstance(parent, Caption): if parent.table: parts["section"] = parent.table.section elif parent.figure: parts["section"] = parent.figure.section parts["caption"] = parent elif isinstance(parent, Cell): parts["section"] = parent.table.section parts["cell"] = parent elif isinstance(parent, Section): parts["section"] = parent elif isinstance(parent, Figure): # occurs with text in the tail of an img parts["section"] = parent.section elif isinstance(parent, Table): # occurs with text in the tail of a table parts["section"] = parent.section else: raise NotImplementedError( f"Para '{text}' parent must be Section, Caption, or Cell, " f"not {parent}" ) # Create the entry in the DB paragraph = Paragraph(**parts) state["paragraph"]["idx"] += 1 state["paragraph"]["text"] = text state["paragraph"]["field"] = field yield from self._parse_sentence(paragraph, node, state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_section(self, node, state): """Parse a Section of the node. Note that this implementation currently creates a Section at the beginning of the document and creates Section based on tag of node. :param node: The lxml node to parse :param state: The global state necessary to place the node in context of the document as a whole. """
if node.tag not in ["html", "section"]: return state # Add a Section stable_id = ( f"{state['document'].name}" f"::" f"{'section'}" f":" f"{state['section']['idx']}" ) # Set name for Section name = node.attrib["name"] if "name" in node.attrib else None state["context"][node] = Section( document=state["document"], name=name, stable_id=stable_id, position=state["section"]["idx"], ) state["section"]["idx"] += 1 return state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_caption(self, node, state): """Parse a Caption of the node. :param node: The lxml node to parse :param state: The global state necessary to place the node in context of the document as a whole. """
if node.tag not in ["caption", "figcaption"]: # captions used in Tables return state # Add a Caption parent = state["parent"][node] stable_id = ( f"{state['document'].name}" f"::" f"{'caption'}" f":" f"{state['caption']['idx']}" ) # Set name for Section name = node.attrib["name"] if "name" in node.attrib else None if isinstance(parent, Table): state["context"][node] = Caption( document=state["document"], table=parent, figure=None, stable_id=stable_id, name=name, position=state["caption"]["idx"], ) elif isinstance(parent, Figure): state["context"][node] = Caption( document=state["document"], table=None, figure=parent, stable_id=stable_id, name=name, position=state["caption"]["idx"], ) else: raise NotImplementedError("Caption must be a child of Table or Figure.") state["caption"]["idx"] += 1 return state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_node(self, node, state): """Entry point for parsing all node types. :param node: The lxml HTML node to parse :param state: The global state necessary to place the node in context of the document as a whole. :rtype: a *generator* of Sentences """
# Processing on entry of node state = self._parse_section(node, state) state = self._parse_figure(node, state) if self.tabular: state = self._parse_table(node, state) state = self._parse_caption(node, state) yield from self._parse_paragraph(node, state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, document, text): """Depth-first search over the provided tree. Implemented as an iterative procedure. The structure of the state needed to parse each node is also defined in this function. :param document: the Document context :param text: the structured text of the document (e.g. HTML) :rtype: a *generator* of Sentences. """
stack = [] root = lxml.html.fromstring(text) # flattens children of node that are in the 'flatten' list if self.flatten: lxml.etree.strip_tags(root, self.flatten) # Assign the text, which was stripped of the 'flatten'-tags, to the document document.text = lxml.etree.tostring(root, encoding="unicode") # This dictionary contain the global state necessary to parse a # document and each context element. This reflects the relationships # defined in parser/models. This contains the state necessary to create # the respective Contexts within the document. state = { "visited": set(), "parent": {}, # map of parent[child] = node used to discover child "context": {}, # track the Context of each node (context['td'] = Cell) "root": root, "document": document, "section": {"idx": 0}, "paragraph": {"idx": 0}, "figure": {"idx": 0}, "caption": {"idx": 0}, "table": {"idx": 0}, "sentence": {"idx": 0, "abs_offset": 0}, } # NOTE: Currently the helper functions directly manipulate the state # rather than returning a modified copy. # Iterative Depth-First Search stack.append(root) state["parent"][root] = document state["context"][root] = document tokenized_sentences = [] while stack: node = stack.pop() if node not in state["visited"]: state["visited"].add(node) # mark as visited # Process if self.lingual: tokenized_sentences += [y for y in self._parse_node(node, state)] else: yield from self._parse_node(node, state) # NOTE: This reversed() order is to ensure that the iterative # DFS matches the order that would be produced by a recursive # DFS implementation. for child in reversed(node): # Skip nodes that are comments or blacklisted if child.tag is lxml.etree.Comment or ( self.blacklist and child.tag in self.blacklist ): continue stack.append(child) # store the parent of the node, which is either the parent # Context, or if the parent did not create a Context, then # use the node's parent Context. state["parent"][child] = ( state["context"][node] if node in state["context"] else state["parent"][node] ) if self.lingual: yield from self.enrich_tokenized_sentences_with_nlp(tokenized_sentences)