_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q33600 | VisiData.rightStatus | train | 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(sh... | python | {
"resource": ""
} |
q33601 | VisiData.run | train | 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 = ''
... | python | {
"resource": ""
} |
q33602 | VisiData.push | train | 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)
... | python | {
"resource": ""
} |
q33603 | BaseSheet.exec_command | train | 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... | python | {
"resource": ""
} |
q33604 | Sheet.column | train | 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 | {
"resource": ""
} |
q33605 | Sheet.deleteSelected | train | 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 | {
"resource": ""
} |
q33606 | Sheet.visibleRows | train | def visibleRows(self): # onscreen rows
'List of rows onscreen. '
return self.rows[self.topRowIndex:self.topRowIndex+self.nVisibleRows] | python | {
"resource": ""
} |
q33607 | Sheet.visibleCols | train | 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 | {
"resource": ""
} |
q33608 | Sheet.nonKeyVisibleCols | train | 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 | {
"resource": ""
} |
q33609 | Sheet.statusLine | train | 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 | {
"resource": ""
} |
q33610 | Sheet.toggle | train | 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 | {
"resource": ""
} |
q33611 | Sheet.select | train | 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, 'selectin... | python | {
"resource": ""
} |
q33612 | Sheet.unselect | train | 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 statu... | python | {
"resource": ""
} |
q33613 | Sheet.selectByIdx | train | def selectByIdx(self, rowIdxs):
'Select given row indexes, without progress bar.'
self.select((self.rows[i] for i in rowIdxs), progress=False) | python | {
"resource": ""
} |
q33614 | Sheet.unselectByIdx | train | def unselectByIdx(self, rowIdxs):
'Unselect given row indexes, without progress bar.'
self.unselect((self.rows[i] for i in rowIdxs), progress=False) | python | {
"resource": ""
} |
q33615 | Sheet.gatherBy | train | 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 | {
"resource": ""
} |
q33616 | Sheet.pageLeft | train | 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
... | python | {
"resource": ""
} |
q33617 | Sheet.addColumn | train | 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 | {
"resource": ""
} |
q33618 | Sheet.rowkey | train | 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 | {
"resource": ""
} |
q33619 | Sheet.checkCursor | train | 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
... | python | {
"resource": ""
} |
q33620 | Sheet.calcColLayout | train | 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
vcolid... | python | {
"resource": ""
} |
q33621 | Sheet.drawColHeader | train | 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.colo... | python | {
"resource": ""
} |
q33622 | Sheet.editCell | train | 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[vc... | python | {
"resource": ""
} |
q33623 | Column.recalc | train | 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 | {
"resource": ""
} |
q33624 | Column.format | train | 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}' % le... | python | {
"resource": ""
} |
q33625 | Column.getTypedValue | train | 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 | {
"resource": ""
} |
q33626 | Column.getTypedValueOrException | train | 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 | {
"resource": ""
} |
q33627 | Column.getTypedValueNoExceptions | train | 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 | {
"resource": ""
} |
q33628 | Column.getCell | train | 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
... | python | {
"resource": ""
} |
q33629 | Column.setValueSafe | train | def setValueSafe(self, row, value):
'setValue and ignore exceptions'
try:
return self.setValue(row, value)
except Exception as e:
exceptionCaught(e) | python | {
"resource": ""
} |
q33630 | Column.setValues | train | 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 | {
"resource": ""
} |
q33631 | Column.getMaxWidth | train | 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 | {
"resource": ""
} |
q33632 | Column.toggleWidth | train | 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 | {
"resource": ""
} |
q33633 | ColorMaker.resolve_colors | train | 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)
ret... | python | {
"resource": ""
} |
q33634 | addAggregators | train | 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, 'aggr... | python | {
"resource": ""
} |
q33635 | CommandLog.removeSheet | train | 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 | {
"resource": ""
} |
q33636 | CommandLog.delay | train | 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 | {
"resource": ""
} |
q33637 | CommandLog.replayOne | train | 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
... | python | {
"resource": ""
} |
q33638 | CommandLog.replay_sync | train | 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:
... | python | {
"resource": ""
} |
q33639 | CommandLog.setLastArgs | train | 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 | {
"resource": ""
} |
q33640 | encode_chunk | train | 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",
... | python | {
"resource": ""
} |
q33641 | _bqschema_to_nullsafe_dtypes | train | 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-castin... | python | {
"resource": ""
} |
q33642 | _cast_empty_df_dtypes | train | 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. Thi... | python | {
"resource": ""
} |
q33643 | _localize_df | train | 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:
... | python | {
"resource": ""
} |
q33644 | read_gbq | train | 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... | python | {
"resource": ""
} |
q33645 | GbqConnector.schema | train | 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
... | python | {
"resource": ""
} |
q33646 | GbqConnector._clean_schema_fields | train | 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"]... | python | {
"resource": ""
} |
q33647 | GbqConnector.verify_schema | train | 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.
P... | python | {
"resource": ""
} |
q33648 | GbqConnector.schema_is_subset | train | 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. Orde... | python | {
"resource": ""
} |
q33649 | _Table.exists | train | 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_co... | python | {
"resource": ""
} |
q33650 | _Table.create | train | 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
dataf... | python | {
"resource": ""
} |
q33651 | _Table.delete | train | 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("Tab... | python | {
"resource": ""
} |
q33652 | _Dataset.exists | train | 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 ... | python | {
"resource": ""
} |
q33653 | _Dataset.create | train | 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(
... | python | {
"resource": ""
} |
q33654 | update_schema | train | 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_ne... | python | {
"resource": ""
} |
q33655 | AutoUsernameMixin.clean | train | 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 | {
"resource": ""
} |
q33656 | AutoGroupnameMixin.clean | train | 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_BL... | python | {
"resource": ""
} |
q33657 | AbstractRadiusGroup.get_default_queryset | train | 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 | {
"resource": ""
} |
q33658 | AuthorizeView.get_user | train | 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 | {
"resource": ""
} |
q33659 | AuthorizeView.authenticate_user | train | 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 \
... | python | {
"resource": ""
} |
q33660 | AuthorizeView.check_user_token | train | 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
... | python | {
"resource": ""
} |
q33661 | PostAuthView.post | train | 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 | {
"resource": ""
} |
q33662 | RedirectCaptivePageView.authorize | train | 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 | {
"resource": ""
} |
q33663 | RedirectCaptivePageView.get_redirect_url | train | 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}... | python | {
"resource": ""
} |
q33664 | get_install_requires | train | 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.st... | python | {
"resource": ""
} |
q33665 | AbstractUserAdmin.get_inline_instances | train | 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.ad... | python | {
"resource": ""
} |
q33666 | construct_stable_id | train | 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(pare... | python | {
"resource": ""
} |
q33667 | vizlib_unary_features | train | 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}]",... | python | {
"resource": ""
} |
q33668 | vizlib_binary_features | train | 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)):
... | python | {
"resource": ""
} |
q33669 | MentionNgrams.apply | train | 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):
... | python | {
"resource": ""
} |
q33670 | MentionFigures.apply | train | 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):
... | python | {
"resource": ""
} |
q33671 | MentionSentences.apply | train | 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, Documen... | python | {
"resource": ""
} |
q33672 | MentionParagraphs.apply | train | 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, Docum... | python | {
"resource": ""
} |
q33673 | MentionCaptions.apply | train | 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)... | python | {
"resource": ""
} |
q33674 | MentionCells.apply | train | 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):
... | python | {
"resource": ""
} |
q33675 | MentionTables.apply | train | 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):
... | python | {
"resource": ""
} |
q33676 | MentionSections.apply | train | 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)... | python | {
"resource": ""
} |
q33677 | MentionExtractor.apply | train | 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 e... | python | {
"resource": ""
} |
q33678 | MentionExtractor.clear | train | 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... | python | {
"resource": ""
} |
q33679 | MentionExtractor.clear_all | train | 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(synchro... | python | {
"resource": ""
} |
q33680 | MentionExtractor.get_mentions | train | 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... | python | {
"resource": ""
} |
q33681 | MentionExtractorUDF.apply | train | 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 =... | python | {
"resource": ""
} |
q33682 | SimpleTokenizer.parse | train | 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
wor... | python | {
"resource": ""
} |
q33683 | strlib_unary_features | train | 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... | python | {
"resource": ""
} |
q33684 | build_node | train | 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... | python | {
"resource": ""
} |
q33685 | _to_span | train | 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 ... | python | {
"resource": ""
} |
q33686 | _to_spans | train | 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... | python | {
"resource": ""
} |
q33687 | get_matches | train | 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 ... | python | {
"resource": ""
} |
q33688 | Featurizer.update | train | 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
... | python | {
"resource": ""
} |
q33689 | Featurizer.apply | train | 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.... | python | {
"resource": ""
} |
q33690 | Featurizer.drop_keys | train | 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 ... | python | {
"resource": ""
} |
q33691 | Featurizer.clear | train | 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 Feature... | python | {
"resource": ""
} |
q33692 | Featurizer.clear_all | train | 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") | python | {
"resource": ""
} |
q33693 | _merge | train | 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 | python | {
"resource": ""
} |
q33694 | get_config | train | 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.exis... | python | {
"resource": ""
} |
q33695 | TemporaryContext._load_id_or_insert | train | 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.i... | python | {
"resource": ""
} |
q33696 | LogisticRegression._build_model | train | 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"]
) | python | {
"resource": ""
} |
q33697 | Parser.apply | train | 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 document... | python | {
"resource": ""
} |
q33698 | Parser.get_last_documents | train | 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))
.ord... | python | {
"resource": ""
} |
q33699 | Parser.get_documents | train | 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() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.