repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ajenhl/tacl | tacl/report.py | Report._get_template | def _get_template(self):
"""Returns a template for this report.
:rtype: `jinja2.Template`
"""
loader = PackageLoader(self._package_name, 'assets/templates')
env = Environment(extensions=['jinja2.ext.with_'], loader=loader)
return env.get_template('{}.html'.format(self._report_name)) | python | def _get_template(self):
"""Returns a template for this report.
:rtype: `jinja2.Template`
"""
loader = PackageLoader(self._package_name, 'assets/templates')
env = Environment(extensions=['jinja2.ext.with_'], loader=loader)
return env.get_template('{}.html'.format(self._report_name)) | [
"def",
"_get_template",
"(",
"self",
")",
":",
"loader",
"=",
"PackageLoader",
"(",
"self",
".",
"_package_name",
",",
"'assets/templates'",
")",
"env",
"=",
"Environment",
"(",
"extensions",
"=",
"[",
"'jinja2.ext.with_'",
"]",
",",
"loader",
"=",
"loader",
... | Returns a template for this report.
:rtype: `jinja2.Template` | [
"Returns",
"a",
"template",
"for",
"this",
"report",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L46-L54 | train | 48,300 |
ajenhl/tacl | tacl/report.py | Report._write | def _write(self, context, report_dir, report_name, assets_dir=None,
template=None):
"""Writes the data in `context` in the report's template to
`report_name` in `report_dir`.
If `assets_dir` is supplied, copies all assets for this report
to the specified directory.
If `template` is supplied, uses that template instead of
automatically finding it. This is useful if a single report
generates multiple files using the same template.
:param context: context data to render within the template
:type context: `dict`
:param report_dir: directory to write the report to
:type report_dir: `str`
:param report_name: name of file to write the report to
:type report_name: `str`
:param assets_dir: optional directory to output report assets to
:type assets_dir: `str`
:param template: template to render and output
:type template: `jinja2.Template`
"""
if template is None:
template = self._get_template()
report = template.render(context)
output_file = os.path.join(report_dir, report_name)
with open(output_file, 'w', encoding='utf-8') as fh:
fh.write(report)
if assets_dir:
self._copy_static_assets(assets_dir) | python | def _write(self, context, report_dir, report_name, assets_dir=None,
template=None):
"""Writes the data in `context` in the report's template to
`report_name` in `report_dir`.
If `assets_dir` is supplied, copies all assets for this report
to the specified directory.
If `template` is supplied, uses that template instead of
automatically finding it. This is useful if a single report
generates multiple files using the same template.
:param context: context data to render within the template
:type context: `dict`
:param report_dir: directory to write the report to
:type report_dir: `str`
:param report_name: name of file to write the report to
:type report_name: `str`
:param assets_dir: optional directory to output report assets to
:type assets_dir: `str`
:param template: template to render and output
:type template: `jinja2.Template`
"""
if template is None:
template = self._get_template()
report = template.render(context)
output_file = os.path.join(report_dir, report_name)
with open(output_file, 'w', encoding='utf-8') as fh:
fh.write(report)
if assets_dir:
self._copy_static_assets(assets_dir) | [
"def",
"_write",
"(",
"self",
",",
"context",
",",
"report_dir",
",",
"report_name",
",",
"assets_dir",
"=",
"None",
",",
"template",
"=",
"None",
")",
":",
"if",
"template",
"is",
"None",
":",
"template",
"=",
"self",
".",
"_get_template",
"(",
")",
"... | Writes the data in `context` in the report's template to
`report_name` in `report_dir`.
If `assets_dir` is supplied, copies all assets for this report
to the specified directory.
If `template` is supplied, uses that template instead of
automatically finding it. This is useful if a single report
generates multiple files using the same template.
:param context: context data to render within the template
:type context: `dict`
:param report_dir: directory to write the report to
:type report_dir: `str`
:param report_name: name of file to write the report to
:type report_name: `str`
:param assets_dir: optional directory to output report assets to
:type assets_dir: `str`
:param template: template to render and output
:type template: `jinja2.Template` | [
"Writes",
"the",
"data",
"in",
"context",
"in",
"the",
"report",
"s",
"template",
"to",
"report_name",
"in",
"report_dir",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L56-L87 | train | 48,301 |
SuperCowPowers/chains | chains/sinks/packet_summary.py | PacketSummary.pull | def pull(self):
"""Print out summary information about each packet from the input_stream"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Print out the timestamp in UTC
print('%s -' % item['timestamp'], end='')
# Transport info
if item['transport']:
print(item['transport']['type'], end='')
# Print out the Packet info
packet_type = item['packet']['type']
print(packet_type, end='')
packet = item['packet']
if packet_type in ['IP', 'IP6']:
# Is there domain info?
if 'src_domain' in packet:
print('%s(%s) --> %s(%s)' % (net_utils.inet_to_str(packet['src']), packet['src_domain'],
net_utils.inet_to_str(packet['dst']), packet['dst_domain']), end='')
else:
print('%s --> %s' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst'])), end='')
else:
print(str(packet))
# Only include application if we have it
if item['application']:
print('Application: %s' % item['application']['type'], end='')
print(str(item['application']), end='')
# Just for newline
print() | python | def pull(self):
"""Print out summary information about each packet from the input_stream"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Print out the timestamp in UTC
print('%s -' % item['timestamp'], end='')
# Transport info
if item['transport']:
print(item['transport']['type'], end='')
# Print out the Packet info
packet_type = item['packet']['type']
print(packet_type, end='')
packet = item['packet']
if packet_type in ['IP', 'IP6']:
# Is there domain info?
if 'src_domain' in packet:
print('%s(%s) --> %s(%s)' % (net_utils.inet_to_str(packet['src']), packet['src_domain'],
net_utils.inet_to_str(packet['dst']), packet['dst_domain']), end='')
else:
print('%s --> %s' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst'])), end='')
else:
print(str(packet))
# Only include application if we have it
if item['application']:
print('Application: %s' % item['application']['type'], end='')
print(str(item['application']), end='')
# Just for newline
print() | [
"def",
"pull",
"(",
"self",
")",
":",
"# For each packet in the pcap process the contents",
"for",
"item",
"in",
"self",
".",
"input_stream",
":",
"# Print out the timestamp in UTC",
"print",
"(",
"'%s -'",
"%",
"item",
"[",
"'timestamp'",
"]",
",",
"end",
"=",
"'... | Print out summary information about each packet from the input_stream | [
"Print",
"out",
"summary",
"information",
"about",
"each",
"packet",
"from",
"the",
"input_stream"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/sinks/packet_summary.py#L17-L50 | train | 48,302 |
SuperCowPowers/chains | chains/sinks/packet_printer.py | PacketPrinter.pull | def pull(self):
"""Print out information about each packet from the input_stream"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Print out the timestamp in UTC
print('Timestamp: %s' % item['timestamp'])
# Unpack the Ethernet frame (mac src/dst, ethertype)
print('Ethernet Frame: %s --> %s (type: %d)' % \
(net_utils.mac_to_str(item['eth']['src']), net_utils.mac_to_str(item['eth']['dst']), item['eth']['type']))
# Print out the Packet info
packet_type = item['packet']['type']
print('Packet: %s ' % packet_type, end='')
packet = item['packet']
if packet_type in ['IP', 'IP6']:
print('%s --> %s (len:%d ttl:%d)' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst']),
packet['len'], packet['ttl']), end='')
if packet_type == 'IP':
print('-- Frag(df:%d mf:%d offset:%d)' % (packet['df'], packet['mf'], packet['offset']))
else:
print()
else:
print(str(packet))
# Print out transport and application layers
if item['transport']:
transport_info = item['transport']
print('Transport: %s ' % transport_info['type'], end='')
for key, value in compat.iteritems(transport_info):
if key != 'data':
print(key+':'+repr(value), end=' ')
# Give summary info about data
data = transport_info['data']
print('\nData: %d bytes' % len(data), end='')
if data:
print('(%s...)' % repr(data)[:30])
else:
print()
# Application data
if item['application']:
print('Application: %s' % item['application']['type'], end='')
print(str(item['application']))
# Is there domain info?
if 'src_domain' in packet:
print('Domains: %s --> %s' % (packet['src_domain'], packet['dst_domain']))
# Tags
if 'tags' in item:
print(list(item['tags']))
print() | python | def pull(self):
"""Print out information about each packet from the input_stream"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Print out the timestamp in UTC
print('Timestamp: %s' % item['timestamp'])
# Unpack the Ethernet frame (mac src/dst, ethertype)
print('Ethernet Frame: %s --> %s (type: %d)' % \
(net_utils.mac_to_str(item['eth']['src']), net_utils.mac_to_str(item['eth']['dst']), item['eth']['type']))
# Print out the Packet info
packet_type = item['packet']['type']
print('Packet: %s ' % packet_type, end='')
packet = item['packet']
if packet_type in ['IP', 'IP6']:
print('%s --> %s (len:%d ttl:%d)' % (net_utils.inet_to_str(packet['src']), net_utils.inet_to_str(packet['dst']),
packet['len'], packet['ttl']), end='')
if packet_type == 'IP':
print('-- Frag(df:%d mf:%d offset:%d)' % (packet['df'], packet['mf'], packet['offset']))
else:
print()
else:
print(str(packet))
# Print out transport and application layers
if item['transport']:
transport_info = item['transport']
print('Transport: %s ' % transport_info['type'], end='')
for key, value in compat.iteritems(transport_info):
if key != 'data':
print(key+':'+repr(value), end=' ')
# Give summary info about data
data = transport_info['data']
print('\nData: %d bytes' % len(data), end='')
if data:
print('(%s...)' % repr(data)[:30])
else:
print()
# Application data
if item['application']:
print('Application: %s' % item['application']['type'], end='')
print(str(item['application']))
# Is there domain info?
if 'src_domain' in packet:
print('Domains: %s --> %s' % (packet['src_domain'], packet['dst_domain']))
# Tags
if 'tags' in item:
print(list(item['tags']))
print() | [
"def",
"pull",
"(",
"self",
")",
":",
"# For each packet in the pcap process the contents",
"for",
"item",
"in",
"self",
".",
"input_stream",
":",
"# Print out the timestamp in UTC",
"print",
"(",
"'Timestamp: %s'",
"%",
"item",
"[",
"'timestamp'",
"]",
")",
"# Unpack... | Print out information about each packet from the input_stream | [
"Print",
"out",
"information",
"about",
"each",
"packet",
"from",
"the",
"input_stream"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/sinks/packet_printer.py#L21-L76 | train | 48,303 |
peeringdb/django-peeringdb | django_peeringdb/client_adaptor/load.py | load_backend | def load_backend(**orm_config):
"""
Load the client adaptor module of django_peeringdb
Assumes config is valid.
"""
settings = {}
settings['SECRET_KEY'] = orm_config.get('secret_key', '')
db_config = orm_config['database']
if db_config:
settings['DATABASES'] = {
'default': database_settings(db_config)
}
from django_peeringdb.client_adaptor.setup import configure
# Override defaults
configure(**settings)
# Must import implementation module after configure
from django_peeringdb.client_adaptor import backend
migrate = orm_config.get("migrate")
if migrate and not backend.Backend().is_database_migrated():
backend.Backend().migrate_database()
return backend | python | def load_backend(**orm_config):
"""
Load the client adaptor module of django_peeringdb
Assumes config is valid.
"""
settings = {}
settings['SECRET_KEY'] = orm_config.get('secret_key', '')
db_config = orm_config['database']
if db_config:
settings['DATABASES'] = {
'default': database_settings(db_config)
}
from django_peeringdb.client_adaptor.setup import configure
# Override defaults
configure(**settings)
# Must import implementation module after configure
from django_peeringdb.client_adaptor import backend
migrate = orm_config.get("migrate")
if migrate and not backend.Backend().is_database_migrated():
backend.Backend().migrate_database()
return backend | [
"def",
"load_backend",
"(",
"*",
"*",
"orm_config",
")",
":",
"settings",
"=",
"{",
"}",
"settings",
"[",
"'SECRET_KEY'",
"]",
"=",
"orm_config",
".",
"get",
"(",
"'secret_key'",
",",
"''",
")",
"db_config",
"=",
"orm_config",
"[",
"'database'",
"]",
"if... | Load the client adaptor module of django_peeringdb
Assumes config is valid. | [
"Load",
"the",
"client",
"adaptor",
"module",
"of",
"django_peeringdb",
"Assumes",
"config",
"is",
"valid",
"."
] | 2a32aae8a7e1c11ab6e5a873bb19619c641098c8 | https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/load.py#L22-L46 | train | 48,304 |
ajenhl/tacl | tacl/results.py | Results.add_label_count | def add_label_count(self):
"""Adds to each result row a count of the number of occurrences of
that n-gram across all works within the label.
This count uses the highest witness count for each work.
"""
self._logger.info('Adding label count')
def add_label_count(df):
# For each n-gram and label pair, we need the maximum count
# among all witnesses to each work, and then the sum of those
# across all works.
work_maxima = df.groupby(constants.WORK_FIELDNAME,
sort=False).max()
df.loc[:, constants.LABEL_COUNT_FIELDNAME] = work_maxima[
constants.COUNT_FIELDNAME].sum()
return df
if self._matches.empty:
self._matches[constants.LABEL_COUNT_FIELDNAME] = 0
else:
self._matches.loc[:, constants.LABEL_COUNT_FIELDNAME] = 0
self._matches = self._matches.groupby(
[constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME],
sort=False).apply(add_label_count)
self._logger.info('Finished adding label count') | python | def add_label_count(self):
"""Adds to each result row a count of the number of occurrences of
that n-gram across all works within the label.
This count uses the highest witness count for each work.
"""
self._logger.info('Adding label count')
def add_label_count(df):
# For each n-gram and label pair, we need the maximum count
# among all witnesses to each work, and then the sum of those
# across all works.
work_maxima = df.groupby(constants.WORK_FIELDNAME,
sort=False).max()
df.loc[:, constants.LABEL_COUNT_FIELDNAME] = work_maxima[
constants.COUNT_FIELDNAME].sum()
return df
if self._matches.empty:
self._matches[constants.LABEL_COUNT_FIELDNAME] = 0
else:
self._matches.loc[:, constants.LABEL_COUNT_FIELDNAME] = 0
self._matches = self._matches.groupby(
[constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME],
sort=False).apply(add_label_count)
self._logger.info('Finished adding label count') | [
"def",
"add_label_count",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding label count'",
")",
"def",
"add_label_count",
"(",
"df",
")",
":",
"# For each n-gram and label pair, we need the maximum count",
"# among all witnesses to each work, and the... | Adds to each result row a count of the number of occurrences of
that n-gram across all works within the label.
This count uses the highest witness count for each work. | [
"Adds",
"to",
"each",
"result",
"row",
"a",
"count",
"of",
"the",
"number",
"of",
"occurrences",
"of",
"that",
"n",
"-",
"gram",
"across",
"all",
"works",
"within",
"the",
"label",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L58-L84 | train | 48,305 |
ajenhl/tacl | tacl/results.py | Results.add_label_work_count | def add_label_work_count(self):
"""Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a given work (possible with zero-fill followed by
filtering by maximum count).
"""
self._logger.info('Adding label work count')
def add_label_text_count(df):
work_maxima = df.groupby(constants.WORK_FIELDNAME,
sort=False).any()
df.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = work_maxima[
constants.COUNT_FIELDNAME].sum()
return df
if self._matches.empty:
self._matches[constants.LABEL_WORK_COUNT_FIELDNAME] = 0
else:
self._matches.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = 0
self._matches = self._matches.groupby(
[constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME],
sort=False).apply(add_label_text_count)
self._logger.info('Finished adding label work count') | python | def add_label_work_count(self):
"""Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a given work (possible with zero-fill followed by
filtering by maximum count).
"""
self._logger.info('Adding label work count')
def add_label_text_count(df):
work_maxima = df.groupby(constants.WORK_FIELDNAME,
sort=False).any()
df.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = work_maxima[
constants.COUNT_FIELDNAME].sum()
return df
if self._matches.empty:
self._matches[constants.LABEL_WORK_COUNT_FIELDNAME] = 0
else:
self._matches.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = 0
self._matches = self._matches.groupby(
[constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME],
sort=False).apply(add_label_text_count)
self._logger.info('Finished adding label work count') | [
"def",
"add_label_work_count",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding label work count'",
")",
"def",
"add_label_text_count",
"(",
"df",
")",
":",
"work_maxima",
"=",
"df",
".",
"groupby",
"(",
"constants",
".",
"WORK_FIELDNA... | Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a given work (possible with zero-fill followed by
filtering by maximum count). | [
"Adds",
"to",
"each",
"result",
"row",
"a",
"count",
"of",
"the",
"number",
"of",
"works",
"within",
"the",
"label",
"contain",
"that",
"n",
"-",
"gram",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L88-L116 | train | 48,306 |
ajenhl/tacl | tacl/results.py | Results._annotate_bifurcated_extend_data | def _annotate_bifurcated_extend_data(self, row, smaller, larger, tokenize,
join):
"""Returns `row` annotated with whether it should be deleted or not.
An n-gram is marked for deletion if:
* its label count is 1 and its constituent (n-1)-grams also
have a label count of 1; or
* there is a containing (n+1)-gram that has the same label
count.
:param row: row of witness n-grams to annotate
:type row: `pandas.Series`
:param smaller: rows of (n-1)-grams for this witness
:type smaller: `pandas.DataFrame`
:param larger: rows of (n+1)-grams for this witness
:type larger: `pandas.DataFrame`
:param tokenize: function to tokenize an n-gram
:param join: function to join tokens
:rtype: `pandas.Series`
"""
lcf = constants.LABEL_COUNT_FIELDNAME
nf = constants.NGRAM_FIELDNAME
ngram = row[constants.NGRAM_FIELDNAME]
label_count = row[constants.LABEL_COUNT_FIELDNAME]
if label_count == 1 and not smaller.empty:
# Keep a result with a label count of 1 if its
# constituents do not also have a count of 1.
ngram_tokens = tokenize(ngram)
sub_ngram1 = join(ngram_tokens[:-1])
sub_ngram2 = join(ngram_tokens[1:])
pattern = FilteredWitnessText.get_filter_ngrams_pattern(
[sub_ngram1, sub_ngram2])
if smaller[smaller[constants.NGRAM_FIELDNAME].str.match(pattern)][
constants.LABEL_COUNT_FIELDNAME].max() == 1:
row[DELETE_FIELDNAME] = True
elif not larger.empty and larger[larger[nf].str.contains(
ngram, regex=False)][lcf].max() == label_count:
# Remove a result if the label count of a containing
# n-gram is equal to its label count.
row[DELETE_FIELDNAME] = True
return row | python | def _annotate_bifurcated_extend_data(self, row, smaller, larger, tokenize,
join):
"""Returns `row` annotated with whether it should be deleted or not.
An n-gram is marked for deletion if:
* its label count is 1 and its constituent (n-1)-grams also
have a label count of 1; or
* there is a containing (n+1)-gram that has the same label
count.
:param row: row of witness n-grams to annotate
:type row: `pandas.Series`
:param smaller: rows of (n-1)-grams for this witness
:type smaller: `pandas.DataFrame`
:param larger: rows of (n+1)-grams for this witness
:type larger: `pandas.DataFrame`
:param tokenize: function to tokenize an n-gram
:param join: function to join tokens
:rtype: `pandas.Series`
"""
lcf = constants.LABEL_COUNT_FIELDNAME
nf = constants.NGRAM_FIELDNAME
ngram = row[constants.NGRAM_FIELDNAME]
label_count = row[constants.LABEL_COUNT_FIELDNAME]
if label_count == 1 and not smaller.empty:
# Keep a result with a label count of 1 if its
# constituents do not also have a count of 1.
ngram_tokens = tokenize(ngram)
sub_ngram1 = join(ngram_tokens[:-1])
sub_ngram2 = join(ngram_tokens[1:])
pattern = FilteredWitnessText.get_filter_ngrams_pattern(
[sub_ngram1, sub_ngram2])
if smaller[smaller[constants.NGRAM_FIELDNAME].str.match(pattern)][
constants.LABEL_COUNT_FIELDNAME].max() == 1:
row[DELETE_FIELDNAME] = True
elif not larger.empty and larger[larger[nf].str.contains(
ngram, regex=False)][lcf].max() == label_count:
# Remove a result if the label count of a containing
# n-gram is equal to its label count.
row[DELETE_FIELDNAME] = True
return row | [
"def",
"_annotate_bifurcated_extend_data",
"(",
"self",
",",
"row",
",",
"smaller",
",",
"larger",
",",
"tokenize",
",",
"join",
")",
":",
"lcf",
"=",
"constants",
".",
"LABEL_COUNT_FIELDNAME",
"nf",
"=",
"constants",
".",
"NGRAM_FIELDNAME",
"ngram",
"=",
"row... | Returns `row` annotated with whether it should be deleted or not.
An n-gram is marked for deletion if:
* its label count is 1 and its constituent (n-1)-grams also
have a label count of 1; or
* there is a containing (n+1)-gram that has the same label
count.
:param row: row of witness n-grams to annotate
:type row: `pandas.Series`
:param smaller: rows of (n-1)-grams for this witness
:type smaller: `pandas.DataFrame`
:param larger: rows of (n+1)-grams for this witness
:type larger: `pandas.DataFrame`
:param tokenize: function to tokenize an n-gram
:param join: function to join tokens
:rtype: `pandas.Series` | [
"Returns",
"row",
"annotated",
"with",
"whether",
"it",
"should",
"be",
"deleted",
"or",
"not",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L118-L161 | train | 48,307 |
ajenhl/tacl | tacl/results.py | Results.bifurcated_extend | def bifurcated_extend(self, corpus, max_size):
"""Replaces the results with those n-grams that contain any of the
original n-grams, and that represent points at which an n-gram
is a constituent of multiple larger n-grams with a lower label
count.
:param corpus: corpus of works to which results belong
:type corpus: `Corpus`
:param max_size: maximum size of n-gram results to include
:type max_size: `int`
"""
temp_fd, temp_path = tempfile.mkstemp(text=True)
try:
self._prepare_bifurcated_extend_data(corpus, max_size, temp_path,
temp_fd)
finally:
try:
os.remove(temp_path)
except OSError as e:
msg = ('Failed to remove temporary file containing unreduced '
'results: {}')
self._logger.error(msg.format(e))
self._bifurcated_extend() | python | def bifurcated_extend(self, corpus, max_size):
"""Replaces the results with those n-grams that contain any of the
original n-grams, and that represent points at which an n-gram
is a constituent of multiple larger n-grams with a lower label
count.
:param corpus: corpus of works to which results belong
:type corpus: `Corpus`
:param max_size: maximum size of n-gram results to include
:type max_size: `int`
"""
temp_fd, temp_path = tempfile.mkstemp(text=True)
try:
self._prepare_bifurcated_extend_data(corpus, max_size, temp_path,
temp_fd)
finally:
try:
os.remove(temp_path)
except OSError as e:
msg = ('Failed to remove temporary file containing unreduced '
'results: {}')
self._logger.error(msg.format(e))
self._bifurcated_extend() | [
"def",
"bifurcated_extend",
"(",
"self",
",",
"corpus",
",",
"max_size",
")",
":",
"temp_fd",
",",
"temp_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"text",
"=",
"True",
")",
"try",
":",
"self",
".",
"_prepare_bifurcated_extend_data",
"(",
"corpus",
",",
... | Replaces the results with those n-grams that contain any of the
original n-grams, and that represent points at which an n-gram
is a constituent of multiple larger n-grams with a lower label
count.
:param corpus: corpus of works to which results belong
:type corpus: `Corpus`
:param max_size: maximum size of n-gram results to include
:type max_size: `int` | [
"Replaces",
"the",
"results",
"with",
"those",
"n",
"-",
"grams",
"that",
"contain",
"any",
"of",
"the",
"original",
"n",
"-",
"grams",
"and",
"that",
"represent",
"points",
"at",
"which",
"an",
"n",
"-",
"gram",
"is",
"a",
"constituent",
"of",
"multiple... | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L166-L189 | train | 48,308 |
ajenhl/tacl | tacl/results.py | Results.collapse_witnesses | def collapse_witnesses(self):
"""Groups together witnesses for the same n-gram and work that has the
same count, and outputs a single row for each group.
This output replaces the siglum field with a sigla field that
provides a comma separated list of the witness sigla. Due to
this, it is not necessarily possible to run other Results
methods on results that have had their witnesses collapsed.
"""
# In order to allow for additional columns to be present in
# the input data (such as label count), copy the siglum
# information into a new final column, then put the sigla
# information into the siglum field and finally rename it.
#
# This means that in merge_sigla below, the column names are
# reversed from what would be expected.
if self._matches.empty:
self._matches.rename(columns={constants.SIGLUM_FIELDNAME:
constants.SIGLA_FIELDNAME},
inplace=True)
return
self._matches.loc[:, constants.SIGLA_FIELDNAME] = \
self._matches[constants.SIGLUM_FIELDNAME]
# This code makes the not unwarranted assumption that the same
# n-gram means the same size and that the same work means the
# same label.
grouped = self._matches.groupby(
[constants.WORK_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.COUNT_FIELDNAME], sort=False)
def merge_sigla(df):
# Take the first result row; only the siglum should differ
# between them, and there may only be one row.
merged = df[0:1]
sigla = list(df[constants.SIGLA_FIELDNAME])
sigla.sort()
merged[constants.SIGLUM_FIELDNAME] = ', '.join(sigla)
return merged
self._matches = grouped.apply(merge_sigla)
del self._matches[constants.SIGLA_FIELDNAME]
self._matches.rename(columns={constants.SIGLUM_FIELDNAME:
constants.SIGLA_FIELDNAME},
inplace=True) | python | def collapse_witnesses(self):
"""Groups together witnesses for the same n-gram and work that has the
same count, and outputs a single row for each group.
This output replaces the siglum field with a sigla field that
provides a comma separated list of the witness sigla. Due to
this, it is not necessarily possible to run other Results
methods on results that have had their witnesses collapsed.
"""
# In order to allow for additional columns to be present in
# the input data (such as label count), copy the siglum
# information into a new final column, then put the sigla
# information into the siglum field and finally rename it.
#
# This means that in merge_sigla below, the column names are
# reversed from what would be expected.
if self._matches.empty:
self._matches.rename(columns={constants.SIGLUM_FIELDNAME:
constants.SIGLA_FIELDNAME},
inplace=True)
return
self._matches.loc[:, constants.SIGLA_FIELDNAME] = \
self._matches[constants.SIGLUM_FIELDNAME]
# This code makes the not unwarranted assumption that the same
# n-gram means the same size and that the same work means the
# same label.
grouped = self._matches.groupby(
[constants.WORK_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.COUNT_FIELDNAME], sort=False)
def merge_sigla(df):
# Take the first result row; only the siglum should differ
# between them, and there may only be one row.
merged = df[0:1]
sigla = list(df[constants.SIGLA_FIELDNAME])
sigla.sort()
merged[constants.SIGLUM_FIELDNAME] = ', '.join(sigla)
return merged
self._matches = grouped.apply(merge_sigla)
del self._matches[constants.SIGLA_FIELDNAME]
self._matches.rename(columns={constants.SIGLUM_FIELDNAME:
constants.SIGLA_FIELDNAME},
inplace=True) | [
"def",
"collapse_witnesses",
"(",
"self",
")",
":",
"# In order to allow for additional columns to be present in",
"# the input data (such as label count), copy the siglum",
"# information into a new final column, then put the sigla",
"# information into the siglum field and finally rename it.",
... | Groups together witnesses for the same n-gram and work that has the
same count, and outputs a single row for each group.
This output replaces the siglum field with a sigla field that
provides a comma separated list of the witness sigla. Due to
this, it is not necessarily possible to run other Results
methods on results that have had their witnesses collapsed. | [
"Groups",
"together",
"witnesses",
"for",
"the",
"same",
"n",
"-",
"gram",
"and",
"work",
"that",
"has",
"the",
"same",
"count",
"and",
"outputs",
"a",
"single",
"row",
"for",
"each",
"group",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L222-L266 | train | 48,309 |
ajenhl/tacl | tacl/results.py | Results.csv | def csv(self, fh):
"""Writes the results data to `fh` in CSV format and returns `fh`.
:param fh: file to write data to
:type fh: file object
:rtype: file object
"""
self._matches.to_csv(fh, encoding='utf-8', float_format='%d',
index=False)
return fh | python | def csv(self, fh):
"""Writes the results data to `fh` in CSV format and returns `fh`.
:param fh: file to write data to
:type fh: file object
:rtype: file object
"""
self._matches.to_csv(fh, encoding='utf-8', float_format='%d',
index=False)
return fh | [
"def",
"csv",
"(",
"self",
",",
"fh",
")",
":",
"self",
".",
"_matches",
".",
"to_csv",
"(",
"fh",
",",
"encoding",
"=",
"'utf-8'",
",",
"float_format",
"=",
"'%d'",
",",
"index",
"=",
"False",
")",
"return",
"fh"
] | Writes the results data to `fh` in CSV format and returns `fh`.
:param fh: file to write data to
:type fh: file object
:rtype: file object | [
"Writes",
"the",
"results",
"data",
"to",
"fh",
"in",
"CSV",
"format",
"and",
"returns",
"fh",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L268-L278 | train | 48,310 |
ajenhl/tacl | tacl/results.py | Results.excise | def excise(self, ngram):
"""Removes all rows whose n-gram contains `ngram`.
This operation uses simple string containment matching. For
tokens that consist of multiple characters, this means that
`ngram` may be part of one or two tokens; eg, "he m" would
match on "she may".
:param ngram: n-gram to remove containing n-gram rows by
:type ngram: `str`
"""
self._logger.info('Excising results containing "{}"'.format(ngram))
if not ngram:
return
self._matches = self._matches[~self._matches[
constants.NGRAM_FIELDNAME].str.contains(ngram, regex=False)] | python | def excise(self, ngram):
"""Removes all rows whose n-gram contains `ngram`.
This operation uses simple string containment matching. For
tokens that consist of multiple characters, this means that
`ngram` may be part of one or two tokens; eg, "he m" would
match on "she may".
:param ngram: n-gram to remove containing n-gram rows by
:type ngram: `str`
"""
self._logger.info('Excising results containing "{}"'.format(ngram))
if not ngram:
return
self._matches = self._matches[~self._matches[
constants.NGRAM_FIELDNAME].str.contains(ngram, regex=False)] | [
"def",
"excise",
"(",
"self",
",",
"ngram",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Excising results containing \"{}\"'",
".",
"format",
"(",
"ngram",
")",
")",
"if",
"not",
"ngram",
":",
"return",
"self",
".",
"_matches",
"=",
"self",
".",... | Removes all rows whose n-gram contains `ngram`.
This operation uses simple string containment matching. For
tokens that consist of multiple characters, this means that
`ngram` may be part of one or two tokens; eg, "he m" would
match on "she may".
:param ngram: n-gram to remove containing n-gram rows by
:type ngram: `str` | [
"Removes",
"all",
"rows",
"whose",
"n",
"-",
"gram",
"contains",
"ngram",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L281-L297 | train | 48,311 |
ajenhl/tacl | tacl/results.py | Results.extend | def extend(self, corpus):
"""Adds rows for all longer forms of n-grams in the results that are
present in the witnesses.
This works with both diff and intersect results.
:param corpus: corpus of works to which results belong
:type corpus: `Corpus`
"""
self._logger.info('Extending results')
if self._matches.empty:
return
highest_n = self._matches[constants.SIZE_FIELDNAME].max()
if highest_n == 1:
self._logger.warning(
'Extending results that contain only 1-grams is unsupported; '
'the original results will be used')
return
# Determine if we are dealing with diff or intersect
# results. In the latter case, we need to perform a reciprocal
# remove as the final stage (since extended n-grams may exist
# in works from more than one label). This test will think
# that intersect results that have had all but one label
# removed are difference results, which will cause the results
# to be potentially incorrect.
is_intersect = self._is_intersect_results(self._matches)
# Supply the extender with only matches on the largest
# n-grams.
matches = self._matches[
self._matches[constants.SIZE_FIELDNAME] == highest_n]
extended_matches = pd.DataFrame(columns=constants.QUERY_FIELDNAMES)
cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME]
for index, (work, siglum, label) in \
matches[cols].drop_duplicates().iterrows():
extended_ngrams = self._generate_extended_ngrams(
matches, work, siglum, label, corpus, highest_n)
extended_matches = pd.concat(
[extended_matches, self._generate_extended_matches(
extended_ngrams, highest_n, work, siglum, label)],
sort=False)
extended_ngrams = None
if is_intersect:
extended_matches = self._reciprocal_remove(extended_matches)
self._matches = self._matches.append(
extended_matches, ignore_index=True).reindex(
columns=constants.QUERY_FIELDNAMES) | python | def extend(self, corpus):
"""Adds rows for all longer forms of n-grams in the results that are
present in the witnesses.
This works with both diff and intersect results.
:param corpus: corpus of works to which results belong
:type corpus: `Corpus`
"""
self._logger.info('Extending results')
if self._matches.empty:
return
highest_n = self._matches[constants.SIZE_FIELDNAME].max()
if highest_n == 1:
self._logger.warning(
'Extending results that contain only 1-grams is unsupported; '
'the original results will be used')
return
# Determine if we are dealing with diff or intersect
# results. In the latter case, we need to perform a reciprocal
# remove as the final stage (since extended n-grams may exist
# in works from more than one label). This test will think
# that intersect results that have had all but one label
# removed are difference results, which will cause the results
# to be potentially incorrect.
is_intersect = self._is_intersect_results(self._matches)
# Supply the extender with only matches on the largest
# n-grams.
matches = self._matches[
self._matches[constants.SIZE_FIELDNAME] == highest_n]
extended_matches = pd.DataFrame(columns=constants.QUERY_FIELDNAMES)
cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME]
for index, (work, siglum, label) in \
matches[cols].drop_duplicates().iterrows():
extended_ngrams = self._generate_extended_ngrams(
matches, work, siglum, label, corpus, highest_n)
extended_matches = pd.concat(
[extended_matches, self._generate_extended_matches(
extended_ngrams, highest_n, work, siglum, label)],
sort=False)
extended_ngrams = None
if is_intersect:
extended_matches = self._reciprocal_remove(extended_matches)
self._matches = self._matches.append(
extended_matches, ignore_index=True).reindex(
columns=constants.QUERY_FIELDNAMES) | [
"def",
"extend",
"(",
"self",
",",
"corpus",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Extending results'",
")",
"if",
"self",
".",
"_matches",
".",
"empty",
":",
"return",
"highest_n",
"=",
"self",
".",
"_matches",
"[",
"constants",
".",
"... | Adds rows for all longer forms of n-grams in the results that are
present in the witnesses.
This works with both diff and intersect results.
:param corpus: corpus of works to which results belong
:type corpus: `Corpus` | [
"Adds",
"rows",
"for",
"all",
"longer",
"forms",
"of",
"n",
"-",
"grams",
"in",
"the",
"results",
"that",
"are",
"present",
"in",
"the",
"witnesses",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L302-L349 | train | 48,312 |
ajenhl/tacl | tacl/results.py | Results._generate_extended_matches | def _generate_extended_matches(self, extended_ngrams, highest_n, work,
siglum, label):
"""Returns extended match data derived from `extended_ngrams`.
This extended match data are the counts for all intermediate
n-grams within each extended n-gram.
:param extended_ngrams: extended n-grams
:type extended_ngrams: `list` of `str`
:param highest_n: the highest degree of n-grams in the original results
:type highest_n: `int`
:param work: name of the work bearing `extended_ngrams`
:type work: `str`
:param siglum: siglum of the text bearing `extended_ngrams`
:type siglum: `str`
:param label: label associated with the text
:type label: `str`
:rtype: `pandas.DataFrame`
"""
# Add data for each n-gram within each extended n-gram. Since
# this treats each extended piece of text separately, the same
# n-gram may be generated more than once, so the complete set
# of new possible matches for this filename needs to combine
# the counts for such.
rows_list = []
for extended_ngram in extended_ngrams:
text = Text(extended_ngram, self._tokenizer)
for size, ngrams in text.get_ngrams(highest_n+1,
len(text.get_tokens())):
data = [{constants.WORK_FIELDNAME: work,
constants.SIGLUM_FIELDNAME: siglum,
constants.LABEL_FIELDNAME: label,
constants.SIZE_FIELDNAME: size,
constants.NGRAM_FIELDNAME: ngram,
constants.COUNT_FIELDNAME: count}
for ngram, count in ngrams.items()]
rows_list.extend(data)
self._logger.debug('Number of extended results: {}'.format(
len(rows_list)))
extended_matches = pd.DataFrame(rows_list)
rows_list = None
self._logger.debug('Finished generating intermediate extended matches')
# extended_matches may be an empty DataFrame, in which case
# manipulating it on the basis of non-existing columns is not
# going to go well.
groupby_fields = [constants.NGRAM_FIELDNAME, constants.WORK_FIELDNAME,
constants.SIGLUM_FIELDNAME, constants.SIZE_FIELDNAME,
constants.LABEL_FIELDNAME]
if constants.NGRAM_FIELDNAME in extended_matches:
extended_matches = extended_matches.groupby(
groupby_fields, sort=False).sum().reset_index()
return extended_matches | python | def _generate_extended_matches(self, extended_ngrams, highest_n, work,
siglum, label):
"""Returns extended match data derived from `extended_ngrams`.
This extended match data are the counts for all intermediate
n-grams within each extended n-gram.
:param extended_ngrams: extended n-grams
:type extended_ngrams: `list` of `str`
:param highest_n: the highest degree of n-grams in the original results
:type highest_n: `int`
:param work: name of the work bearing `extended_ngrams`
:type work: `str`
:param siglum: siglum of the text bearing `extended_ngrams`
:type siglum: `str`
:param label: label associated with the text
:type label: `str`
:rtype: `pandas.DataFrame`
"""
# Add data for each n-gram within each extended n-gram. Since
# this treats each extended piece of text separately, the same
# n-gram may be generated more than once, so the complete set
# of new possible matches for this filename needs to combine
# the counts for such.
rows_list = []
for extended_ngram in extended_ngrams:
text = Text(extended_ngram, self._tokenizer)
for size, ngrams in text.get_ngrams(highest_n+1,
len(text.get_tokens())):
data = [{constants.WORK_FIELDNAME: work,
constants.SIGLUM_FIELDNAME: siglum,
constants.LABEL_FIELDNAME: label,
constants.SIZE_FIELDNAME: size,
constants.NGRAM_FIELDNAME: ngram,
constants.COUNT_FIELDNAME: count}
for ngram, count in ngrams.items()]
rows_list.extend(data)
self._logger.debug('Number of extended results: {}'.format(
len(rows_list)))
extended_matches = pd.DataFrame(rows_list)
rows_list = None
self._logger.debug('Finished generating intermediate extended matches')
# extended_matches may be an empty DataFrame, in which case
# manipulating it on the basis of non-existing columns is not
# going to go well.
groupby_fields = [constants.NGRAM_FIELDNAME, constants.WORK_FIELDNAME,
constants.SIGLUM_FIELDNAME, constants.SIZE_FIELDNAME,
constants.LABEL_FIELDNAME]
if constants.NGRAM_FIELDNAME in extended_matches:
extended_matches = extended_matches.groupby(
groupby_fields, sort=False).sum().reset_index()
return extended_matches | [
"def",
"_generate_extended_matches",
"(",
"self",
",",
"extended_ngrams",
",",
"highest_n",
",",
"work",
",",
"siglum",
",",
"label",
")",
":",
"# Add data for each n-gram within each extended n-gram. Since",
"# this treats each extended piece of text separately, the same",
"# n-... | Returns extended match data derived from `extended_ngrams`.
This extended match data are the counts for all intermediate
n-grams within each extended n-gram.
:param extended_ngrams: extended n-grams
:type extended_ngrams: `list` of `str`
:param highest_n: the highest degree of n-grams in the original results
:type highest_n: `int`
:param work: name of the work bearing `extended_ngrams`
:type work: `str`
:param siglum: siglum of the text bearing `extended_ngrams`
:type siglum: `str`
:param label: label associated with the text
:type label: `str`
:rtype: `pandas.DataFrame` | [
"Returns",
"extended",
"match",
"data",
"derived",
"from",
"extended_ngrams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L351-L403 | train | 48,313 |
ajenhl/tacl | tacl/results.py | Results._generate_extended_ngrams | def _generate_extended_ngrams(self, matches, work, siglum, label, corpus,
highest_n):
"""Returns the n-grams of the largest size that exist in `siglum`
witness to `work` under `label`, generated from adding
together overlapping n-grams in `matches`.
:param matches: n-gram matches
:type matches: `pandas.DataFrame`
:param work: name of work whose results are being processed
:type work: `str`
:param siglum: siglum of witness whose results are being processed
:type siglum: `str`
:param label: label of witness whose results are being processed
:type label: `str`
:param corpus: corpus to which `filename` belongs
:type corpus: `Corpus`
:param highest_n: highest degree of n-gram in `matches`
:type highest_n: `int`
:rtype: `list` of `str`
"""
# For large result sets, this method may involve a lot of
# processing within the for loop, so optimise even small
# things, such as aliasing dotted calls here and below.
t_join = self._tokenizer.joiner.join
witness_matches = matches[
(matches[constants.WORK_FIELDNAME] == work) &
(matches[constants.SIGLUM_FIELDNAME] == siglum) &
(matches[constants.LABEL_FIELDNAME] == label)]
text = corpus.get_witness(work, siglum).get_token_content()
ngrams = [tuple(self._tokenizer.tokenize(ngram)) for ngram in
list(witness_matches[constants.NGRAM_FIELDNAME])]
# Go through the list of n-grams, and create a list of
# extended n-grams by joining two n-grams together that
# overlap (a[-overlap:] == b[:-1]) and checking that the result
# occurs in text.
working_ngrams = ngrams[:]
extended_ngrams = set(ngrams)
new_working_ngrams = []
overlap = highest_n - 1
# Create an index of n-grams by their overlapping portion,
# pointing to the non-overlapping token.
ngram_index = {}
for ngram in ngrams:
values = ngram_index.setdefault(ngram[:-1], [])
values.append(ngram[-1:])
extended_add = extended_ngrams.add
new_working_append = new_working_ngrams.append
ngram_size = highest_n
while working_ngrams:
removals = set()
ngram_size += 1
self._logger.debug(
'Iterating over {} n-grams to produce {}-grams'.format(
len(working_ngrams), ngram_size))
for base in working_ngrams:
remove_base = False
base_overlap = base[-overlap:]
for next_token in ngram_index.get(base_overlap, []):
extension = base + next_token
if t_join(extension) in text:
extended_add(extension)
new_working_append(extension)
remove_base = True
if remove_base:
# Remove base from extended_ngrams, because it is
# now encompassed by extension.
removals.add(base)
extended_ngrams -= removals
working_ngrams = new_working_ngrams[:]
new_working_ngrams = []
new_working_append = new_working_ngrams.append
extended_ngrams = sorted(extended_ngrams, key=len, reverse=True)
extended_ngrams = [t_join(ngram) for ngram in extended_ngrams]
self._logger.debug('Generated {} extended n-grams'.format(
len(extended_ngrams)))
self._logger.debug('Longest generated n-gram: {}'.format(
extended_ngrams[0]))
# In order to get the counts correct in the next step of the
# process, these n-grams must be overlaid over the text and
# repeated as many times as there are matches. N-grams that do
# not match (and they may not match on previously matched
# parts of the text) are discarded.
ngrams = []
for ngram in extended_ngrams:
# Remove from the text those parts that match. Replace
# them with a double space, which should prevent any
# incorrect match on the text from each side of the match
# that is now contiguous.
text, count = re.subn(re.escape(ngram), ' ', text)
ngrams.extend([ngram] * count)
self._logger.debug('Aligned extended n-grams with the text; '
'{} distinct n-grams exist'.format(len(ngrams)))
return ngrams | python | def _generate_extended_ngrams(self, matches, work, siglum, label, corpus,
highest_n):
"""Returns the n-grams of the largest size that exist in `siglum`
witness to `work` under `label`, generated from adding
together overlapping n-grams in `matches`.
:param matches: n-gram matches
:type matches: `pandas.DataFrame`
:param work: name of work whose results are being processed
:type work: `str`
:param siglum: siglum of witness whose results are being processed
:type siglum: `str`
:param label: label of witness whose results are being processed
:type label: `str`
:param corpus: corpus to which `filename` belongs
:type corpus: `Corpus`
:param highest_n: highest degree of n-gram in `matches`
:type highest_n: `int`
:rtype: `list` of `str`
"""
# For large result sets, this method may involve a lot of
# processing within the for loop, so optimise even small
# things, such as aliasing dotted calls here and below.
t_join = self._tokenizer.joiner.join
witness_matches = matches[
(matches[constants.WORK_FIELDNAME] == work) &
(matches[constants.SIGLUM_FIELDNAME] == siglum) &
(matches[constants.LABEL_FIELDNAME] == label)]
text = corpus.get_witness(work, siglum).get_token_content()
ngrams = [tuple(self._tokenizer.tokenize(ngram)) for ngram in
list(witness_matches[constants.NGRAM_FIELDNAME])]
# Go through the list of n-grams, and create a list of
# extended n-grams by joining two n-grams together that
# overlap (a[-overlap:] == b[:-1]) and checking that the result
# occurs in text.
working_ngrams = ngrams[:]
extended_ngrams = set(ngrams)
new_working_ngrams = []
overlap = highest_n - 1
# Create an index of n-grams by their overlapping portion,
# pointing to the non-overlapping token.
ngram_index = {}
for ngram in ngrams:
values = ngram_index.setdefault(ngram[:-1], [])
values.append(ngram[-1:])
extended_add = extended_ngrams.add
new_working_append = new_working_ngrams.append
ngram_size = highest_n
while working_ngrams:
removals = set()
ngram_size += 1
self._logger.debug(
'Iterating over {} n-grams to produce {}-grams'.format(
len(working_ngrams), ngram_size))
for base in working_ngrams:
remove_base = False
base_overlap = base[-overlap:]
for next_token in ngram_index.get(base_overlap, []):
extension = base + next_token
if t_join(extension) in text:
extended_add(extension)
new_working_append(extension)
remove_base = True
if remove_base:
# Remove base from extended_ngrams, because it is
# now encompassed by extension.
removals.add(base)
extended_ngrams -= removals
working_ngrams = new_working_ngrams[:]
new_working_ngrams = []
new_working_append = new_working_ngrams.append
extended_ngrams = sorted(extended_ngrams, key=len, reverse=True)
extended_ngrams = [t_join(ngram) for ngram in extended_ngrams]
self._logger.debug('Generated {} extended n-grams'.format(
len(extended_ngrams)))
self._logger.debug('Longest generated n-gram: {}'.format(
extended_ngrams[0]))
# In order to get the counts correct in the next step of the
# process, these n-grams must be overlaid over the text and
# repeated as many times as there are matches. N-grams that do
# not match (and they may not match on previously matched
# parts of the text) are discarded.
ngrams = []
for ngram in extended_ngrams:
# Remove from the text those parts that match. Replace
# them with a double space, which should prevent any
# incorrect match on the text from each side of the match
# that is now contiguous.
text, count = re.subn(re.escape(ngram), ' ', text)
ngrams.extend([ngram] * count)
self._logger.debug('Aligned extended n-grams with the text; '
'{} distinct n-grams exist'.format(len(ngrams)))
return ngrams | [
"def",
"_generate_extended_ngrams",
"(",
"self",
",",
"matches",
",",
"work",
",",
"siglum",
",",
"label",
",",
"corpus",
",",
"highest_n",
")",
":",
"# For large result sets, this method may involve a lot of",
"# processing within the for loop, so optimise even small",
"# th... | Returns the n-grams of the largest size that exist in `siglum`
witness to `work` under `label`, generated from adding
together overlapping n-grams in `matches`.
:param matches: n-gram matches
:type matches: `pandas.DataFrame`
:param work: name of work whose results are being processed
:type work: `str`
:param siglum: siglum of witness whose results are being processed
:type siglum: `str`
:param label: label of witness whose results are being processed
:type label: `str`
:param corpus: corpus to which `filename` belongs
:type corpus: `Corpus`
:param highest_n: highest degree of n-gram in `matches`
:type highest_n: `int`
:rtype: `list` of `str` | [
"Returns",
"the",
"n",
"-",
"grams",
"of",
"the",
"largest",
"size",
"that",
"exist",
"in",
"siglum",
"witness",
"to",
"work",
"under",
"label",
"generated",
"from",
"adding",
"together",
"overlapping",
"n",
"-",
"grams",
"in",
"matches",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L405-L498 | train | 48,314 |
ajenhl/tacl | tacl/results.py | Results._generate_filter_ngrams | def _generate_filter_ngrams(self, data, min_size):
"""Returns the n-grams in `data` that do not contain any other n-gram
in `data`.
:param data: n-gram results data
:type data: `pandas.DataFrame`
:param min_size: minimum n-gram size in `data`
:type min_size: `int`
:rtype: `list` of `str`
"""
max_size = data[constants.SIZE_FIELDNAME].max()
kept_ngrams = list(data[data[constants.SIZE_FIELDNAME] == min_size][
constants.NGRAM_FIELDNAME])
for size in range(min_size+1, max_size+1):
pattern = FilteredWitnessText.get_filter_ngrams_pattern(
kept_ngrams)
potential_ngrams = list(data[data[constants.SIZE_FIELDNAME] ==
size][constants.NGRAM_FIELDNAME])
kept_ngrams.extend([ngram for ngram in potential_ngrams if
pattern.search(ngram) is None])
return kept_ngrams | python | def _generate_filter_ngrams(self, data, min_size):
"""Returns the n-grams in `data` that do not contain any other n-gram
in `data`.
:param data: n-gram results data
:type data: `pandas.DataFrame`
:param min_size: minimum n-gram size in `data`
:type min_size: `int`
:rtype: `list` of `str`
"""
max_size = data[constants.SIZE_FIELDNAME].max()
kept_ngrams = list(data[data[constants.SIZE_FIELDNAME] == min_size][
constants.NGRAM_FIELDNAME])
for size in range(min_size+1, max_size+1):
pattern = FilteredWitnessText.get_filter_ngrams_pattern(
kept_ngrams)
potential_ngrams = list(data[data[constants.SIZE_FIELDNAME] ==
size][constants.NGRAM_FIELDNAME])
kept_ngrams.extend([ngram for ngram in potential_ngrams if
pattern.search(ngram) is None])
return kept_ngrams | [
"def",
"_generate_filter_ngrams",
"(",
"self",
",",
"data",
",",
"min_size",
")",
":",
"max_size",
"=",
"data",
"[",
"constants",
".",
"SIZE_FIELDNAME",
"]",
".",
"max",
"(",
")",
"kept_ngrams",
"=",
"list",
"(",
"data",
"[",
"data",
"[",
"constants",
".... | Returns the n-grams in `data` that do not contain any other n-gram
in `data`.
:param data: n-gram results data
:type data: `pandas.DataFrame`
:param min_size: minimum n-gram size in `data`
:type min_size: `int`
:rtype: `list` of `str` | [
"Returns",
"the",
"n",
"-",
"grams",
"in",
"data",
"that",
"do",
"not",
"contain",
"any",
"other",
"n",
"-",
"gram",
"in",
"data",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L500-L521 | train | 48,315 |
ajenhl/tacl | tacl/results.py | Results._generate_substrings | def _generate_substrings(self, ngram, size):
"""Returns a list of all substrings of `ngram`.
:param ngram: n-gram to generate substrings of
:type ngram: `str`
:param size: size of `ngram`
:type size: `int`
:rtype: `list`
"""
text = Text(ngram, self._tokenizer)
substrings = []
for sub_size, ngrams in text.get_ngrams(1, size-1):
for sub_ngram, count in ngrams.items():
substrings.extend([sub_ngram] * count)
return substrings | python | def _generate_substrings(self, ngram, size):
"""Returns a list of all substrings of `ngram`.
:param ngram: n-gram to generate substrings of
:type ngram: `str`
:param size: size of `ngram`
:type size: `int`
:rtype: `list`
"""
text = Text(ngram, self._tokenizer)
substrings = []
for sub_size, ngrams in text.get_ngrams(1, size-1):
for sub_ngram, count in ngrams.items():
substrings.extend([sub_ngram] * count)
return substrings | [
"def",
"_generate_substrings",
"(",
"self",
",",
"ngram",
",",
"size",
")",
":",
"text",
"=",
"Text",
"(",
"ngram",
",",
"self",
".",
"_tokenizer",
")",
"substrings",
"=",
"[",
"]",
"for",
"sub_size",
",",
"ngrams",
"in",
"text",
".",
"get_ngrams",
"("... | Returns a list of all substrings of `ngram`.
:param ngram: n-gram to generate substrings of
:type ngram: `str`
:param size: size of `ngram`
:type size: `int`
:rtype: `list` | [
"Returns",
"a",
"list",
"of",
"all",
"substrings",
"of",
"ngram",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L523-L538 | train | 48,316 |
ajenhl/tacl | tacl/results.py | Results.group_by_witness | def group_by_witness(self):
"""Groups results by witness, providing a single summary field giving
the n-grams found in it, a count of their number, and the count of
their combined occurrences."""
if self._matches.empty:
# Ensure that the right columns are used, even though the
# results are empty.
self._matches = pd.DataFrame(
{}, columns=[constants.WORK_FIELDNAME,
constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME,
constants.NGRAMS_FIELDNAME,
constants.NUMBER_FIELDNAME,
constants.TOTAL_COUNT_FIELDNAME])
return
def witness_summary(group):
matches = group.sort_values(by=[constants.NGRAM_FIELDNAME],
ascending=[True])
match = matches.iloc[0]
ngrams = ', '.join(list(matches[constants.NGRAM_FIELDNAME]))
match[constants.NGRAMS_FIELDNAME] = ngrams
match[constants.NUMBER_FIELDNAME] = len(matches)
match[constants.TOTAL_COUNT_FIELDNAME] = matches[
constants.COUNT_FIELDNAME].sum()
return match
group_cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME]
# Remove zero-count results.
self._matches = self._matches[
self._matches[constants.COUNT_FIELDNAME] != 0]
self._matches = self._matches.groupby(group_cols, sort=False).apply(
witness_summary)
del self._matches[constants.NGRAM_FIELDNAME]
del self._matches[constants.SIZE_FIELDNAME]
del self._matches[constants.COUNT_FIELDNAME] | python | def group_by_witness(self):
"""Groups results by witness, providing a single summary field giving
the n-grams found in it, a count of their number, and the count of
their combined occurrences."""
if self._matches.empty:
# Ensure that the right columns are used, even though the
# results are empty.
self._matches = pd.DataFrame(
{}, columns=[constants.WORK_FIELDNAME,
constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME,
constants.NGRAMS_FIELDNAME,
constants.NUMBER_FIELDNAME,
constants.TOTAL_COUNT_FIELDNAME])
return
def witness_summary(group):
matches = group.sort_values(by=[constants.NGRAM_FIELDNAME],
ascending=[True])
match = matches.iloc[0]
ngrams = ', '.join(list(matches[constants.NGRAM_FIELDNAME]))
match[constants.NGRAMS_FIELDNAME] = ngrams
match[constants.NUMBER_FIELDNAME] = len(matches)
match[constants.TOTAL_COUNT_FIELDNAME] = matches[
constants.COUNT_FIELDNAME].sum()
return match
group_cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME]
# Remove zero-count results.
self._matches = self._matches[
self._matches[constants.COUNT_FIELDNAME] != 0]
self._matches = self._matches.groupby(group_cols, sort=False).apply(
witness_summary)
del self._matches[constants.NGRAM_FIELDNAME]
del self._matches[constants.SIZE_FIELDNAME]
del self._matches[constants.COUNT_FIELDNAME] | [
"def",
"group_by_witness",
"(",
"self",
")",
":",
"if",
"self",
".",
"_matches",
".",
"empty",
":",
"# Ensure that the right columns are used, even though the",
"# results are empty.",
"self",
".",
"_matches",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"}",
",",
"colu... | Groups results by witness, providing a single summary field giving
the n-grams found in it, a count of their number, and the count of
their combined occurrences. | [
"Groups",
"results",
"by",
"witness",
"providing",
"a",
"single",
"summary",
"field",
"giving",
"the",
"n",
"-",
"grams",
"found",
"in",
"it",
"a",
"count",
"of",
"their",
"number",
"and",
"the",
"count",
"of",
"their",
"combined",
"occurrences",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L613-L648 | train | 48,317 |
ajenhl/tacl | tacl/results.py | Results._is_intersect_results | def _is_intersect_results(results):
"""Returns False if `results` has an n-gram that exists in only one
label, True otherwise.
:param results: results to analyze
:type results: `pandas.DataFrame`
:rtype: `bool`
"""
sample = results.iloc[0]
ngram = sample[constants.NGRAM_FIELDNAME]
label = sample[constants.LABEL_FIELDNAME]
return not(results[
(results[constants.NGRAM_FIELDNAME] == ngram) &
(results[constants.LABEL_FIELDNAME] != label)].empty) | python | def _is_intersect_results(results):
"""Returns False if `results` has an n-gram that exists in only one
label, True otherwise.
:param results: results to analyze
:type results: `pandas.DataFrame`
:rtype: `bool`
"""
sample = results.iloc[0]
ngram = sample[constants.NGRAM_FIELDNAME]
label = sample[constants.LABEL_FIELDNAME]
return not(results[
(results[constants.NGRAM_FIELDNAME] == ngram) &
(results[constants.LABEL_FIELDNAME] != label)].empty) | [
"def",
"_is_intersect_results",
"(",
"results",
")",
":",
"sample",
"=",
"results",
".",
"iloc",
"[",
"0",
"]",
"ngram",
"=",
"sample",
"[",
"constants",
".",
"NGRAM_FIELDNAME",
"]",
"label",
"=",
"sample",
"[",
"constants",
".",
"LABEL_FIELDNAME",
"]",
"r... | Returns False if `results` has an n-gram that exists in only one
label, True otherwise.
:param results: results to analyze
:type results: `pandas.DataFrame`
:rtype: `bool` | [
"Returns",
"False",
"if",
"results",
"has",
"an",
"n",
"-",
"gram",
"that",
"exists",
"in",
"only",
"one",
"label",
"True",
"otherwise",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L651-L665 | train | 48,318 |
ajenhl/tacl | tacl/results.py | Results.prune_by_ngram | def prune_by_ngram(self, ngrams):
"""Removes results rows whose n-gram is in `ngrams`.
:param ngrams: n-grams to remove
:type ngrams: `list` of `str`
"""
self._logger.info('Pruning results by n-gram')
self._matches = self._matches[
~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)] | python | def prune_by_ngram(self, ngrams):
"""Removes results rows whose n-gram is in `ngrams`.
:param ngrams: n-grams to remove
:type ngrams: `list` of `str`
"""
self._logger.info('Pruning results by n-gram')
self._matches = self._matches[
~self._matches[constants.NGRAM_FIELDNAME].isin(ngrams)] | [
"def",
"prune_by_ngram",
"(",
"self",
",",
"ngrams",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Pruning results by n-gram'",
")",
"self",
".",
"_matches",
"=",
"self",
".",
"_matches",
"[",
"~",
"self",
".",
"_matches",
"[",
"constants",
".",
... | Removes results rows whose n-gram is in `ngrams`.
:param ngrams: n-grams to remove
:type ngrams: `list` of `str` | [
"Removes",
"results",
"rows",
"whose",
"n",
"-",
"gram",
"is",
"in",
"ngrams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L704-L713 | train | 48,319 |
ajenhl/tacl | tacl/results.py | Results.prune_by_ngram_count_per_work | def prune_by_ngram_count_per_work(self, minimum=None, maximum=None,
label=None):
"""Removes results rows if the n-gram count for all works bearing that
n-gram is outside the range specified by `minimum` and
`maximum`.
That is, if a single witness of a single work has an n-gram
count that falls within the specified range, all result rows
for that n-gram are kept.
If `label` is specified, the works checked are restricted to
those associated with `label`.
:param minimum: minimum n-gram count
:type minimum: `int`
:param maximum: maximum n-gram count
:type maximum: `int`
:param label: optional label to restrict requirement to
:type label: `str`
"""
self._logger.info('Pruning results by n-gram count per work')
matches = self._matches
keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique()
if label is not None:
matches = matches[matches[constants.LABEL_FIELDNAME] == label]
if minimum and maximum:
keep_ngrams = matches[
(matches[constants.COUNT_FIELDNAME] >= minimum) &
(matches[constants.COUNT_FIELDNAME] <= maximum)][
constants.NGRAM_FIELDNAME].unique()
elif minimum:
keep_ngrams = matches[
matches[constants.COUNT_FIELDNAME] >= minimum][
constants.NGRAM_FIELDNAME].unique()
elif maximum:
keep_ngrams = matches[
self._matches[constants.COUNT_FIELDNAME] <= maximum][
constants.NGRAM_FIELDNAME].unique()
self._matches = self._matches[self._matches[
constants.NGRAM_FIELDNAME].isin(keep_ngrams)] | python | def prune_by_ngram_count_per_work(self, minimum=None, maximum=None,
label=None):
"""Removes results rows if the n-gram count for all works bearing that
n-gram is outside the range specified by `minimum` and
`maximum`.
That is, if a single witness of a single work has an n-gram
count that falls within the specified range, all result rows
for that n-gram are kept.
If `label` is specified, the works checked are restricted to
those associated with `label`.
:param minimum: minimum n-gram count
:type minimum: `int`
:param maximum: maximum n-gram count
:type maximum: `int`
:param label: optional label to restrict requirement to
:type label: `str`
"""
self._logger.info('Pruning results by n-gram count per work')
matches = self._matches
keep_ngrams = matches[constants.NGRAM_FIELDNAME].unique()
if label is not None:
matches = matches[matches[constants.LABEL_FIELDNAME] == label]
if minimum and maximum:
keep_ngrams = matches[
(matches[constants.COUNT_FIELDNAME] >= minimum) &
(matches[constants.COUNT_FIELDNAME] <= maximum)][
constants.NGRAM_FIELDNAME].unique()
elif minimum:
keep_ngrams = matches[
matches[constants.COUNT_FIELDNAME] >= minimum][
constants.NGRAM_FIELDNAME].unique()
elif maximum:
keep_ngrams = matches[
self._matches[constants.COUNT_FIELDNAME] <= maximum][
constants.NGRAM_FIELDNAME].unique()
self._matches = self._matches[self._matches[
constants.NGRAM_FIELDNAME].isin(keep_ngrams)] | [
"def",
"prune_by_ngram_count_per_work",
"(",
"self",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Pruning results by n-gram count per work'",
")",
"matches",
"=",
"se... | Removes results rows if the n-gram count for all works bearing that
n-gram is outside the range specified by `minimum` and
`maximum`.
That is, if a single witness of a single work has an n-gram
count that falls within the specified range, all result rows
for that n-gram are kept.
If `label` is specified, the works checked are restricted to
those associated with `label`.
:param minimum: minimum n-gram count
:type minimum: `int`
:param maximum: maximum n-gram count
:type maximum: `int`
:param label: optional label to restrict requirement to
:type label: `str` | [
"Removes",
"results",
"rows",
"if",
"the",
"n",
"-",
"gram",
"count",
"for",
"all",
"works",
"bearing",
"that",
"n",
"-",
"gram",
"is",
"outside",
"the",
"range",
"specified",
"by",
"minimum",
"and",
"maximum",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L771-L811 | train | 48,320 |
ajenhl/tacl | tacl/results.py | Results.prune_by_ngram_size | def prune_by_ngram_size(self, minimum=None, maximum=None):
"""Removes results rows whose n-gram size is outside the
range specified by `minimum` and `maximum`.
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
"""
self._logger.info('Pruning results by n-gram size')
if minimum:
self._matches = self._matches[
self._matches[constants.SIZE_FIELDNAME] >= minimum]
if maximum:
self._matches = self._matches[
self._matches[constants.SIZE_FIELDNAME] <= maximum] | python | def prune_by_ngram_size(self, minimum=None, maximum=None):
"""Removes results rows whose n-gram size is outside the
range specified by `minimum` and `maximum`.
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
"""
self._logger.info('Pruning results by n-gram size')
if minimum:
self._matches = self._matches[
self._matches[constants.SIZE_FIELDNAME] >= minimum]
if maximum:
self._matches = self._matches[
self._matches[constants.SIZE_FIELDNAME] <= maximum] | [
"def",
"prune_by_ngram_size",
"(",
"self",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Pruning results by n-gram size'",
")",
"if",
"minimum",
":",
"self",
".",
"_matches",
"=",
"self",
".... | Removes results rows whose n-gram size is outside the
range specified by `minimum` and `maximum`.
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int` | [
"Removes",
"results",
"rows",
"whose",
"n",
"-",
"gram",
"size",
"is",
"outside",
"the",
"range",
"specified",
"by",
"minimum",
"and",
"maximum",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L814-L830 | train | 48,321 |
ajenhl/tacl | tacl/results.py | Results.prune_by_work_count | def prune_by_work_count(self, minimum=None, maximum=None, label=None):
"""Removes results rows for n-grams that are not attested in a
number of works in the range specified by `minimum` and
`maximum`.
Work here encompasses all witnesses, so that the same n-gram
appearing in multiple witnesses of the same work are counted
as a single work.
If `label` is specified, the works counted are restricted to
those associated with `label`.
:param minimum: minimum number of works
:type minimum: `int`
:param maximum: maximum number of works
:type maximum: `int`
:param label: optional label to restrict requirement to
:type label: `str`
"""
self._logger.info('Pruning results by work count')
count_fieldname = 'tmp_count'
matches = self._matches
if label is not None:
matches = matches[matches[constants.LABEL_FIELDNAME] == label]
filtered = matches[matches[constants.COUNT_FIELDNAME] > 0]
grouped = filtered.groupby(constants.NGRAM_FIELDNAME, sort=False)
counts = pd.DataFrame(grouped[constants.WORK_FIELDNAME].nunique())
counts.rename(columns={constants.WORK_FIELDNAME: count_fieldname},
inplace=True)
if minimum:
counts = counts[counts[count_fieldname] >= minimum]
if maximum:
counts = counts[counts[count_fieldname] <= maximum]
self._matches = pd.merge(self._matches, counts,
left_on=constants.NGRAM_FIELDNAME,
right_index=True)
del self._matches[count_fieldname] | python | def prune_by_work_count(self, minimum=None, maximum=None, label=None):
"""Removes results rows for n-grams that are not attested in a
number of works in the range specified by `minimum` and
`maximum`.
Work here encompasses all witnesses, so that the same n-gram
appearing in multiple witnesses of the same work are counted
as a single work.
If `label` is specified, the works counted are restricted to
those associated with `label`.
:param minimum: minimum number of works
:type minimum: `int`
:param maximum: maximum number of works
:type maximum: `int`
:param label: optional label to restrict requirement to
:type label: `str`
"""
self._logger.info('Pruning results by work count')
count_fieldname = 'tmp_count'
matches = self._matches
if label is not None:
matches = matches[matches[constants.LABEL_FIELDNAME] == label]
filtered = matches[matches[constants.COUNT_FIELDNAME] > 0]
grouped = filtered.groupby(constants.NGRAM_FIELDNAME, sort=False)
counts = pd.DataFrame(grouped[constants.WORK_FIELDNAME].nunique())
counts.rename(columns={constants.WORK_FIELDNAME: count_fieldname},
inplace=True)
if minimum:
counts = counts[counts[count_fieldname] >= minimum]
if maximum:
counts = counts[counts[count_fieldname] <= maximum]
self._matches = pd.merge(self._matches, counts,
left_on=constants.NGRAM_FIELDNAME,
right_index=True)
del self._matches[count_fieldname] | [
"def",
"prune_by_work_count",
"(",
"self",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Pruning results by work count'",
")",
"count_fieldname",
"=",
"'tmp_count'",
... | Removes results rows for n-grams that are not attested in a
number of works in the range specified by `minimum` and
`maximum`.
Work here encompasses all witnesses, so that the same n-gram
appearing in multiple witnesses of the same work are counted
as a single work.
If `label` is specified, the works counted are restricted to
those associated with `label`.
:param minimum: minimum number of works
:type minimum: `int`
:param maximum: maximum number of works
:type maximum: `int`
:param label: optional label to restrict requirement to
:type label: `str` | [
"Removes",
"results",
"rows",
"for",
"n",
"-",
"grams",
"that",
"are",
"not",
"attested",
"in",
"a",
"number",
"of",
"works",
"in",
"the",
"range",
"specified",
"by",
"minimum",
"and",
"maximum",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L834-L871 | train | 48,322 |
ajenhl/tacl | tacl/results.py | Results.reciprocal_remove | def reciprocal_remove(self):
"""Removes results rows for which the n-gram is not present in
at least one text in each labelled set of texts."""
self._logger.info(
'Removing n-grams that are not attested in all labels')
self._matches = self._reciprocal_remove(self._matches) | python | def reciprocal_remove(self):
"""Removes results rows for which the n-gram is not present in
at least one text in each labelled set of texts."""
self._logger.info(
'Removing n-grams that are not attested in all labels')
self._matches = self._reciprocal_remove(self._matches) | [
"def",
"reciprocal_remove",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Removing n-grams that are not attested in all labels'",
")",
"self",
".",
"_matches",
"=",
"self",
".",
"_reciprocal_remove",
"(",
"self",
".",
"_matches",
")"
] | Removes results rows for which the n-gram is not present in
at least one text in each labelled set of texts. | [
"Removes",
"results",
"rows",
"for",
"which",
"the",
"n",
"-",
"gram",
"is",
"not",
"present",
"in",
"at",
"least",
"one",
"text",
"in",
"each",
"labelled",
"set",
"of",
"texts",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L875-L880 | train | 48,323 |
ajenhl/tacl | tacl/results.py | Results.reduce | def reduce(self):
"""Removes results rows whose n-grams are contained in larger
n-grams."""
self._logger.info('Reducing the n-grams')
# This does not make use of any pandas functionality; it
# probably could, and if so ought to.
data = {}
labels = {}
# Derive a convenient data structure from the rows.
for row_index, row in self._matches.iterrows():
work = row[constants.WORK_FIELDNAME]
siglum = row[constants.SIGLUM_FIELDNAME]
labels[work] = row[constants.LABEL_FIELDNAME]
witness_data = data.setdefault((work, siglum), {})
witness_data[row[constants.NGRAM_FIELDNAME]] = {
'count': int(row[constants.COUNT_FIELDNAME]),
'size': int(row[constants.SIZE_FIELDNAME])}
for witness_data in data.values():
ngrams = list(witness_data.keys())
ngrams.sort(key=lambda ngram: witness_data[ngram]['size'],
reverse=True)
for ngram in ngrams:
if witness_data[ngram]['count'] > 0:
self._reduce_by_ngram(witness_data, ngram)
# Recreate rows from the modified data structure.
rows = []
for (work, siglum), witness_data in data.items():
for ngram, ngram_data in witness_data.items():
count = ngram_data['count']
if count > 0:
rows.append(
{constants.NGRAM_FIELDNAME: ngram,
constants.SIZE_FIELDNAME: ngram_data['size'],
constants.WORK_FIELDNAME: work,
constants.SIGLUM_FIELDNAME: siglum,
constants.COUNT_FIELDNAME: count,
constants.LABEL_FIELDNAME: labels[work]})
self._matches = pd.DataFrame(
rows, columns=constants.QUERY_FIELDNAMES) | python | def reduce(self):
"""Removes results rows whose n-grams are contained in larger
n-grams."""
self._logger.info('Reducing the n-grams')
# This does not make use of any pandas functionality; it
# probably could, and if so ought to.
data = {}
labels = {}
# Derive a convenient data structure from the rows.
for row_index, row in self._matches.iterrows():
work = row[constants.WORK_FIELDNAME]
siglum = row[constants.SIGLUM_FIELDNAME]
labels[work] = row[constants.LABEL_FIELDNAME]
witness_data = data.setdefault((work, siglum), {})
witness_data[row[constants.NGRAM_FIELDNAME]] = {
'count': int(row[constants.COUNT_FIELDNAME]),
'size': int(row[constants.SIZE_FIELDNAME])}
for witness_data in data.values():
ngrams = list(witness_data.keys())
ngrams.sort(key=lambda ngram: witness_data[ngram]['size'],
reverse=True)
for ngram in ngrams:
if witness_data[ngram]['count'] > 0:
self._reduce_by_ngram(witness_data, ngram)
# Recreate rows from the modified data structure.
rows = []
for (work, siglum), witness_data in data.items():
for ngram, ngram_data in witness_data.items():
count = ngram_data['count']
if count > 0:
rows.append(
{constants.NGRAM_FIELDNAME: ngram,
constants.SIZE_FIELDNAME: ngram_data['size'],
constants.WORK_FIELDNAME: work,
constants.SIGLUM_FIELDNAME: siglum,
constants.COUNT_FIELDNAME: count,
constants.LABEL_FIELDNAME: labels[work]})
self._matches = pd.DataFrame(
rows, columns=constants.QUERY_FIELDNAMES) | [
"def",
"reduce",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Reducing the n-grams'",
")",
"# This does not make use of any pandas functionality; it",
"# probably could, and if so ought to.",
"data",
"=",
"{",
"}",
"labels",
"=",
"{",
"}",
"# Der... | Removes results rows whose n-grams are contained in larger
n-grams. | [
"Removes",
"results",
"rows",
"whose",
"n",
"-",
"grams",
"are",
"contained",
"in",
"larger",
"n",
"-",
"grams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L892-L930 | train | 48,324 |
ajenhl/tacl | tacl/results.py | Results._reduce_by_ngram | def _reduce_by_ngram(self, data, ngram):
"""Lowers the counts of all n-grams in `data` that are
substrings of `ngram` by `ngram`\'s count.
Modifies `data` in place.
:param data: row data dictionary for the current text
:type data: `dict`
:param ngram: n-gram being reduced
:type ngram: `str`
"""
# Find all substrings of `ngram` and reduce their count by the
# count of `ngram`. Substrings may not exist in `data`.
count = data[ngram]['count']
for substring in self._generate_substrings(ngram, data[ngram]['size']):
try:
substring_data = data[substring]
except KeyError:
continue
else:
substring_data['count'] -= count | python | def _reduce_by_ngram(self, data, ngram):
"""Lowers the counts of all n-grams in `data` that are
substrings of `ngram` by `ngram`\'s count.
Modifies `data` in place.
:param data: row data dictionary for the current text
:type data: `dict`
:param ngram: n-gram being reduced
:type ngram: `str`
"""
# Find all substrings of `ngram` and reduce their count by the
# count of `ngram`. Substrings may not exist in `data`.
count = data[ngram]['count']
for substring in self._generate_substrings(ngram, data[ngram]['size']):
try:
substring_data = data[substring]
except KeyError:
continue
else:
substring_data['count'] -= count | [
"def",
"_reduce_by_ngram",
"(",
"self",
",",
"data",
",",
"ngram",
")",
":",
"# Find all substrings of `ngram` and reduce their count by the",
"# count of `ngram`. Substrings may not exist in `data`.",
"count",
"=",
"data",
"[",
"ngram",
"]",
"[",
"'count'",
"]",
"for",
"... | Lowers the counts of all n-grams in `data` that are
substrings of `ngram` by `ngram`\'s count.
Modifies `data` in place.
:param data: row data dictionary for the current text
:type data: `dict`
:param ngram: n-gram being reduced
:type ngram: `str` | [
"Lowers",
"the",
"counts",
"of",
"all",
"n",
"-",
"grams",
"in",
"data",
"that",
"are",
"substrings",
"of",
"ngram",
"by",
"ngram",
"\\",
"s",
"count",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L932-L953 | train | 48,325 |
ajenhl/tacl | tacl/results.py | Results.relabel | def relabel(self, catalogue):
"""Relabels results rows according to `catalogue`.
A row whose work is labelled in the catalogue will have its
label set to the label in the catalogue. Rows whose works are
not labelled in the catalogue will be unchanged.
:param catalogue: mapping of work names to labels
:type catalogue: `Catalogue`
"""
for work, label in catalogue.items():
self._matches.loc[self._matches[constants.WORK_FIELDNAME] == work,
constants.LABEL_FIELDNAME] = label | python | def relabel(self, catalogue):
"""Relabels results rows according to `catalogue`.
A row whose work is labelled in the catalogue will have its
label set to the label in the catalogue. Rows whose works are
not labelled in the catalogue will be unchanged.
:param catalogue: mapping of work names to labels
:type catalogue: `Catalogue`
"""
for work, label in catalogue.items():
self._matches.loc[self._matches[constants.WORK_FIELDNAME] == work,
constants.LABEL_FIELDNAME] = label | [
"def",
"relabel",
"(",
"self",
",",
"catalogue",
")",
":",
"for",
"work",
",",
"label",
"in",
"catalogue",
".",
"items",
"(",
")",
":",
"self",
".",
"_matches",
".",
"loc",
"[",
"self",
".",
"_matches",
"[",
"constants",
".",
"WORK_FIELDNAME",
"]",
"... | Relabels results rows according to `catalogue`.
A row whose work is labelled in the catalogue will have its
label set to the label in the catalogue. Rows whose works are
not labelled in the catalogue will be unchanged.
:param catalogue: mapping of work names to labels
:type catalogue: `Catalogue` | [
"Relabels",
"results",
"rows",
"according",
"to",
"catalogue",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L956-L969 | train | 48,326 |
ajenhl/tacl | tacl/results.py | Results.remove_label | def remove_label(self, label):
"""Removes all results rows associated with `label`.
:param label: label to filter results on
:type label: `str`
"""
self._logger.info('Removing label "{}"'.format(label))
count = self._matches[constants.LABEL_FIELDNAME].value_counts().get(
label, 0)
self._matches = self._matches[
self._matches[constants.LABEL_FIELDNAME] != label]
self._logger.info('Removed {} labelled results'.format(count)) | python | def remove_label(self, label):
"""Removes all results rows associated with `label`.
:param label: label to filter results on
:type label: `str`
"""
self._logger.info('Removing label "{}"'.format(label))
count = self._matches[constants.LABEL_FIELDNAME].value_counts().get(
label, 0)
self._matches = self._matches[
self._matches[constants.LABEL_FIELDNAME] != label]
self._logger.info('Removed {} labelled results'.format(count)) | [
"def",
"remove_label",
"(",
"self",
",",
"label",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Removing label \"{}\"'",
".",
"format",
"(",
"label",
")",
")",
"count",
"=",
"self",
".",
"_matches",
"[",
"constants",
".",
"LABEL_FIELDNAME",
"]",
... | Removes all results rows associated with `label`.
:param label: label to filter results on
:type label: `str` | [
"Removes",
"all",
"results",
"rows",
"associated",
"with",
"label",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L972-L984 | train | 48,327 |
ajenhl/tacl | tacl/results.py | Results.sort | def sort(self):
"""Sorts all results rows.
Sorts by: size (descending), n-gram, count (descending), label,
text name, siglum.
"""
self._matches.sort_values(
by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME,
constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME],
ascending=[False, True, False, True, True, True], inplace=True) | python | def sort(self):
"""Sorts all results rows.
Sorts by: size (descending), n-gram, count (descending), label,
text name, siglum.
"""
self._matches.sort_values(
by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME,
constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME],
ascending=[False, True, False, True, True, True], inplace=True) | [
"def",
"sort",
"(",
"self",
")",
":",
"self",
".",
"_matches",
".",
"sort_values",
"(",
"by",
"=",
"[",
"constants",
".",
"SIZE_FIELDNAME",
",",
"constants",
".",
"NGRAM_FIELDNAME",
",",
"constants",
".",
"COUNT_FIELDNAME",
",",
"constants",
".",
"LABEL_FIEL... | Sorts all results rows.
Sorts by: size (descending), n-gram, count (descending), label,
text name, siglum. | [
"Sorts",
"all",
"results",
"rows",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L989-L1000 | train | 48,328 |
ajenhl/tacl | tacl/results.py | Results.zero_fill | def zero_fill(self, corpus):
"""Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
:type corpus: `Corpus`
"""
self._logger.info('Zero-filling results')
zero_rows = []
work_sigla = {}
grouping_cols = [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.SIZE_FIELDNAME, constants.WORK_FIELDNAME]
grouped = self._matches.groupby(grouping_cols, sort=False)
for (label, ngram, size, work), group in grouped:
row_data = {
constants.NGRAM_FIELDNAME: ngram,
constants.LABEL_FIELDNAME: label,
constants.SIZE_FIELDNAME: size,
constants.COUNT_FIELDNAME: 0,
constants.WORK_FIELDNAME: work,
}
if work not in work_sigla:
work_sigla[work] = corpus.get_sigla(work)
for siglum in work_sigla[work]:
if group[group[constants.SIGLUM_FIELDNAME] == siglum].empty:
row_data[constants.SIGLUM_FIELDNAME] = siglum
zero_rows.append(row_data)
zero_df = pd.DataFrame(zero_rows, columns=constants.QUERY_FIELDNAMES)
self._matches = pd.concat([self._matches, zero_df], ignore_index=True,
sort=False) | python | def zero_fill(self, corpus):
"""Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
:type corpus: `Corpus`
"""
self._logger.info('Zero-filling results')
zero_rows = []
work_sigla = {}
grouping_cols = [constants.LABEL_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.SIZE_FIELDNAME, constants.WORK_FIELDNAME]
grouped = self._matches.groupby(grouping_cols, sort=False)
for (label, ngram, size, work), group in grouped:
row_data = {
constants.NGRAM_FIELDNAME: ngram,
constants.LABEL_FIELDNAME: label,
constants.SIZE_FIELDNAME: size,
constants.COUNT_FIELDNAME: 0,
constants.WORK_FIELDNAME: work,
}
if work not in work_sigla:
work_sigla[work] = corpus.get_sigla(work)
for siglum in work_sigla[work]:
if group[group[constants.SIGLUM_FIELDNAME] == siglum].empty:
row_data[constants.SIGLUM_FIELDNAME] = siglum
zero_rows.append(row_data)
zero_df = pd.DataFrame(zero_rows, columns=constants.QUERY_FIELDNAMES)
self._matches = pd.concat([self._matches, zero_df], ignore_index=True,
sort=False) | [
"def",
"zero_fill",
"(",
"self",
",",
"corpus",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Zero-filling results'",
")",
"zero_rows",
"=",
"[",
"]",
"work_sigla",
"=",
"{",
"}",
"grouping_cols",
"=",
"[",
"constants",
".",
"LABEL_FIELDNAME",
",",... | Adds rows to the results to ensure that, for every n-gram that is
attested in at least one witness, every witness for that text
has a row, with added rows having a count of zero.
:param corpus: corpus containing the texts appearing in the results
:type corpus: `Corpus` | [
"Adds",
"rows",
"to",
"the",
"results",
"to",
"ensure",
"that",
"for",
"every",
"n",
"-",
"gram",
"that",
"is",
"attested",
"in",
"at",
"least",
"one",
"witness",
"every",
"witness",
"for",
"that",
"text",
"has",
"a",
"row",
"with",
"added",
"rows",
"h... | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L1005-L1036 | train | 48,329 |
SuperCowPowers/chains | chains/utils/log_utils.py | get_logger | def get_logger():
"""Setup logging output defaults"""
# Grab the logger
if not hasattr(get_logger, 'logger'):
# Setup the default logging config
get_logger.logger = logging.getLogger('chains')
format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s'
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, format=format_str)
# Return the logger
return get_logger.logger | python | def get_logger():
"""Setup logging output defaults"""
# Grab the logger
if not hasattr(get_logger, 'logger'):
# Setup the default logging config
get_logger.logger = logging.getLogger('chains')
format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(message)s'
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, format=format_str)
# Return the logger
return get_logger.logger | [
"def",
"get_logger",
"(",
")",
":",
"# Grab the logger",
"if",
"not",
"hasattr",
"(",
"get_logger",
",",
"'logger'",
")",
":",
"# Setup the default logging config",
"get_logger",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'chains'",
")",
"format_str",
... | Setup logging output defaults | [
"Setup",
"logging",
"output",
"defaults"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/log_utils.py#L7-L19 | train | 48,330 |
SuperCowPowers/chains | chains/sources/packet_streamer.py | PacketStreamer.read_interface | def read_interface(self):
"""Read Packets from the packet capture interface"""
# Spin up the packet capture
if self._iface_is_file():
self.pcap = pcapy.open_offline(self.iface_name)
else:
try:
# self.pcap = pcap.pcap(name=self.iface_name, promisc=True, immediate=True)
# snaplen (maximum number of bytes to capture _per_packet_)
# promiscious mode (1 for true)
# timeout (in milliseconds)
self.pcap = pcapy.open_live(self.iface_name, 65536 , 1 , 0)
except OSError:
try:
logger.warning('Could not get promisc mode, turning flag off')
self.pcap = pcapy.open_live(self.iface_name, 65536 , 0 , 0)
except OSError:
log_utils.panic('Could no open interface with any options (may need to be sudo)')
# Add the BPF if it's specified
if self.bpf:
self.pcap.setfilter(self.bpf)
print('listening on %s: %s' % (self.iface_name, self.bpf))
# For each packet in the pcap process the contents
_packets = 0
while True:
# Grab the next header and packet buffer
header, raw_buf = self.pcap.next()
# If we don't get a packet header break out of the loop
if not header:
break;
# Extract the timestamp from the header and yield the packet
seconds, micro_sec = header.getts()
timestamp = seconds + micro_sec * 10**-6
yield {'timestamp': timestamp, 'raw_buf': raw_buf, 'packet_num': _packets}
_packets += 1
# Is there a max packets set if so break on it
if self.max_packets and _packets >= self.max_packets:
break
# All done so report and raise a StopIteration
try:
print('Packet stats: %d received, %d dropped, %d dropped by interface' % self.pcap.stats())
except pcapy.PcapError:
print('No stats available...')
raise StopIteration | python | def read_interface(self):
"""Read Packets from the packet capture interface"""
# Spin up the packet capture
if self._iface_is_file():
self.pcap = pcapy.open_offline(self.iface_name)
else:
try:
# self.pcap = pcap.pcap(name=self.iface_name, promisc=True, immediate=True)
# snaplen (maximum number of bytes to capture _per_packet_)
# promiscious mode (1 for true)
# timeout (in milliseconds)
self.pcap = pcapy.open_live(self.iface_name, 65536 , 1 , 0)
except OSError:
try:
logger.warning('Could not get promisc mode, turning flag off')
self.pcap = pcapy.open_live(self.iface_name, 65536 , 0 , 0)
except OSError:
log_utils.panic('Could no open interface with any options (may need to be sudo)')
# Add the BPF if it's specified
if self.bpf:
self.pcap.setfilter(self.bpf)
print('listening on %s: %s' % (self.iface_name, self.bpf))
# For each packet in the pcap process the contents
_packets = 0
while True:
# Grab the next header and packet buffer
header, raw_buf = self.pcap.next()
# If we don't get a packet header break out of the loop
if not header:
break;
# Extract the timestamp from the header and yield the packet
seconds, micro_sec = header.getts()
timestamp = seconds + micro_sec * 10**-6
yield {'timestamp': timestamp, 'raw_buf': raw_buf, 'packet_num': _packets}
_packets += 1
# Is there a max packets set if so break on it
if self.max_packets and _packets >= self.max_packets:
break
# All done so report and raise a StopIteration
try:
print('Packet stats: %d received, %d dropped, %d dropped by interface' % self.pcap.stats())
except pcapy.PcapError:
print('No stats available...')
raise StopIteration | [
"def",
"read_interface",
"(",
"self",
")",
":",
"# Spin up the packet capture",
"if",
"self",
".",
"_iface_is_file",
"(",
")",
":",
"self",
".",
"pcap",
"=",
"pcapy",
".",
"open_offline",
"(",
"self",
".",
"iface_name",
")",
"else",
":",
"try",
":",
"# sel... | Read Packets from the packet capture interface | [
"Read",
"Packets",
"from",
"the",
"packet",
"capture",
"interface"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/sources/packet_streamer.py#L64-L114 | train | 48,331 |
ajenhl/tacl | tacl/__main__.py | generate_parser | def generate_parser():
"""Returns a parser configured with sub-commands and arguments."""
parser = argparse.ArgumentParser(
description=constants.TACL_DESCRIPTION,
formatter_class=ParagraphFormatter)
subparsers = parser.add_subparsers(title='subcommands')
generate_align_subparser(subparsers)
generate_catalogue_subparser(subparsers)
generate_counts_subparser(subparsers)
generate_diff_subparser(subparsers)
generate_excise_subparser(subparsers)
generate_highlight_subparser(subparsers)
generate_intersect_subparser(subparsers)
generate_lifetime_subparser(subparsers)
generate_ngrams_subparser(subparsers)
generate_prepare_subparser(subparsers)
generate_results_subparser(subparsers)
generate_supplied_diff_subparser(subparsers)
generate_search_subparser(subparsers)
generate_supplied_intersect_subparser(subparsers)
generate_statistics_subparser(subparsers)
generate_strip_subparser(subparsers)
return parser | python | def generate_parser():
"""Returns a parser configured with sub-commands and arguments."""
parser = argparse.ArgumentParser(
description=constants.TACL_DESCRIPTION,
formatter_class=ParagraphFormatter)
subparsers = parser.add_subparsers(title='subcommands')
generate_align_subparser(subparsers)
generate_catalogue_subparser(subparsers)
generate_counts_subparser(subparsers)
generate_diff_subparser(subparsers)
generate_excise_subparser(subparsers)
generate_highlight_subparser(subparsers)
generate_intersect_subparser(subparsers)
generate_lifetime_subparser(subparsers)
generate_ngrams_subparser(subparsers)
generate_prepare_subparser(subparsers)
generate_results_subparser(subparsers)
generate_supplied_diff_subparser(subparsers)
generate_search_subparser(subparsers)
generate_supplied_intersect_subparser(subparsers)
generate_statistics_subparser(subparsers)
generate_strip_subparser(subparsers)
return parser | [
"def",
"generate_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"constants",
".",
"TACL_DESCRIPTION",
",",
"formatter_class",
"=",
"ParagraphFormatter",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(... | Returns a parser configured with sub-commands and arguments. | [
"Returns",
"a",
"parser",
"configured",
"with",
"sub",
"-",
"commands",
"and",
"arguments",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L73-L95 | train | 48,332 |
ajenhl/tacl | tacl/__main__.py | generate_align_subparser | def generate_align_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate aligned
sequences from a set of results."""
parser = subparsers.add_parser(
'align', description=constants.ALIGN_DESCRIPTION,
epilog=constants.ALIGN_EPILOG,
formatter_class=ParagraphFormatter, help=constants.ALIGN_HELP)
parser.set_defaults(func=align_results)
utils.add_common_arguments(parser)
parser.add_argument('-m', '--minimum', default=20,
help=constants.ALIGN_MINIMUM_SIZE_HELP, type=int)
utils.add_corpus_arguments(parser)
parser.add_argument('output', help=constants.ALIGN_OUTPUT_HELP,
metavar='OUTPUT')
parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP,
metavar='RESULTS') | python | def generate_align_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate aligned
sequences from a set of results."""
parser = subparsers.add_parser(
'align', description=constants.ALIGN_DESCRIPTION,
epilog=constants.ALIGN_EPILOG,
formatter_class=ParagraphFormatter, help=constants.ALIGN_HELP)
parser.set_defaults(func=align_results)
utils.add_common_arguments(parser)
parser.add_argument('-m', '--minimum', default=20,
help=constants.ALIGN_MINIMUM_SIZE_HELP, type=int)
utils.add_corpus_arguments(parser)
parser.add_argument('output', help=constants.ALIGN_OUTPUT_HELP,
metavar='OUTPUT')
parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP,
metavar='RESULTS') | [
"def",
"generate_align_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'align'",
",",
"description",
"=",
"constants",
".",
"ALIGN_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"ALIGN_EPILOG",
",",
"formatter_cl... | Adds a sub-command parser to `subparsers` to generate aligned
sequences from a set of results. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"generate",
"aligned",
"sequences",
"from",
"a",
"set",
"of",
"results",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L98-L113 | train | 48,333 |
ajenhl/tacl | tacl/__main__.py | generate_catalogue | def generate_catalogue(args, parser):
"""Generates and saves a catalogue file."""
catalogue = tacl.Catalogue()
catalogue.generate(args.corpus, args.label)
catalogue.save(args.catalogue) | python | def generate_catalogue(args, parser):
"""Generates and saves a catalogue file."""
catalogue = tacl.Catalogue()
catalogue.generate(args.corpus, args.label)
catalogue.save(args.catalogue) | [
"def",
"generate_catalogue",
"(",
"args",
",",
"parser",
")",
":",
"catalogue",
"=",
"tacl",
".",
"Catalogue",
"(",
")",
"catalogue",
".",
"generate",
"(",
"args",
".",
"corpus",
",",
"args",
".",
"label",
")",
"catalogue",
".",
"save",
"(",
"args",
".... | Generates and saves a catalogue file. | [
"Generates",
"and",
"saves",
"a",
"catalogue",
"file",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L116-L120 | train | 48,334 |
ajenhl/tacl | tacl/__main__.py | generate_catalogue_subparser | def generate_catalogue_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate and save
a catalogue file."""
parser = subparsers.add_parser(
'catalogue', description=constants.CATALOGUE_DESCRIPTION,
epilog=constants.CATALOGUE_EPILOG,
formatter_class=ParagraphFormatter, help=constants.CATALOGUE_HELP)
utils.add_common_arguments(parser)
parser.set_defaults(func=generate_catalogue)
parser.add_argument('corpus', help=constants.DB_CORPUS_HELP,
metavar='CORPUS')
utils.add_query_arguments(parser)
parser.add_argument('-l', '--label', default='',
help=constants.CATALOGUE_LABEL_HELP) | python | def generate_catalogue_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate and save
a catalogue file."""
parser = subparsers.add_parser(
'catalogue', description=constants.CATALOGUE_DESCRIPTION,
epilog=constants.CATALOGUE_EPILOG,
formatter_class=ParagraphFormatter, help=constants.CATALOGUE_HELP)
utils.add_common_arguments(parser)
parser.set_defaults(func=generate_catalogue)
parser.add_argument('corpus', help=constants.DB_CORPUS_HELP,
metavar='CORPUS')
utils.add_query_arguments(parser)
parser.add_argument('-l', '--label', default='',
help=constants.CATALOGUE_LABEL_HELP) | [
"def",
"generate_catalogue_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'catalogue'",
",",
"description",
"=",
"constants",
".",
"CATALOGUE_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"CATALOGUE_EPILOG",
",",... | Adds a sub-command parser to `subparsers` to generate and save
a catalogue file. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"generate",
"and",
"save",
"a",
"catalogue",
"file",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L123-L136 | train | 48,335 |
ajenhl/tacl | tacl/__main__.py | generate_counts_subparser | def generate_counts_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a counts
query."""
parser = subparsers.add_parser(
'counts', description=constants.COUNTS_DESCRIPTION,
epilog=constants.COUNTS_EPILOG, formatter_class=ParagraphFormatter,
help=constants.COUNTS_HELP)
parser.set_defaults(func=ngram_counts)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser) | python | def generate_counts_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a counts
query."""
parser = subparsers.add_parser(
'counts', description=constants.COUNTS_DESCRIPTION,
epilog=constants.COUNTS_EPILOG, formatter_class=ParagraphFormatter,
help=constants.COUNTS_HELP)
parser.set_defaults(func=ngram_counts)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser) | [
"def",
"generate_counts_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'counts'",
",",
"description",
"=",
"constants",
".",
"COUNTS_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"COUNTS_EPILOG",
",",
"formatte... | Adds a sub-command parser to `subparsers` to make a counts
query. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"make",
"a",
"counts",
"query",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L139-L150 | train | 48,336 |
ajenhl/tacl | tacl/__main__.py | generate_diff_subparser | def generate_diff_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a diff
query."""
parser = subparsers.add_parser(
'diff', description=constants.DIFF_DESCRIPTION,
epilog=constants.DIFF_EPILOG, formatter_class=ParagraphFormatter,
help=constants.DIFF_HELP)
parser.set_defaults(func=ngram_diff)
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--asymmetric', help=constants.ASYMMETRIC_HELP,
metavar='LABEL')
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser) | python | def generate_diff_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a diff
query."""
parser = subparsers.add_parser(
'diff', description=constants.DIFF_DESCRIPTION,
epilog=constants.DIFF_EPILOG, formatter_class=ParagraphFormatter,
help=constants.DIFF_HELP)
parser.set_defaults(func=ngram_diff)
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--asymmetric', help=constants.ASYMMETRIC_HELP,
metavar='LABEL')
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser) | [
"def",
"generate_diff_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'diff'",
",",
"description",
"=",
"constants",
".",
"DIFF_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"DIFF_EPILOG",
",",
"formatter_class"... | Adds a sub-command parser to `subparsers` to make a diff
query. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"make",
"a",
"diff",
"query",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L153-L167 | train | 48,337 |
ajenhl/tacl | tacl/__main__.py | generate_excise_subparser | def generate_excise_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to excise n-grams from
witnesses."""
parser = subparsers.add_parser(
'excise', description=constants.EXCISE_DESCRIPTION,
help=constants.EXCISE_HELP)
parser.set_defaults(func=excise)
utils.add_common_arguments(parser)
parser.add_argument('ngrams', metavar='NGRAMS',
help=constants.EXCISE_NGRAMS_HELP)
parser.add_argument('replacement', metavar='REPLACEMENT',
help=constants.EXCISE_REPLACEMENT_HELP)
parser.add_argument('output', metavar='OUTPUT',
help=constants.EXCISE_OUTPUT_HELP)
utils.add_corpus_arguments(parser)
parser.add_argument('works', metavar='WORK',
help=constants.EXCISE_WORKS_HELP, nargs='+') | python | def generate_excise_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to excise n-grams from
witnesses."""
parser = subparsers.add_parser(
'excise', description=constants.EXCISE_DESCRIPTION,
help=constants.EXCISE_HELP)
parser.set_defaults(func=excise)
utils.add_common_arguments(parser)
parser.add_argument('ngrams', metavar='NGRAMS',
help=constants.EXCISE_NGRAMS_HELP)
parser.add_argument('replacement', metavar='REPLACEMENT',
help=constants.EXCISE_REPLACEMENT_HELP)
parser.add_argument('output', metavar='OUTPUT',
help=constants.EXCISE_OUTPUT_HELP)
utils.add_corpus_arguments(parser)
parser.add_argument('works', metavar='WORK',
help=constants.EXCISE_WORKS_HELP, nargs='+') | [
"def",
"generate_excise_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'excise'",
",",
"description",
"=",
"constants",
".",
"EXCISE_DESCRIPTION",
",",
"help",
"=",
"constants",
".",
"EXCISE_HELP",
")",
"parser",
"... | Adds a sub-command parser to `subparsers` to excise n-grams from
witnesses. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"excise",
"n",
"-",
"grams",
"from",
"witnesses",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L170-L186 | train | 48,338 |
ajenhl/tacl | tacl/__main__.py | generate_highlight_subparser | def generate_highlight_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to highlight a witness'
text with its matches in a result."""
parser = subparsers.add_parser(
'highlight', description=constants.HIGHLIGHT_DESCRIPTION,
epilog=constants.HIGHLIGHT_EPILOG, formatter_class=ParagraphFormatter,
help=constants.HIGHLIGHT_HELP)
parser.set_defaults(func=highlight_text)
utils.add_common_arguments(parser)
parser.add_argument('-m', '--minus-ngrams', metavar='NGRAMS',
help=constants.HIGHLIGHT_MINUS_NGRAMS_HELP)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-n', '--ngrams', action='append', metavar='NGRAMS',
help=constants.HIGHLIGHT_NGRAMS_HELP)
group.add_argument('-r', '--results', metavar='RESULTS',
help=constants.HIGHLIGHT_RESULTS_HELP)
parser.add_argument('-l', '--label', action='append', metavar='LABEL',
help=constants.HIGHLIGHT_LABEL_HELP)
utils.add_corpus_arguments(parser)
parser.add_argument('base_name', help=constants.HIGHLIGHT_BASE_NAME_HELP,
metavar='BASE_NAME')
parser.add_argument('output', metavar='OUTPUT',
help=constants.REPORT_OUTPUT_HELP) | python | def generate_highlight_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to highlight a witness'
text with its matches in a result."""
parser = subparsers.add_parser(
'highlight', description=constants.HIGHLIGHT_DESCRIPTION,
epilog=constants.HIGHLIGHT_EPILOG, formatter_class=ParagraphFormatter,
help=constants.HIGHLIGHT_HELP)
parser.set_defaults(func=highlight_text)
utils.add_common_arguments(parser)
parser.add_argument('-m', '--minus-ngrams', metavar='NGRAMS',
help=constants.HIGHLIGHT_MINUS_NGRAMS_HELP)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-n', '--ngrams', action='append', metavar='NGRAMS',
help=constants.HIGHLIGHT_NGRAMS_HELP)
group.add_argument('-r', '--results', metavar='RESULTS',
help=constants.HIGHLIGHT_RESULTS_HELP)
parser.add_argument('-l', '--label', action='append', metavar='LABEL',
help=constants.HIGHLIGHT_LABEL_HELP)
utils.add_corpus_arguments(parser)
parser.add_argument('base_name', help=constants.HIGHLIGHT_BASE_NAME_HELP,
metavar='BASE_NAME')
parser.add_argument('output', metavar='OUTPUT',
help=constants.REPORT_OUTPUT_HELP) | [
"def",
"generate_highlight_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'highlight'",
",",
"description",
"=",
"constants",
".",
"HIGHLIGHT_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"HIGHLIGHT_EPILOG",
",",... | Adds a sub-command parser to `subparsers` to highlight a witness'
text with its matches in a result. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"highlight",
"a",
"witness",
"text",
"with",
"its",
"matches",
"in",
"a",
"result",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L189-L211 | train | 48,339 |
ajenhl/tacl | tacl/__main__.py | generate_intersect_subparser | def generate_intersect_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make an
intersection query."""
parser = subparsers.add_parser(
'intersect', description=constants.INTERSECT_DESCRIPTION,
epilog=constants.INTERSECT_EPILOG, formatter_class=ParagraphFormatter,
help=constants.INTERSECT_HELP)
parser.set_defaults(func=ngram_intersection)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser) | python | def generate_intersect_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make an
intersection query."""
parser = subparsers.add_parser(
'intersect', description=constants.INTERSECT_DESCRIPTION,
epilog=constants.INTERSECT_EPILOG, formatter_class=ParagraphFormatter,
help=constants.INTERSECT_HELP)
parser.set_defaults(func=ngram_intersection)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser) | [
"def",
"generate_intersect_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'intersect'",
",",
"description",
"=",
"constants",
".",
"INTERSECT_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"INTERSECT_EPILOG",
",",... | Adds a sub-command parser to `subparsers` to make an
intersection query. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"make",
"an",
"intersection",
"query",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L214-L225 | train | 48,340 |
ajenhl/tacl | tacl/__main__.py | generate_lifetime_subparser | def generate_lifetime_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a lifetime report."""
parser = subparsers.add_parser(
'lifetime', description=constants.LIFETIME_DESCRIPTION,
epilog=constants.LIFETIME_EPILOG, formatter_class=ParagraphFormatter,
help=constants.LIFETIME_HELP)
parser.set_defaults(func=lifetime_report)
utils.add_tokenizer_argument(parser)
utils.add_common_arguments(parser)
utils.add_query_arguments(parser)
parser.add_argument('results', help=constants.LIFETIME_RESULTS_HELP,
metavar='RESULTS')
parser.add_argument('label', help=constants.LIFETIME_LABEL_HELP,
metavar='LABEL')
parser.add_argument('output', help=constants.REPORT_OUTPUT_HELP,
metavar='OUTPUT') | python | def generate_lifetime_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to make a lifetime report."""
parser = subparsers.add_parser(
'lifetime', description=constants.LIFETIME_DESCRIPTION,
epilog=constants.LIFETIME_EPILOG, formatter_class=ParagraphFormatter,
help=constants.LIFETIME_HELP)
parser.set_defaults(func=lifetime_report)
utils.add_tokenizer_argument(parser)
utils.add_common_arguments(parser)
utils.add_query_arguments(parser)
parser.add_argument('results', help=constants.LIFETIME_RESULTS_HELP,
metavar='RESULTS')
parser.add_argument('label', help=constants.LIFETIME_LABEL_HELP,
metavar='LABEL')
parser.add_argument('output', help=constants.REPORT_OUTPUT_HELP,
metavar='OUTPUT') | [
"def",
"generate_lifetime_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'lifetime'",
",",
"description",
"=",
"constants",
".",
"LIFETIME_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"LIFETIME_EPILOG",
",",
"... | Adds a sub-command parser to `subparsers` to make a lifetime report. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"make",
"a",
"lifetime",
"report",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L228-L243 | train | 48,341 |
ajenhl/tacl | tacl/__main__.py | generate_ngrams | def generate_ngrams(args, parser):
"""Adds n-grams data to the data store."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
if args.catalogue:
catalogue = utils.get_catalogue(args)
else:
catalogue = None
store.add_ngrams(corpus, args.min_size, args.max_size, catalogue) | python | def generate_ngrams(args, parser):
"""Adds n-grams data to the data store."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
if args.catalogue:
catalogue = utils.get_catalogue(args)
else:
catalogue = None
store.add_ngrams(corpus, args.min_size, args.max_size, catalogue) | [
"def",
"generate_ngrams",
"(",
"args",
",",
"parser",
")",
":",
"store",
"=",
"utils",
".",
"get_data_store",
"(",
"args",
")",
"corpus",
"=",
"utils",
".",
"get_corpus",
"(",
"args",
")",
"if",
"args",
".",
"catalogue",
":",
"catalogue",
"=",
"utils",
... | Adds n-grams data to the data store. | [
"Adds",
"n",
"-",
"grams",
"data",
"to",
"the",
"data",
"store",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L246-L254 | train | 48,342 |
ajenhl/tacl | tacl/__main__.py | generate_ngrams_subparser | def generate_ngrams_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to add n-grams data
to the data store."""
parser = subparsers.add_parser(
'ngrams', description=constants.NGRAMS_DESCRIPTION,
epilog=constants.NGRAMS_EPILOG, formatter_class=ParagraphFormatter,
help=constants.NGRAMS_HELP)
parser.set_defaults(func=generate_ngrams)
utils.add_common_arguments(parser)
parser.add_argument('-c', '--catalogue', dest='catalogue',
help=constants.NGRAMS_CATALOGUE_HELP,
metavar='CATALOGUE')
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
parser.add_argument('min_size', help=constants.NGRAMS_MINIMUM_HELP,
metavar='MINIMUM', type=int)
parser.add_argument('max_size', help=constants.NGRAMS_MAXIMUM_HELP,
metavar='MAXIMUM', type=int) | python | def generate_ngrams_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to add n-grams data
to the data store."""
parser = subparsers.add_parser(
'ngrams', description=constants.NGRAMS_DESCRIPTION,
epilog=constants.NGRAMS_EPILOG, formatter_class=ParagraphFormatter,
help=constants.NGRAMS_HELP)
parser.set_defaults(func=generate_ngrams)
utils.add_common_arguments(parser)
parser.add_argument('-c', '--catalogue', dest='catalogue',
help=constants.NGRAMS_CATALOGUE_HELP,
metavar='CATALOGUE')
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
parser.add_argument('min_size', help=constants.NGRAMS_MINIMUM_HELP,
metavar='MINIMUM', type=int)
parser.add_argument('max_size', help=constants.NGRAMS_MAXIMUM_HELP,
metavar='MAXIMUM', type=int) | [
"def",
"generate_ngrams_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'ngrams'",
",",
"description",
"=",
"constants",
".",
"NGRAMS_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"NGRAMS_EPILOG",
",",
"formatte... | Adds a sub-command parser to `subparsers` to add n-grams data
to the data store. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"add",
"n",
"-",
"grams",
"data",
"to",
"the",
"data",
"store",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L257-L274 | train | 48,343 |
ajenhl/tacl | tacl/__main__.py | generate_prepare_subparser | def generate_prepare_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to prepare source XML
files for stripping."""
parser = subparsers.add_parser(
'prepare', description=constants.PREPARE_DESCRIPTION,
epilog=constants.PREPARE_EPILOG, formatter_class=ParagraphFormatter,
help=constants.PREPARE_HELP)
parser.set_defaults(func=prepare_xml)
utils.add_common_arguments(parser)
parser.add_argument('-s', '--source', dest='source',
choices=constants.TEI_SOURCE_CHOICES,
default=constants.TEI_SOURCE_CBETA_GITHUB,
help=constants.PREPARE_SOURCE_HELP,
metavar='SOURCE')
parser.add_argument('input', help=constants.PREPARE_INPUT_HELP,
metavar='INPUT')
parser.add_argument('output', help=constants.PREPARE_OUTPUT_HELP,
metavar='OUTPUT') | python | def generate_prepare_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to prepare source XML
files for stripping."""
parser = subparsers.add_parser(
'prepare', description=constants.PREPARE_DESCRIPTION,
epilog=constants.PREPARE_EPILOG, formatter_class=ParagraphFormatter,
help=constants.PREPARE_HELP)
parser.set_defaults(func=prepare_xml)
utils.add_common_arguments(parser)
parser.add_argument('-s', '--source', dest='source',
choices=constants.TEI_SOURCE_CHOICES,
default=constants.TEI_SOURCE_CBETA_GITHUB,
help=constants.PREPARE_SOURCE_HELP,
metavar='SOURCE')
parser.add_argument('input', help=constants.PREPARE_INPUT_HELP,
metavar='INPUT')
parser.add_argument('output', help=constants.PREPARE_OUTPUT_HELP,
metavar='OUTPUT') | [
"def",
"generate_prepare_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'prepare'",
",",
"description",
"=",
"constants",
".",
"PREPARE_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"PREPARE_EPILOG",
",",
"form... | Adds a sub-command parser to `subparsers` to prepare source XML
files for stripping. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"prepare",
"source",
"XML",
"files",
"for",
"stripping",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L277-L294 | train | 48,344 |
ajenhl/tacl | tacl/__main__.py | generate_search_subparser | def generate_search_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate search
results for a set of n-grams."""
parser = subparsers.add_parser(
'search', description=constants.SEARCH_DESCRIPTION,
epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter,
help=constants.SEARCH_HELP)
parser.set_defaults(func=search_texts)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser)
parser.add_argument('ngrams', help=constants.SEARCH_NGRAMS_HELP,
nargs='*', metavar='NGRAMS') | python | def generate_search_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate search
results for a set of n-grams."""
parser = subparsers.add_parser(
'search', description=constants.SEARCH_DESCRIPTION,
epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter,
help=constants.SEARCH_HELP)
parser.set_defaults(func=search_texts)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser)
utils.add_corpus_arguments(parser)
utils.add_query_arguments(parser)
parser.add_argument('ngrams', help=constants.SEARCH_NGRAMS_HELP,
nargs='*', metavar='NGRAMS') | [
"def",
"generate_search_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'search'",
",",
"description",
"=",
"constants",
".",
"SEARCH_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"SEARCH_EPILOG",
",",
"formatte... | Adds a sub-command parser to `subparsers` to generate search
results for a set of n-grams. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"generate",
"search",
"results",
"for",
"a",
"set",
"of",
"n",
"-",
"grams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L377-L390 | train | 48,345 |
ajenhl/tacl | tacl/__main__.py | generate_statistics_subparser | def generate_statistics_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate statistics
from a set of results."""
parser = subparsers.add_parser(
'stats', description=constants.STATISTICS_DESCRIPTION,
formatter_class=ParagraphFormatter, help=constants.STATISTICS_HELP)
parser.set_defaults(func=generate_statistics)
utils.add_common_arguments(parser)
utils.add_corpus_arguments(parser)
parser.add_argument('results', help=constants.STATISTICS_RESULTS_HELP,
metavar='RESULTS') | python | def generate_statistics_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate statistics
from a set of results."""
parser = subparsers.add_parser(
'stats', description=constants.STATISTICS_DESCRIPTION,
formatter_class=ParagraphFormatter, help=constants.STATISTICS_HELP)
parser.set_defaults(func=generate_statistics)
utils.add_common_arguments(parser)
utils.add_corpus_arguments(parser)
parser.add_argument('results', help=constants.STATISTICS_RESULTS_HELP,
metavar='RESULTS') | [
"def",
"generate_statistics_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'stats'",
",",
"description",
"=",
"constants",
".",
"STATISTICS_DESCRIPTION",
",",
"formatter_class",
"=",
"ParagraphFormatter",
",",
"help",
... | Adds a sub-command parser to `subparsers` to generate statistics
from a set of results. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"generate",
"statistics",
"from",
"a",
"set",
"of",
"results",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L401-L411 | train | 48,346 |
ajenhl/tacl | tacl/__main__.py | generate_strip_subparser | def generate_strip_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to process prepared files
for use with the tacl ngrams command."""
parser = subparsers.add_parser(
'strip', description=constants.STRIP_DESCRIPTION,
epilog=constants.STRIP_EPILOG, formatter_class=ParagraphFormatter,
help=constants.STRIP_HELP)
parser.set_defaults(func=strip_files)
utils.add_common_arguments(parser)
parser.add_argument('input', help=constants.STRIP_INPUT_HELP,
metavar='INPUT')
parser.add_argument('output', help=constants.STRIP_OUTPUT_HELP,
metavar='OUTPUT') | python | def generate_strip_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to process prepared files
for use with the tacl ngrams command."""
parser = subparsers.add_parser(
'strip', description=constants.STRIP_DESCRIPTION,
epilog=constants.STRIP_EPILOG, formatter_class=ParagraphFormatter,
help=constants.STRIP_HELP)
parser.set_defaults(func=strip_files)
utils.add_common_arguments(parser)
parser.add_argument('input', help=constants.STRIP_INPUT_HELP,
metavar='INPUT')
parser.add_argument('output', help=constants.STRIP_OUTPUT_HELP,
metavar='OUTPUT') | [
"def",
"generate_strip_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'strip'",
",",
"description",
"=",
"constants",
".",
"STRIP_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"STRIP_EPILOG",
",",
"formatter_cl... | Adds a sub-command parser to `subparsers` to process prepared files
for use with the tacl ngrams command. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"process",
"prepared",
"files",
"for",
"use",
"with",
"the",
"tacl",
"ngrams",
"command",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L414-L426 | train | 48,347 |
ajenhl/tacl | tacl/__main__.py | generate_supplied_diff_subparser | def generate_supplied_diff_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to run a diff query using
the supplied results sets."""
parser = subparsers.add_parser(
'sdiff', description=constants.SUPPLIED_DIFF_DESCRIPTION,
epilog=constants.SUPPLIED_DIFF_EPILOG,
formatter_class=ParagraphFormatter, help=constants.SUPPLIED_DIFF_HELP)
parser.set_defaults(func=supplied_diff)
utils.add_common_arguments(parser)
utils.add_tokenizer_argument(parser)
utils.add_db_arguments(parser, True)
utils.add_supplied_query_arguments(parser) | python | def generate_supplied_diff_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to run a diff query using
the supplied results sets."""
parser = subparsers.add_parser(
'sdiff', description=constants.SUPPLIED_DIFF_DESCRIPTION,
epilog=constants.SUPPLIED_DIFF_EPILOG,
formatter_class=ParagraphFormatter, help=constants.SUPPLIED_DIFF_HELP)
parser.set_defaults(func=supplied_diff)
utils.add_common_arguments(parser)
utils.add_tokenizer_argument(parser)
utils.add_db_arguments(parser, True)
utils.add_supplied_query_arguments(parser) | [
"def",
"generate_supplied_diff_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'sdiff'",
",",
"description",
"=",
"constants",
".",
"SUPPLIED_DIFF_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"SUPPLIED_DIFF_EPILOG"... | Adds a sub-command parser to `subparsers` to run a diff query using
the supplied results sets. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"run",
"a",
"diff",
"query",
"using",
"the",
"supplied",
"results",
"sets",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L429-L440 | train | 48,348 |
ajenhl/tacl | tacl/__main__.py | generate_supplied_intersect_subparser | def generate_supplied_intersect_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to run an intersect query
using the supplied results sets."""
parser = subparsers.add_parser(
'sintersect', description=constants.SUPPLIED_INTERSECT_DESCRIPTION,
epilog=constants.SUPPLIED_INTERSECT_EPILOG,
formatter_class=ParagraphFormatter,
help=constants.SUPPLIED_INTERSECT_HELP)
parser.set_defaults(func=supplied_intersect)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser, True)
utils.add_supplied_query_arguments(parser) | python | def generate_supplied_intersect_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to run an intersect query
using the supplied results sets."""
parser = subparsers.add_parser(
'sintersect', description=constants.SUPPLIED_INTERSECT_DESCRIPTION,
epilog=constants.SUPPLIED_INTERSECT_EPILOG,
formatter_class=ParagraphFormatter,
help=constants.SUPPLIED_INTERSECT_HELP)
parser.set_defaults(func=supplied_intersect)
utils.add_common_arguments(parser)
utils.add_db_arguments(parser, True)
utils.add_supplied_query_arguments(parser) | [
"def",
"generate_supplied_intersect_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'sintersect'",
",",
"description",
"=",
"constants",
".",
"SUPPLIED_INTERSECT_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"SUPPLI... | Adds a sub-command parser to `subparsers` to run an intersect query
using the supplied results sets. | [
"Adds",
"a",
"sub",
"-",
"command",
"parser",
"to",
"subparsers",
"to",
"run",
"an",
"intersect",
"query",
"using",
"the",
"supplied",
"results",
"sets",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L443-L454 | train | 48,349 |
ajenhl/tacl | tacl/__main__.py | highlight_text | def highlight_text(args, parser):
"""Outputs the result of highlighting a text."""
tokenizer = utils.get_tokenizer(args)
corpus = utils.get_corpus(args)
output_dir = os.path.abspath(args.output)
if os.path.exists(output_dir):
parser.exit(status=3, message='Output directory already exists, '
'aborting.\n')
os.makedirs(output_dir, exist_ok=True)
if args.ngrams:
if args.label is None or len(args.label) != len(args.ngrams):
parser.error('There must be as many labels as there are files '
'of n-grams')
report = tacl.NgramHighlightReport(corpus, tokenizer)
ngrams = []
for ngram_file in args.ngrams:
ngrams.append(utils.get_ngrams(ngram_file))
minus_ngrams = []
if args.minus_ngrams:
minus_ngrams = utils.get_ngrams(args.minus_ngrams)
report.generate(args.output, args.base_name, ngrams, args.label,
minus_ngrams)
else:
report = tacl.ResultsHighlightReport(corpus, tokenizer)
report.generate(args.output, args.base_name, args.results) | python | def highlight_text(args, parser):
"""Outputs the result of highlighting a text."""
tokenizer = utils.get_tokenizer(args)
corpus = utils.get_corpus(args)
output_dir = os.path.abspath(args.output)
if os.path.exists(output_dir):
parser.exit(status=3, message='Output directory already exists, '
'aborting.\n')
os.makedirs(output_dir, exist_ok=True)
if args.ngrams:
if args.label is None or len(args.label) != len(args.ngrams):
parser.error('There must be as many labels as there are files '
'of n-grams')
report = tacl.NgramHighlightReport(corpus, tokenizer)
ngrams = []
for ngram_file in args.ngrams:
ngrams.append(utils.get_ngrams(ngram_file))
minus_ngrams = []
if args.minus_ngrams:
minus_ngrams = utils.get_ngrams(args.minus_ngrams)
report.generate(args.output, args.base_name, ngrams, args.label,
minus_ngrams)
else:
report = tacl.ResultsHighlightReport(corpus, tokenizer)
report.generate(args.output, args.base_name, args.results) | [
"def",
"highlight_text",
"(",
"args",
",",
"parser",
")",
":",
"tokenizer",
"=",
"utils",
".",
"get_tokenizer",
"(",
"args",
")",
"corpus",
"=",
"utils",
".",
"get_corpus",
"(",
"args",
")",
"output_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"a... | Outputs the result of highlighting a text. | [
"Outputs",
"the",
"result",
"of",
"highlighting",
"a",
"text",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L457-L481 | train | 48,350 |
ajenhl/tacl | tacl/__main__.py | lifetime_report | def lifetime_report(args, parser):
"""Generates a lifetime report."""
catalogue = utils.get_catalogue(args)
tokenizer = utils.get_tokenizer(args)
results = tacl.Results(args.results, tokenizer)
output_dir = os.path.abspath(args.output)
os.makedirs(output_dir, exist_ok=True)
report = tacl.LifetimeReport()
report.generate(output_dir, catalogue, results, args.label) | python | def lifetime_report(args, parser):
"""Generates a lifetime report."""
catalogue = utils.get_catalogue(args)
tokenizer = utils.get_tokenizer(args)
results = tacl.Results(args.results, tokenizer)
output_dir = os.path.abspath(args.output)
os.makedirs(output_dir, exist_ok=True)
report = tacl.LifetimeReport()
report.generate(output_dir, catalogue, results, args.label) | [
"def",
"lifetime_report",
"(",
"args",
",",
"parser",
")",
":",
"catalogue",
"=",
"utils",
".",
"get_catalogue",
"(",
"args",
")",
"tokenizer",
"=",
"utils",
".",
"get_tokenizer",
"(",
"args",
")",
"results",
"=",
"tacl",
".",
"Results",
"(",
"args",
"."... | Generates a lifetime report. | [
"Generates",
"a",
"lifetime",
"report",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L484-L492 | train | 48,351 |
ajenhl/tacl | tacl/__main__.py | ngram_counts | def ngram_counts(args, parser):
"""Outputs the results of performing a counts query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
store.counts(catalogue, sys.stdout) | python | def ngram_counts(args, parser):
"""Outputs the results of performing a counts query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
store.counts(catalogue, sys.stdout) | [
"def",
"ngram_counts",
"(",
"args",
",",
"parser",
")",
":",
"store",
"=",
"utils",
".",
"get_data_store",
"(",
"args",
")",
"corpus",
"=",
"utils",
".",
"get_corpus",
"(",
"args",
")",
"catalogue",
"=",
"utils",
".",
"get_catalogue",
"(",
"args",
")",
... | Outputs the results of performing a counts query. | [
"Outputs",
"the",
"results",
"of",
"performing",
"a",
"counts",
"query",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L495-L501 | train | 48,352 |
ajenhl/tacl | tacl/__main__.py | ngram_diff | def ngram_diff(args, parser):
"""Outputs the results of performing a diff query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
tokenizer = utils.get_tokenizer(args)
store.validate(corpus, catalogue)
if args.asymmetric:
store.diff_asymmetric(catalogue, args.asymmetric, tokenizer,
sys.stdout)
else:
store.diff(catalogue, tokenizer, sys.stdout) | python | def ngram_diff(args, parser):
"""Outputs the results of performing a diff query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
tokenizer = utils.get_tokenizer(args)
store.validate(corpus, catalogue)
if args.asymmetric:
store.diff_asymmetric(catalogue, args.asymmetric, tokenizer,
sys.stdout)
else:
store.diff(catalogue, tokenizer, sys.stdout) | [
"def",
"ngram_diff",
"(",
"args",
",",
"parser",
")",
":",
"store",
"=",
"utils",
".",
"get_data_store",
"(",
"args",
")",
"corpus",
"=",
"utils",
".",
"get_corpus",
"(",
"args",
")",
"catalogue",
"=",
"utils",
".",
"get_catalogue",
"(",
"args",
")",
"... | Outputs the results of performing a diff query. | [
"Outputs",
"the",
"results",
"of",
"performing",
"a",
"diff",
"query",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L504-L515 | train | 48,353 |
ajenhl/tacl | tacl/__main__.py | ngram_intersection | def ngram_intersection(args, parser):
"""Outputs the results of performing an intersection query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
store.intersection(catalogue, sys.stdout) | python | def ngram_intersection(args, parser):
"""Outputs the results of performing an intersection query."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
store.intersection(catalogue, sys.stdout) | [
"def",
"ngram_intersection",
"(",
"args",
",",
"parser",
")",
":",
"store",
"=",
"utils",
".",
"get_data_store",
"(",
"args",
")",
"corpus",
"=",
"utils",
".",
"get_corpus",
"(",
"args",
")",
"catalogue",
"=",
"utils",
".",
"get_catalogue",
"(",
"args",
... | Outputs the results of performing an intersection query. | [
"Outputs",
"the",
"results",
"of",
"performing",
"an",
"intersection",
"query",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L518-L524 | train | 48,354 |
ajenhl/tacl | tacl/__main__.py | prepare_xml | def prepare_xml(args, parser):
"""Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work.
"""
if args.source == constants.TEI_SOURCE_CBETA_GITHUB:
corpus_class = tacl.TEICorpusCBETAGitHub
else:
raise Exception('Unsupported TEI source option provided')
corpus = corpus_class(args.input, args.output)
corpus.tidy() | python | def prepare_xml(args, parser):
"""Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work.
"""
if args.source == constants.TEI_SOURCE_CBETA_GITHUB:
corpus_class = tacl.TEICorpusCBETAGitHub
else:
raise Exception('Unsupported TEI source option provided')
corpus = corpus_class(args.input, args.output)
corpus.tidy() | [
"def",
"prepare_xml",
"(",
"args",
",",
"parser",
")",
":",
"if",
"args",
".",
"source",
"==",
"constants",
".",
"TEI_SOURCE_CBETA_GITHUB",
":",
"corpus_class",
"=",
"tacl",
".",
"TEICorpusCBETAGitHub",
"else",
":",
"raise",
"Exception",
"(",
"'Unsupported TEI s... | Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work. | [
"Prepares",
"XML",
"files",
"for",
"stripping",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L527-L539 | train | 48,355 |
ajenhl/tacl | tacl/__main__.py | search_texts | def search_texts(args, parser):
"""Searches texts for presence of n-grams."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
ngrams = []
for ngram_file in args.ngrams:
ngrams.extend(utils.get_ngrams(ngram_file))
store.search(catalogue, ngrams, sys.stdout) | python | def search_texts(args, parser):
"""Searches texts for presence of n-grams."""
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
store.validate(corpus, catalogue)
ngrams = []
for ngram_file in args.ngrams:
ngrams.extend(utils.get_ngrams(ngram_file))
store.search(catalogue, ngrams, sys.stdout) | [
"def",
"search_texts",
"(",
"args",
",",
"parser",
")",
":",
"store",
"=",
"utils",
".",
"get_data_store",
"(",
"args",
")",
"corpus",
"=",
"utils",
".",
"get_corpus",
"(",
"args",
")",
"catalogue",
"=",
"utils",
".",
"get_catalogue",
"(",
"args",
")",
... | Searches texts for presence of n-grams. | [
"Searches",
"texts",
"for",
"presence",
"of",
"n",
"-",
"grams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L606-L615 | train | 48,356 |
ajenhl/tacl | tacl/__main__.py | strip_files | def strip_files(args, parser):
"""Processes prepared XML files for use with the tacl ngrams
command."""
stripper = tacl.Stripper(args.input, args.output)
stripper.strip_files() | python | def strip_files(args, parser):
"""Processes prepared XML files for use with the tacl ngrams
command."""
stripper = tacl.Stripper(args.input, args.output)
stripper.strip_files() | [
"def",
"strip_files",
"(",
"args",
",",
"parser",
")",
":",
"stripper",
"=",
"tacl",
".",
"Stripper",
"(",
"args",
".",
"input",
",",
"args",
".",
"output",
")",
"stripper",
".",
"strip_files",
"(",
")"
] | Processes prepared XML files for use with the tacl ngrams
command. | [
"Processes",
"prepared",
"XML",
"files",
"for",
"use",
"with",
"the",
"tacl",
"ngrams",
"command",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L618-L622 | train | 48,357 |
SuperCowPowers/chains | chains/links/http_meta.py | HTTPMeta.http_meta_data | def http_meta_data(self):
"""Pull out the application metadata for each flow in the input_stream"""
# For each flow process the contents
for flow in self.input_stream:
# Client to Server
if flow['direction'] == 'CTS':
try:
request = dpkt.http.Request(flow['payload'])
request_data = data_utils.make_dict(request)
request_data['uri'] = self._clean_uri(request['uri'])
flow['http'] = {'type':'HTTP_REQUEST', 'data':request_data}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
flow['http'] = None
# Server to Client
else:
try:
response = dpkt.http.Response(flow['payload'])
flow['http'] = {'type': 'HTTP_RESPONSE', 'data': data_utils.make_dict(response)}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
flow['http'] = None
# Mark non-TCP HTTP
if flow['http'] and flow['protocol'] != 'TCP':
flow['http'].update({'weird': 'UDP-HTTP'})
# All done
yield flow | python | def http_meta_data(self):
"""Pull out the application metadata for each flow in the input_stream"""
# For each flow process the contents
for flow in self.input_stream:
# Client to Server
if flow['direction'] == 'CTS':
try:
request = dpkt.http.Request(flow['payload'])
request_data = data_utils.make_dict(request)
request_data['uri'] = self._clean_uri(request['uri'])
flow['http'] = {'type':'HTTP_REQUEST', 'data':request_data}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
flow['http'] = None
# Server to Client
else:
try:
response = dpkt.http.Response(flow['payload'])
flow['http'] = {'type': 'HTTP_RESPONSE', 'data': data_utils.make_dict(response)}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
flow['http'] = None
# Mark non-TCP HTTP
if flow['http'] and flow['protocol'] != 'TCP':
flow['http'].update({'weird': 'UDP-HTTP'})
# All done
yield flow | [
"def",
"http_meta_data",
"(",
"self",
")",
":",
"# For each flow process the contents",
"for",
"flow",
"in",
"self",
".",
"input_stream",
":",
"# Client to Server",
"if",
"flow",
"[",
"'direction'",
"]",
"==",
"'CTS'",
":",
"try",
":",
"request",
"=",
"dpkt",
... | Pull out the application metadata for each flow in the input_stream | [
"Pull",
"out",
"the",
"application",
"metadata",
"for",
"each",
"flow",
"in",
"the",
"input_stream"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/http_meta.py#L23-L52 | train | 48,358 |
SuperCowPowers/chains | chains/links/transport_meta.py | TransportMeta.transport_meta_data | def transport_meta_data(self):
"""Pull out the transport metadata for each packet in the input_stream"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Get the transport data and type
trans_data = item['packet']['data']
trans_type = self._get_transport_type(trans_data)
if trans_type and trans_data:
item['transport'] = data_utils.make_dict(trans_data)
item['transport']['type'] = trans_type
item['transport']['flags'] = self._readable_flags(item['transport'])
item['transport']['data'] = trans_data['data']
# All done
yield item | python | def transport_meta_data(self):
"""Pull out the transport metadata for each packet in the input_stream"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Get the transport data and type
trans_data = item['packet']['data']
trans_type = self._get_transport_type(trans_data)
if trans_type and trans_data:
item['transport'] = data_utils.make_dict(trans_data)
item['transport']['type'] = trans_type
item['transport']['flags'] = self._readable_flags(item['transport'])
item['transport']['data'] = trans_data['data']
# All done
yield item | [
"def",
"transport_meta_data",
"(",
"self",
")",
":",
"# For each packet in the pcap process the contents",
"for",
"item",
"in",
"self",
".",
"input_stream",
":",
"# Get the transport data and type",
"trans_data",
"=",
"item",
"[",
"'packet'",
"]",
"[",
"'data'",
"]",
... | Pull out the transport metadata for each packet in the input_stream | [
"Pull",
"out",
"the",
"transport",
"metadata",
"for",
"each",
"packet",
"in",
"the",
"input_stream"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/transport_meta.py#L21-L37 | train | 48,359 |
SuperCowPowers/chains | chains/links/transport_meta.py | TransportMeta._readable_flags | def _readable_flags(transport):
"""Method that turns bit flags into a human readable list
Args:
transport (dict): transport info, specifically needs a 'flags' key with bit_flags
Returns:
list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ...]
"""
if 'flags' not in transport:
return None
_flag_list = []
flags = transport['flags']
if flags & dpkt.tcp.TH_SYN:
if flags & dpkt.tcp.TH_ACK:
_flag_list.append('syn_ack')
else:
_flag_list.append('syn')
elif flags & dpkt.tcp.TH_FIN:
if flags & dpkt.tcp.TH_ACK:
_flag_list.append('fin_ack')
else:
_flag_list.append('fin')
elif flags & dpkt.tcp.TH_RST:
_flag_list.append('rst')
elif flags & dpkt.tcp.TH_PUSH:
_flag_list.append('psh')
return _flag_list | python | def _readable_flags(transport):
"""Method that turns bit flags into a human readable list
Args:
transport (dict): transport info, specifically needs a 'flags' key with bit_flags
Returns:
list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ...]
"""
if 'flags' not in transport:
return None
_flag_list = []
flags = transport['flags']
if flags & dpkt.tcp.TH_SYN:
if flags & dpkt.tcp.TH_ACK:
_flag_list.append('syn_ack')
else:
_flag_list.append('syn')
elif flags & dpkt.tcp.TH_FIN:
if flags & dpkt.tcp.TH_ACK:
_flag_list.append('fin_ack')
else:
_flag_list.append('fin')
elif flags & dpkt.tcp.TH_RST:
_flag_list.append('rst')
elif flags & dpkt.tcp.TH_PUSH:
_flag_list.append('psh')
return _flag_list | [
"def",
"_readable_flags",
"(",
"transport",
")",
":",
"if",
"'flags'",
"not",
"in",
"transport",
":",
"return",
"None",
"_flag_list",
"=",
"[",
"]",
"flags",
"=",
"transport",
"[",
"'flags'",
"]",
"if",
"flags",
"&",
"dpkt",
".",
"tcp",
".",
"TH_SYN",
... | Method that turns bit flags into a human readable list
Args:
transport (dict): transport info, specifically needs a 'flags' key with bit_flags
Returns:
list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ...] | [
"Method",
"that",
"turns",
"bit",
"flags",
"into",
"a",
"human",
"readable",
"list"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/transport_meta.py#L45-L71 | train | 48,360 |
ajenhl/tacl | tacl/jitc.py | JitCReport._create_breakdown_chart | def _create_breakdown_chart(self, data, work, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a stacked bar chart.
The generated data gives the percentages of the text of the
work (across all witnesses) that are in common with all other
works, shared with each "maybe" work, and unique.
:param data: data to derive the chart data from
:type data: `pandas.DataFrame`
:param work: work to show related work data for
:type work: `str`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
chart_data = data.loc[work].sort_values(by=SHARED, ascending=False)[
[SHARED, UNIQUE, COMMON]]
csv_path = os.path.join(output_dir, 'breakdown_{}.csv'.format(
work))
chart_data.to_csv(csv_path) | python | def _create_breakdown_chart(self, data, work, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a stacked bar chart.
The generated data gives the percentages of the text of the
work (across all witnesses) that are in common with all other
works, shared with each "maybe" work, and unique.
:param data: data to derive the chart data from
:type data: `pandas.DataFrame`
:param work: work to show related work data for
:type work: `str`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
chart_data = data.loc[work].sort_values(by=SHARED, ascending=False)[
[SHARED, UNIQUE, COMMON]]
csv_path = os.path.join(output_dir, 'breakdown_{}.csv'.format(
work))
chart_data.to_csv(csv_path) | [
"def",
"_create_breakdown_chart",
"(",
"self",
",",
"data",
",",
"work",
",",
"output_dir",
")",
":",
"chart_data",
"=",
"data",
".",
"loc",
"[",
"work",
"]",
".",
"sort_values",
"(",
"by",
"=",
"SHARED",
",",
"ascending",
"=",
"False",
")",
"[",
"[",
... | Generates and writes to a file in `output_dir` the data used to
display a stacked bar chart.
The generated data gives the percentages of the text of the
work (across all witnesses) that are in common with all other
works, shared with each "maybe" work, and unique.
:param data: data to derive the chart data from
:type data: `pandas.DataFrame`
:param work: work to show related work data for
:type work: `str`
:param output_dir: directory to output data file to
:type output_dir: `str` | [
"Generates",
"and",
"writes",
"to",
"a",
"file",
"in",
"output_dir",
"the",
"data",
"used",
"to",
"display",
"a",
"stacked",
"bar",
"chart",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L74-L94 | train | 48,361 |
ajenhl/tacl | tacl/jitc.py | JitCReport._create_chord_chart | def _create_chord_chart(self, data, works, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a chord chart.
:param data: data to derive the chord data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `list`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
matrix = []
chord_data = data.unstack(BASE_WORK)[SHARED]
for index, row_data in chord_data.fillna(value=0).iterrows():
matrix.append([value / 100 for value in row_data])
colours = generate_colours(len(works))
colour_works = [{'work': work, 'colour': colour} for work, colour
in zip(chord_data, colours)]
json_data = json.dumps({'works': colour_works, 'matrix': matrix})
with open(os.path.join(output_dir, 'chord_data.js'), 'w') as fh:
fh.write('var chordData = {}'.format(json_data)) | python | def _create_chord_chart(self, data, works, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a chord chart.
:param data: data to derive the chord data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `list`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
matrix = []
chord_data = data.unstack(BASE_WORK)[SHARED]
for index, row_data in chord_data.fillna(value=0).iterrows():
matrix.append([value / 100 for value in row_data])
colours = generate_colours(len(works))
colour_works = [{'work': work, 'colour': colour} for work, colour
in zip(chord_data, colours)]
json_data = json.dumps({'works': colour_works, 'matrix': matrix})
with open(os.path.join(output_dir, 'chord_data.js'), 'w') as fh:
fh.write('var chordData = {}'.format(json_data)) | [
"def",
"_create_chord_chart",
"(",
"self",
",",
"data",
",",
"works",
",",
"output_dir",
")",
":",
"matrix",
"=",
"[",
"]",
"chord_data",
"=",
"data",
".",
"unstack",
"(",
"BASE_WORK",
")",
"[",
"SHARED",
"]",
"for",
"index",
",",
"row_data",
"in",
"ch... | Generates and writes to a file in `output_dir` the data used to
display a chord chart.
:param data: data to derive the chord data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `list`
:param output_dir: directory to output data file to
:type output_dir: `str` | [
"Generates",
"and",
"writes",
"to",
"a",
"file",
"in",
"output_dir",
"the",
"data",
"used",
"to",
"display",
"a",
"chord",
"chart",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L96-L117 | train | 48,362 |
ajenhl/tacl | tacl/jitc.py | JitCReport._create_matrix_chart | def _create_matrix_chart(self, data, works, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a matrix chart.
:param data: data to derive the matrix data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `list`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
nodes = [{'work': work, 'group': 1} for work in works]
weights = data.stack().unstack(RELATED_WORK).max()
seen = []
links = []
for (source, target), weight in weights.iteritems():
if target not in seen and target != source:
seen.append(source)
links.append({'source': works.index(source),
'target': works.index(target),
'value': weight})
json_data = json.dumps({'nodes': nodes, 'links': links})
with open(os.path.join(output_dir, 'matrix_data.js'), 'w') as fh:
fh.write('var matrixData = {}'.format(json_data)) | python | def _create_matrix_chart(self, data, works, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a matrix chart.
:param data: data to derive the matrix data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `list`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
nodes = [{'work': work, 'group': 1} for work in works]
weights = data.stack().unstack(RELATED_WORK).max()
seen = []
links = []
for (source, target), weight in weights.iteritems():
if target not in seen and target != source:
seen.append(source)
links.append({'source': works.index(source),
'target': works.index(target),
'value': weight})
json_data = json.dumps({'nodes': nodes, 'links': links})
with open(os.path.join(output_dir, 'matrix_data.js'), 'w') as fh:
fh.write('var matrixData = {}'.format(json_data)) | [
"def",
"_create_matrix_chart",
"(",
"self",
",",
"data",
",",
"works",
",",
"output_dir",
")",
":",
"nodes",
"=",
"[",
"{",
"'work'",
":",
"work",
",",
"'group'",
":",
"1",
"}",
"for",
"work",
"in",
"works",
"]",
"weights",
"=",
"data",
".",
"stack",... | Generates and writes to a file in `output_dir` the data used to
display a matrix chart.
:param data: data to derive the matrix data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `list`
:param output_dir: directory to output data file to
:type output_dir: `str` | [
"Generates",
"and",
"writes",
"to",
"a",
"file",
"in",
"output_dir",
"the",
"data",
"used",
"to",
"display",
"a",
"matrix",
"chart",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L119-L143 | train | 48,363 |
ajenhl/tacl | tacl/jitc.py | JitCReport._create_related_chart | def _create_related_chart(self, data, work, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a grouped bar chart.
This data gives, for each "maybe" work, the percentage of it
that is shared with `work`, and the percentage of `work` that
is shared with the "maybe" work.
:param data: data to derive the chart data from
:type data: `pandas.DataFrame`
:param works: work to show related data for
:type works: `str`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
chart_data = data[work].dropna().sort_values(by=SHARED_RELATED_WORK,
ascending=False)
csv_path = os.path.join(output_dir, 'related_{}.csv'.format(work))
chart_data.to_csv(csv_path) | python | def _create_related_chart(self, data, work, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a grouped bar chart.
This data gives, for each "maybe" work, the percentage of it
that is shared with `work`, and the percentage of `work` that
is shared with the "maybe" work.
:param data: data to derive the chart data from
:type data: `pandas.DataFrame`
:param works: work to show related data for
:type works: `str`
:param output_dir: directory to output data file to
:type output_dir: `str`
"""
chart_data = data[work].dropna().sort_values(by=SHARED_RELATED_WORK,
ascending=False)
csv_path = os.path.join(output_dir, 'related_{}.csv'.format(work))
chart_data.to_csv(csv_path) | [
"def",
"_create_related_chart",
"(",
"self",
",",
"data",
",",
"work",
",",
"output_dir",
")",
":",
"chart_data",
"=",
"data",
"[",
"work",
"]",
".",
"dropna",
"(",
")",
".",
"sort_values",
"(",
"by",
"=",
"SHARED_RELATED_WORK",
",",
"ascending",
"=",
"F... | Generates and writes to a file in `output_dir` the data used to
display a grouped bar chart.
This data gives, for each "maybe" work, the percentage of it
that is shared with `work`, and the percentage of `work` that
is shared with the "maybe" work.
:param data: data to derive the chart data from
:type data: `pandas.DataFrame`
:param works: work to show related data for
:type works: `str`
:param output_dir: directory to output data file to
:type output_dir: `str` | [
"Generates",
"and",
"writes",
"to",
"a",
"file",
"in",
"output_dir",
"the",
"data",
"used",
"to",
"display",
"a",
"grouped",
"bar",
"chart",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L145-L164 | train | 48,364 |
ajenhl/tacl | tacl/jitc.py | JitCReport._drop_no_label_results | def _drop_no_label_results(self, results, fh):
"""Writes `results` to `fh` minus those results associated with the
'no' label.
:param results: results to be manipulated
:type results: file-like object
:param fh: output destination
:type fh: file-like object
"""
results.seek(0)
results = Results(results, self._tokenizer)
results.remove_label(self._no_label)
results.csv(fh) | python | def _drop_no_label_results(self, results, fh):
"""Writes `results` to `fh` minus those results associated with the
'no' label.
:param results: results to be manipulated
:type results: file-like object
:param fh: output destination
:type fh: file-like object
"""
results.seek(0)
results = Results(results, self._tokenizer)
results.remove_label(self._no_label)
results.csv(fh) | [
"def",
"_drop_no_label_results",
"(",
"self",
",",
"results",
",",
"fh",
")",
":",
"results",
".",
"seek",
"(",
"0",
")",
"results",
"=",
"Results",
"(",
"results",
",",
"self",
".",
"_tokenizer",
")",
"results",
".",
"remove_label",
"(",
"self",
".",
... | Writes `results` to `fh` minus those results associated with the
'no' label.
:param results: results to be manipulated
:type results: file-like object
:param fh: output destination
:type fh: file-like object | [
"Writes",
"results",
"to",
"fh",
"minus",
"those",
"results",
"associated",
"with",
"the",
"no",
"label",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L166-L179 | train | 48,365 |
ajenhl/tacl | tacl/jitc.py | JitCReport._generate_statistics | def _generate_statistics(self, out_path, results_path):
"""Writes a statistics report for the results at `results_path` to
`out_path`.
Reuses an existing statistics report if one exists at
`out_path`.
:param out_path: path to output statistics report to
:type out_path: `str`
:param results_path: path of results to generate statistics for
:type results_path: `str`
"""
if not os.path.exists(out_path):
report = StatisticsReport(self._corpus, self._tokenizer,
results_path)
report.generate_statistics()
with open(out_path, mode='w', encoding='utf-8', newline='') as fh:
report.csv(fh) | python | def _generate_statistics(self, out_path, results_path):
"""Writes a statistics report for the results at `results_path` to
`out_path`.
Reuses an existing statistics report if one exists at
`out_path`.
:param out_path: path to output statistics report to
:type out_path: `str`
:param results_path: path of results to generate statistics for
:type results_path: `str`
"""
if not os.path.exists(out_path):
report = StatisticsReport(self._corpus, self._tokenizer,
results_path)
report.generate_statistics()
with open(out_path, mode='w', encoding='utf-8', newline='') as fh:
report.csv(fh) | [
"def",
"_generate_statistics",
"(",
"self",
",",
"out_path",
",",
"results_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"out_path",
")",
":",
"report",
"=",
"StatisticsReport",
"(",
"self",
".",
"_corpus",
",",
"self",
".",
"_toke... | Writes a statistics report for the results at `results_path` to
`out_path`.
Reuses an existing statistics report if one exists at
`out_path`.
:param out_path: path to output statistics report to
:type out_path: `str`
:param results_path: path of results to generate statistics for
:type results_path: `str` | [
"Writes",
"a",
"statistics",
"report",
"for",
"the",
"results",
"at",
"results_path",
"to",
"out_path",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L216-L234 | train | 48,366 |
ajenhl/tacl | tacl/jitc.py | JitCReport._process_diff | def _process_diff(self, yes_work, maybe_work, work_dir, ym_results_path,
yn_results_path, stats):
"""Returns statistics on the difference between the intersection of
`yes_work` and `maybe_work` and the intersection of `yes_work`
and "no" works.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param ym_results_path: path to results intersecting
`yes_work` with `maybe_work`
:type yn_results_path: `str`
:param yn_results_path: path to results intersecting
`yes_work` with "no" works
:type yn_results_path: `str`
:param stats: data structure to hold the statistical data
:type stats: `dict`
:rtype: `dict`
"""
distinct_results_path = os.path.join(
work_dir, 'distinct_{}.csv'.format(maybe_work))
results = [yn_results_path, ym_results_path]
labels = [self._no_label, self._maybe_label]
self._run_query(distinct_results_path, self._store.diff_supplied,
[results, labels, self._tokenizer])
return self._update_stats('diff', work_dir, distinct_results_path,
yes_work, maybe_work, stats, SHARED, COMMON) | python | def _process_diff(self, yes_work, maybe_work, work_dir, ym_results_path,
yn_results_path, stats):
"""Returns statistics on the difference between the intersection of
`yes_work` and `maybe_work` and the intersection of `yes_work`
and "no" works.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param ym_results_path: path to results intersecting
`yes_work` with `maybe_work`
:type yn_results_path: `str`
:param yn_results_path: path to results intersecting
`yes_work` with "no" works
:type yn_results_path: `str`
:param stats: data structure to hold the statistical data
:type stats: `dict`
:rtype: `dict`
"""
distinct_results_path = os.path.join(
work_dir, 'distinct_{}.csv'.format(maybe_work))
results = [yn_results_path, ym_results_path]
labels = [self._no_label, self._maybe_label]
self._run_query(distinct_results_path, self._store.diff_supplied,
[results, labels, self._tokenizer])
return self._update_stats('diff', work_dir, distinct_results_path,
yes_work, maybe_work, stats, SHARED, COMMON) | [
"def",
"_process_diff",
"(",
"self",
",",
"yes_work",
",",
"maybe_work",
",",
"work_dir",
",",
"ym_results_path",
",",
"yn_results_path",
",",
"stats",
")",
":",
"distinct_results_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"'distinct_{}.... | Returns statistics on the difference between the intersection of
`yes_work` and `maybe_work` and the intersection of `yes_work`
and "no" works.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param ym_results_path: path to results intersecting
`yes_work` with `maybe_work`
:type yn_results_path: `str`
:param yn_results_path: path to results intersecting
`yes_work` with "no" works
:type yn_results_path: `str`
:param stats: data structure to hold the statistical data
:type stats: `dict`
:rtype: `dict` | [
"Returns",
"statistics",
"on",
"the",
"difference",
"between",
"the",
"intersection",
"of",
"yes_work",
"and",
"maybe_work",
"and",
"the",
"intersection",
"of",
"yes_work",
"and",
"no",
"works",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L247-L277 | train | 48,367 |
ajenhl/tacl | tacl/jitc.py | JitCReport._process_intersection | def _process_intersection(self, yes_work, maybe_work, work_dir,
ym_results_path, stats):
"""Returns statistics on the intersection between `yes_work` and
`maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param ym_results_path: path to results intersecting
`yes_work` with `maybe_work`
:type ym_results_path: `str`
:param stats: data structure to hold the statistical data
:type stats: `dict`
:rtype: `dict`
"""
catalogue = {yes_work: self._no_label, maybe_work: self._maybe_label}
self._run_query(ym_results_path, self._store.intersection, [catalogue],
False)
# Though this is the intersection only between "yes" and
# "maybe", the percentage of overlap is added to the "common"
# stat rather than "shared". Then, in _process_diff, the
# percentage of difference between "yes" and "no" can be
# removed from "common" and added to "shared".
return self._update_stats('intersect', work_dir, ym_results_path,
yes_work, maybe_work, stats, COMMON, UNIQUE) | python | def _process_intersection(self, yes_work, maybe_work, work_dir,
ym_results_path, stats):
"""Returns statistics on the intersection between `yes_work` and
`maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param ym_results_path: path to results intersecting
`yes_work` with `maybe_work`
:type ym_results_path: `str`
:param stats: data structure to hold the statistical data
:type stats: `dict`
:rtype: `dict`
"""
catalogue = {yes_work: self._no_label, maybe_work: self._maybe_label}
self._run_query(ym_results_path, self._store.intersection, [catalogue],
False)
# Though this is the intersection only between "yes" and
# "maybe", the percentage of overlap is added to the "common"
# stat rather than "shared". Then, in _process_diff, the
# percentage of difference between "yes" and "no" can be
# removed from "common" and added to "shared".
return self._update_stats('intersect', work_dir, ym_results_path,
yes_work, maybe_work, stats, COMMON, UNIQUE) | [
"def",
"_process_intersection",
"(",
"self",
",",
"yes_work",
",",
"maybe_work",
",",
"work_dir",
",",
"ym_results_path",
",",
"stats",
")",
":",
"catalogue",
"=",
"{",
"yes_work",
":",
"self",
".",
"_no_label",
",",
"maybe_work",
":",
"self",
".",
"_maybe_l... | Returns statistics on the intersection between `yes_work` and
`maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param ym_results_path: path to results intersecting
`yes_work` with `maybe_work`
:type ym_results_path: `str`
:param stats: data structure to hold the statistical data
:type stats: `dict`
:rtype: `dict` | [
"Returns",
"statistics",
"on",
"the",
"intersection",
"between",
"yes_work",
"and",
"maybe_work",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L279-L307 | train | 48,368 |
ajenhl/tacl | tacl/jitc.py | JitCReport._process_maybe_work | def _process_maybe_work(self, yes_work, maybe_work, work_dir,
yn_results_path, stats):
"""Returns statistics of how `yes_work` compares with `maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param yn_results_path: path to results intersecting
`yes_work` with "no" works
:type yn_results_path: `str`
:param stats: data structure to hold statistical data of the
comparison
:type stats: `dict`
:rtype: `dict`
"""
if maybe_work == yes_work:
return stats
self._logger.info(
'Processing "maybe" work {} against "yes" work {}.'.format(
maybe_work, yes_work))
# Set base values for each statistic of interest, for each
# witness.
for siglum in self._corpus.get_sigla(maybe_work):
witness = (maybe_work, siglum)
stats[COMMON][witness] = 0
stats[SHARED][witness] = 0
stats[UNIQUE][witness] = 100
works = [yes_work, maybe_work]
# Sort the works to have a single filename for the
# intersection each pair of works, whether they are yes or
# maybe. This saves repeating the intersection with the roles
# switched, since _run_query will use a found file rather than
# rerun the query.
works.sort()
ym_results_path = os.path.join(
self._ym_intersects_dir, '{}_intersect_{}.csv'.format(*works))
stats = self._process_intersection(yes_work, maybe_work, work_dir,
ym_results_path, stats)
stats = self._process_diff(yes_work, maybe_work, work_dir,
ym_results_path, yn_results_path, stats)
return stats | python | def _process_maybe_work(self, yes_work, maybe_work, work_dir,
yn_results_path, stats):
"""Returns statistics of how `yes_work` compares with `maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param yn_results_path: path to results intersecting
`yes_work` with "no" works
:type yn_results_path: `str`
:param stats: data structure to hold statistical data of the
comparison
:type stats: `dict`
:rtype: `dict`
"""
if maybe_work == yes_work:
return stats
self._logger.info(
'Processing "maybe" work {} against "yes" work {}.'.format(
maybe_work, yes_work))
# Set base values for each statistic of interest, for each
# witness.
for siglum in self._corpus.get_sigla(maybe_work):
witness = (maybe_work, siglum)
stats[COMMON][witness] = 0
stats[SHARED][witness] = 0
stats[UNIQUE][witness] = 100
works = [yes_work, maybe_work]
# Sort the works to have a single filename for the
# intersection each pair of works, whether they are yes or
# maybe. This saves repeating the intersection with the roles
# switched, since _run_query will use a found file rather than
# rerun the query.
works.sort()
ym_results_path = os.path.join(
self._ym_intersects_dir, '{}_intersect_{}.csv'.format(*works))
stats = self._process_intersection(yes_work, maybe_work, work_dir,
ym_results_path, stats)
stats = self._process_diff(yes_work, maybe_work, work_dir,
ym_results_path, yn_results_path, stats)
return stats | [
"def",
"_process_maybe_work",
"(",
"self",
",",
"yes_work",
",",
"maybe_work",
",",
"work_dir",
",",
"yn_results_path",
",",
"stats",
")",
":",
"if",
"maybe_work",
"==",
"yes_work",
":",
"return",
"stats",
"self",
".",
"_logger",
".",
"info",
"(",
"'Processi... | Returns statistics of how `yes_work` compares with `maybe_work`.
:param yes_work: name of work for which stats are collected
:type yes_work: `str`
:param maybe_work: name of work being compared with `yes_work`
:type maybe_work: `str`
:param work_dir: directory where generated files are saved
:type work_dir: `str`
:param yn_results_path: path to results intersecting
`yes_work` with "no" works
:type yn_results_path: `str`
:param stats: data structure to hold statistical data of the
comparison
:type stats: `dict`
:rtype: `dict` | [
"Returns",
"statistics",
"of",
"how",
"yes_work",
"compares",
"with",
"maybe_work",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L309-L353 | train | 48,369 |
ajenhl/tacl | tacl/jitc.py | JitCReport._process_works | def _process_works(self, maybe_works, no_works, output_dir):
"""Collect and return the data of how each work in `maybe_works`
relates to each other work.
:param maybe_works:
:type maybe_works: `list` of `str`
:param no_works:
:type no_works: `list` of `str`
:param output_dir: base output directory
:type output_dir: `str`
:rtype: `pandas.DataFrame`
"""
output_data_dir = os.path.join(output_dir, 'data')
no_catalogue = {work: self._no_label for work in no_works}
self._ym_intersects_dir = os.path.join(output_data_dir,
'ym_intersects')
data = {}
os.makedirs(self._ym_intersects_dir, exist_ok=True)
for yes_work in maybe_works:
no_catalogue[yes_work] = self._maybe_label
stats = self._process_yes_work(yes_work, no_catalogue,
maybe_works, output_data_dir)
no_catalogue.pop(yes_work)
for scope in (SHARED, COMMON, UNIQUE):
work_data = stats[scope]
index = pd.MultiIndex.from_tuples(
list(work_data.keys()), names=[RELATED_WORK, SIGLUM])
data[(yes_work, scope)] = pd.Series(list(work_data.values()),
index=index)
df = pd.DataFrame(data)
df.columns.names = [BASE_WORK, SCOPE]
df = df.stack(BASE_WORK).swaplevel(
BASE_WORK, SIGLUM).swaplevel(RELATED_WORK, BASE_WORK)
return df | python | def _process_works(self, maybe_works, no_works, output_dir):
"""Collect and return the data of how each work in `maybe_works`
relates to each other work.
:param maybe_works:
:type maybe_works: `list` of `str`
:param no_works:
:type no_works: `list` of `str`
:param output_dir: base output directory
:type output_dir: `str`
:rtype: `pandas.DataFrame`
"""
output_data_dir = os.path.join(output_dir, 'data')
no_catalogue = {work: self._no_label for work in no_works}
self._ym_intersects_dir = os.path.join(output_data_dir,
'ym_intersects')
data = {}
os.makedirs(self._ym_intersects_dir, exist_ok=True)
for yes_work in maybe_works:
no_catalogue[yes_work] = self._maybe_label
stats = self._process_yes_work(yes_work, no_catalogue,
maybe_works, output_data_dir)
no_catalogue.pop(yes_work)
for scope in (SHARED, COMMON, UNIQUE):
work_data = stats[scope]
index = pd.MultiIndex.from_tuples(
list(work_data.keys()), names=[RELATED_WORK, SIGLUM])
data[(yes_work, scope)] = pd.Series(list(work_data.values()),
index=index)
df = pd.DataFrame(data)
df.columns.names = [BASE_WORK, SCOPE]
df = df.stack(BASE_WORK).swaplevel(
BASE_WORK, SIGLUM).swaplevel(RELATED_WORK, BASE_WORK)
return df | [
"def",
"_process_works",
"(",
"self",
",",
"maybe_works",
",",
"no_works",
",",
"output_dir",
")",
":",
"output_data_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'data'",
")",
"no_catalogue",
"=",
"{",
"work",
":",
"self",
".",
"_n... | Collect and return the data of how each work in `maybe_works`
relates to each other work.
:param maybe_works:
:type maybe_works: `list` of `str`
:param no_works:
:type no_works: `list` of `str`
:param output_dir: base output directory
:type output_dir: `str`
:rtype: `pandas.DataFrame` | [
"Collect",
"and",
"return",
"the",
"data",
"of",
"how",
"each",
"work",
"in",
"maybe_works",
"relates",
"to",
"each",
"other",
"work",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L355-L389 | train | 48,370 |
ajenhl/tacl | tacl/jitc.py | JitCReport._process_yes_work | def _process_yes_work(self, yes_work, no_catalogue, maybe_works,
output_dir):
"""Returns statistics of how `yes_work` compares with the other works
in `no_catalogue` and the "maybe" works.
:param yes_work: name of work being processed
:type yes_work: `str`
:param no_catalogue: catalogue of containing `yes_work` and the "no"
works
:type no_catalogue: `Catalogue`
:param maybe_works: names of "maybe" works
:type maybe_works: `list` of `str`
:param output_dir: directory where generated files are saved
:type output_dir: `str`
:rtype: `dict`
"""
self._logger.info('Processing "maybe" work {} as "yes".'.format(
yes_work))
stats = {COMMON: {}, SHARED: {}, UNIQUE: {}}
yes_work_dir = os.path.join(output_dir, yes_work)
os.makedirs(yes_work_dir, exist_ok=True)
results_path = os.path.join(yes_work_dir, 'intersect_with_no.csv')
self._run_query(results_path, self._store.intersection, [no_catalogue])
for maybe_work in maybe_works:
stats = self._process_maybe_work(
yes_work, maybe_work, yes_work_dir, results_path, stats)
return stats | python | def _process_yes_work(self, yes_work, no_catalogue, maybe_works,
output_dir):
"""Returns statistics of how `yes_work` compares with the other works
in `no_catalogue` and the "maybe" works.
:param yes_work: name of work being processed
:type yes_work: `str`
:param no_catalogue: catalogue of containing `yes_work` and the "no"
works
:type no_catalogue: `Catalogue`
:param maybe_works: names of "maybe" works
:type maybe_works: `list` of `str`
:param output_dir: directory where generated files are saved
:type output_dir: `str`
:rtype: `dict`
"""
self._logger.info('Processing "maybe" work {} as "yes".'.format(
yes_work))
stats = {COMMON: {}, SHARED: {}, UNIQUE: {}}
yes_work_dir = os.path.join(output_dir, yes_work)
os.makedirs(yes_work_dir, exist_ok=True)
results_path = os.path.join(yes_work_dir, 'intersect_with_no.csv')
self._run_query(results_path, self._store.intersection, [no_catalogue])
for maybe_work in maybe_works:
stats = self._process_maybe_work(
yes_work, maybe_work, yes_work_dir, results_path, stats)
return stats | [
"def",
"_process_yes_work",
"(",
"self",
",",
"yes_work",
",",
"no_catalogue",
",",
"maybe_works",
",",
"output_dir",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Processing \"maybe\" work {} as \"yes\".'",
".",
"format",
"(",
"yes_work",
")",
")",
"sta... | Returns statistics of how `yes_work` compares with the other works
in `no_catalogue` and the "maybe" works.
:param yes_work: name of work being processed
:type yes_work: `str`
:param no_catalogue: catalogue of containing `yes_work` and the "no"
works
:type no_catalogue: `Catalogue`
:param maybe_works: names of "maybe" works
:type maybe_works: `list` of `str`
:param output_dir: directory where generated files are saved
:type output_dir: `str`
:rtype: `dict` | [
"Returns",
"statistics",
"of",
"how",
"yes_work",
"compares",
"with",
"the",
"other",
"works",
"in",
"no_catalogue",
"and",
"the",
"maybe",
"works",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L391-L418 | train | 48,371 |
ajenhl/tacl | tacl/jitc.py | JitCReport._run_query | def _run_query(self, path, query, query_args, drop_no=True):
"""Runs `query` and outputs results to a file at `path`.
If `path` exists, the query is not run.
:param path: path to output results to
:type path: `str`
:param query: query to run
:type query: `method`
:param query_args: arguments to supply to the query
:type query_args: `list`
:param drop_no: whether to drop results from the No corpus
:type drop_no: `bool`
"""
if os.path.exists(path):
return
output_results = io.StringIO(newline='')
query(*query_args, output_fh=output_results)
with open(path, mode='w', encoding='utf-8', newline='') as fh:
if drop_no:
self._drop_no_label_results(output_results, fh)
else:
fh.write(output_results.getvalue()) | python | def _run_query(self, path, query, query_args, drop_no=True):
"""Runs `query` and outputs results to a file at `path`.
If `path` exists, the query is not run.
:param path: path to output results to
:type path: `str`
:param query: query to run
:type query: `method`
:param query_args: arguments to supply to the query
:type query_args: `list`
:param drop_no: whether to drop results from the No corpus
:type drop_no: `bool`
"""
if os.path.exists(path):
return
output_results = io.StringIO(newline='')
query(*query_args, output_fh=output_results)
with open(path, mode='w', encoding='utf-8', newline='') as fh:
if drop_no:
self._drop_no_label_results(output_results, fh)
else:
fh.write(output_results.getvalue()) | [
"def",
"_run_query",
"(",
"self",
",",
"path",
",",
"query",
",",
"query_args",
",",
"drop_no",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"output_results",
"=",
"io",
".",
"StringIO",
"(",
"newlin... | Runs `query` and outputs results to a file at `path`.
If `path` exists, the query is not run.
:param path: path to output results to
:type path: `str`
:param query: query to run
:type query: `method`
:param query_args: arguments to supply to the query
:type query_args: `list`
:param drop_no: whether to drop results from the No corpus
:type drop_no: `bool` | [
"Runs",
"query",
"and",
"outputs",
"results",
"to",
"a",
"file",
"at",
"path",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L420-L443 | train | 48,372 |
ajenhl/tacl | tacl/data_store.py | DataStore._add_indices | def _add_indices(self):
"""Adds the database indices relating to n-grams."""
self._logger.info('Adding database indices')
self._conn.execute(constants.CREATE_INDEX_TEXTNGRAM_SQL)
self._logger.info('Indices added') | python | def _add_indices(self):
"""Adds the database indices relating to n-grams."""
self._logger.info('Adding database indices')
self._conn.execute(constants.CREATE_INDEX_TEXTNGRAM_SQL)
self._logger.info('Indices added') | [
"def",
"_add_indices",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding database indices'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"CREATE_INDEX_TEXTNGRAM_SQL",
")",
"self",
".",
"_logger",
".",
"info",
"("... | Adds the database indices relating to n-grams. | [
"Adds",
"the",
"database",
"indices",
"relating",
"to",
"n",
"-",
"grams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L44-L48 | train | 48,373 |
ajenhl/tacl | tacl/data_store.py | DataStore.add_ngrams | def add_ngrams(self, corpus, minimum, maximum, catalogue=None):
"""Adds n-gram data from `corpus` to the data store.
:param corpus: corpus of works
:type corpus: `Corpus`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
:param catalogue: optional catalogue to limit corpus to
:type catalogue: `Catalogue`
"""
self._initialise_database()
if catalogue:
for work in catalogue:
for witness in corpus.get_witnesses(work):
self._add_text_ngrams(witness, minimum, maximum)
else:
for witness in corpus.get_witnesses():
self._add_text_ngrams(witness, minimum, maximum)
self._add_indices()
self._analyse() | python | def add_ngrams(self, corpus, minimum, maximum, catalogue=None):
"""Adds n-gram data from `corpus` to the data store.
:param corpus: corpus of works
:type corpus: `Corpus`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
:param catalogue: optional catalogue to limit corpus to
:type catalogue: `Catalogue`
"""
self._initialise_database()
if catalogue:
for work in catalogue:
for witness in corpus.get_witnesses(work):
self._add_text_ngrams(witness, minimum, maximum)
else:
for witness in corpus.get_witnesses():
self._add_text_ngrams(witness, minimum, maximum)
self._add_indices()
self._analyse() | [
"def",
"add_ngrams",
"(",
"self",
",",
"corpus",
",",
"minimum",
",",
"maximum",
",",
"catalogue",
"=",
"None",
")",
":",
"self",
".",
"_initialise_database",
"(",
")",
"if",
"catalogue",
":",
"for",
"work",
"in",
"catalogue",
":",
"for",
"witness",
"in"... | Adds n-gram data from `corpus` to the data store.
:param corpus: corpus of works
:type corpus: `Corpus`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
:param catalogue: optional catalogue to limit corpus to
:type catalogue: `Catalogue` | [
"Adds",
"n",
"-",
"gram",
"data",
"from",
"corpus",
"to",
"the",
"data",
"store",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L50-L72 | train | 48,374 |
ajenhl/tacl | tacl/data_store.py | DataStore._add_temporary_ngrams | def _add_temporary_ngrams(self, ngrams):
"""Adds `ngrams` to a temporary table."""
# Remove duplicate n-grams, empty n-grams, and non-string n-grams.
ngrams = [ngram for ngram in ngrams if ngram and
isinstance(ngram, str)]
# Deduplicate while preserving order (useful for testing).
seen = {}
ngrams = [seen.setdefault(x, x) for x in ngrams if x not in seen]
self._conn.execute(constants.DROP_TEMPORARY_NGRAMS_TABLE_SQL)
self._conn.execute(constants.CREATE_TEMPORARY_NGRAMS_TABLE_SQL)
self._conn.executemany(constants.INSERT_TEMPORARY_NGRAM_SQL,
[(ngram,) for ngram in ngrams]) | python | def _add_temporary_ngrams(self, ngrams):
"""Adds `ngrams` to a temporary table."""
# Remove duplicate n-grams, empty n-grams, and non-string n-grams.
ngrams = [ngram for ngram in ngrams if ngram and
isinstance(ngram, str)]
# Deduplicate while preserving order (useful for testing).
seen = {}
ngrams = [seen.setdefault(x, x) for x in ngrams if x not in seen]
self._conn.execute(constants.DROP_TEMPORARY_NGRAMS_TABLE_SQL)
self._conn.execute(constants.CREATE_TEMPORARY_NGRAMS_TABLE_SQL)
self._conn.executemany(constants.INSERT_TEMPORARY_NGRAM_SQL,
[(ngram,) for ngram in ngrams]) | [
"def",
"_add_temporary_ngrams",
"(",
"self",
",",
"ngrams",
")",
":",
"# Remove duplicate n-grams, empty n-grams, and non-string n-grams.",
"ngrams",
"=",
"[",
"ngram",
"for",
"ngram",
"in",
"ngrams",
"if",
"ngram",
"and",
"isinstance",
"(",
"ngram",
",",
"str",
")"... | Adds `ngrams` to a temporary table. | [
"Adds",
"ngrams",
"to",
"a",
"temporary",
"table",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L74-L85 | train | 48,375 |
ajenhl/tacl | tacl/data_store.py | DataStore._add_temporary_results | def _add_temporary_results(self, results, label):
"""Adds `results` to a temporary table with `label`.
:param results: results file
:type results: `File`
:param label: label to be associated with results
:type label: `str`
"""
NGRAM, SIZE, NAME, SIGLUM, COUNT, LABEL = constants.QUERY_FIELDNAMES
reader = csv.DictReader(results)
data = [(row[NGRAM], row[SIZE], row[NAME], row[SIGLUM], row[COUNT],
label) for row in reader]
self._conn.executemany(constants.INSERT_TEMPORARY_RESULTS_SQL, data) | python | def _add_temporary_results(self, results, label):
"""Adds `results` to a temporary table with `label`.
:param results: results file
:type results: `File`
:param label: label to be associated with results
:type label: `str`
"""
NGRAM, SIZE, NAME, SIGLUM, COUNT, LABEL = constants.QUERY_FIELDNAMES
reader = csv.DictReader(results)
data = [(row[NGRAM], row[SIZE], row[NAME], row[SIGLUM], row[COUNT],
label) for row in reader]
self._conn.executemany(constants.INSERT_TEMPORARY_RESULTS_SQL, data) | [
"def",
"_add_temporary_results",
"(",
"self",
",",
"results",
",",
"label",
")",
":",
"NGRAM",
",",
"SIZE",
",",
"NAME",
",",
"SIGLUM",
",",
"COUNT",
",",
"LABEL",
"=",
"constants",
".",
"QUERY_FIELDNAMES",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"... | Adds `results` to a temporary table with `label`.
:param results: results file
:type results: `File`
:param label: label to be associated with results
:type label: `str` | [
"Adds",
"results",
"to",
"a",
"temporary",
"table",
"with",
"label",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L101-L114 | train | 48,376 |
ajenhl/tacl | tacl/data_store.py | DataStore._add_text_ngrams | def _add_text_ngrams(self, witness, minimum, maximum):
"""Adds n-gram data from `witness` to the data store.
:param witness: witness to get n-grams from
:type witness: `WitnessText`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
"""
text_id = self._get_text_id(witness)
self._logger.info('Adding n-grams ({} <= n <= {}) for {}'.format(
minimum, maximum, witness.get_filename()))
skip_sizes = []
for size in range(minimum, maximum + 1):
if self._has_ngrams(text_id, size):
self._logger.info(
'{}-grams are already in the database'.format(size))
skip_sizes.append(size)
for size, ngrams in witness.get_ngrams(minimum, maximum, skip_sizes):
self._add_text_size_ngrams(text_id, size, ngrams) | python | def _add_text_ngrams(self, witness, minimum, maximum):
"""Adds n-gram data from `witness` to the data store.
:param witness: witness to get n-grams from
:type witness: `WitnessText`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int`
"""
text_id = self._get_text_id(witness)
self._logger.info('Adding n-grams ({} <= n <= {}) for {}'.format(
minimum, maximum, witness.get_filename()))
skip_sizes = []
for size in range(minimum, maximum + 1):
if self._has_ngrams(text_id, size):
self._logger.info(
'{}-grams are already in the database'.format(size))
skip_sizes.append(size)
for size, ngrams in witness.get_ngrams(minimum, maximum, skip_sizes):
self._add_text_size_ngrams(text_id, size, ngrams) | [
"def",
"_add_text_ngrams",
"(",
"self",
",",
"witness",
",",
"minimum",
",",
"maximum",
")",
":",
"text_id",
"=",
"self",
".",
"_get_text_id",
"(",
"witness",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding n-grams ({} <= n <= {}) for {}'",
".",
"forma... | Adds n-gram data from `witness` to the data store.
:param witness: witness to get n-grams from
:type witness: `WitnessText`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram size
:type maximum: `int` | [
"Adds",
"n",
"-",
"gram",
"data",
"from",
"witness",
"to",
"the",
"data",
"store",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L121-L142 | train | 48,377 |
ajenhl/tacl | tacl/data_store.py | DataStore._add_text_record | def _add_text_record(self, witness):
"""Adds a Text record for `witness`.
:param witness: witness to add a record for
:type text: `WitnessText`
"""
filename = witness.get_filename()
name, siglum = witness.get_names()
self._logger.info('Adding record for text {}'.format(filename))
checksum = witness.get_checksum()
token_count = len(witness.get_tokens())
with self._conn:
cursor = self._conn.execute(
constants.INSERT_TEXT_SQL,
[name, siglum, checksum, token_count, ''])
return cursor.lastrowid | python | def _add_text_record(self, witness):
"""Adds a Text record for `witness`.
:param witness: witness to add a record for
:type text: `WitnessText`
"""
filename = witness.get_filename()
name, siglum = witness.get_names()
self._logger.info('Adding record for text {}'.format(filename))
checksum = witness.get_checksum()
token_count = len(witness.get_tokens())
with self._conn:
cursor = self._conn.execute(
constants.INSERT_TEXT_SQL,
[name, siglum, checksum, token_count, ''])
return cursor.lastrowid | [
"def",
"_add_text_record",
"(",
"self",
",",
"witness",
")",
":",
"filename",
"=",
"witness",
".",
"get_filename",
"(",
")",
"name",
",",
"siglum",
"=",
"witness",
".",
"get_names",
"(",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding record for te... | Adds a Text record for `witness`.
:param witness: witness to add a record for
:type text: `WitnessText` | [
"Adds",
"a",
"Text",
"record",
"for",
"witness",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L144-L160 | train | 48,378 |
ajenhl/tacl | tacl/data_store.py | DataStore._add_text_size_ngrams | def _add_text_size_ngrams(self, text_id, size, ngrams):
"""Adds `ngrams`, that are of size `size`, to the data store.
The added `ngrams` are associated with `text_id`.
:param text_id: database ID of text associated with `ngrams`
:type text_id: `int`
:param size: size of n-grams
:type size: `int`
:param ngrams: n-grams to be added
:type ngrams: `collections.Counter`
"""
unique_ngrams = len(ngrams)
self._logger.info('Adding {} unique {}-grams'.format(
unique_ngrams, size))
parameters = [[text_id, ngram, size, count]
for ngram, count in ngrams.items()]
with self._conn:
self._conn.execute(constants.INSERT_TEXT_HAS_NGRAM_SQL,
[text_id, size, unique_ngrams])
self._conn.executemany(constants.INSERT_NGRAM_SQL, parameters) | python | def _add_text_size_ngrams(self, text_id, size, ngrams):
"""Adds `ngrams`, that are of size `size`, to the data store.
The added `ngrams` are associated with `text_id`.
:param text_id: database ID of text associated with `ngrams`
:type text_id: `int`
:param size: size of n-grams
:type size: `int`
:param ngrams: n-grams to be added
:type ngrams: `collections.Counter`
"""
unique_ngrams = len(ngrams)
self._logger.info('Adding {} unique {}-grams'.format(
unique_ngrams, size))
parameters = [[text_id, ngram, size, count]
for ngram, count in ngrams.items()]
with self._conn:
self._conn.execute(constants.INSERT_TEXT_HAS_NGRAM_SQL,
[text_id, size, unique_ngrams])
self._conn.executemany(constants.INSERT_NGRAM_SQL, parameters) | [
"def",
"_add_text_size_ngrams",
"(",
"self",
",",
"text_id",
",",
"size",
",",
"ngrams",
")",
":",
"unique_ngrams",
"=",
"len",
"(",
"ngrams",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding {} unique {}-grams'",
".",
"format",
"(",
"unique_ngrams",
... | Adds `ngrams`, that are of size `size`, to the data store.
The added `ngrams` are associated with `text_id`.
:param text_id: database ID of text associated with `ngrams`
:type text_id: `int`
:param size: size of n-grams
:type size: `int`
:param ngrams: n-grams to be added
:type ngrams: `collections.Counter` | [
"Adds",
"ngrams",
"that",
"are",
"of",
"size",
"size",
"to",
"the",
"data",
"store",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L162-L183 | train | 48,379 |
ajenhl/tacl | tacl/data_store.py | DataStore._analyse | def _analyse(self, table=''):
"""Analyses the database, or `table` if it is supplied.
:param table: optional name of table to analyse
:type table: `str`
"""
self._logger.info('Starting analysis of database')
self._conn.execute(constants.ANALYSE_SQL.format(table))
self._logger.info('Analysis of database complete') | python | def _analyse(self, table=''):
"""Analyses the database, or `table` if it is supplied.
:param table: optional name of table to analyse
:type table: `str`
"""
self._logger.info('Starting analysis of database')
self._conn.execute(constants.ANALYSE_SQL.format(table))
self._logger.info('Analysis of database complete') | [
"def",
"_analyse",
"(",
"self",
",",
"table",
"=",
"''",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Starting analysis of database'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"ANALYSE_SQL",
".",
"format",
"(",
"table",
... | Analyses the database, or `table` if it is supplied.
:param table: optional name of table to analyse
:type table: `str` | [
"Analyses",
"the",
"database",
"or",
"table",
"if",
"it",
"is",
"supplied",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L185-L194 | train | 48,380 |
ajenhl/tacl | tacl/data_store.py | DataStore._check_diff_result | def _check_diff_result(row, matches, tokenize, join):
"""Returns `row`, possibly with its count changed to 0, depending on
the status of the n-grams that compose it.
The n-gram represented in `row` can be decomposed into two
(n-1)-grams. If neither sub-n-gram is present in `matches`, do
not change the count since this is a new difference.
If both sub-n-grams are present with a positive count, do not
change the count as it is composed entirely of sub-ngrams and
therefore not filler.
Otherwise, change the count to 0 as the n-gram is filler.
:param row: result row of the n-gram to check
:type row: pandas.Series
:param matches: (n-1)-grams and their associated counts to check
against
:type matches: `dict`
:param tokenize: function to tokenize a string
:type tokenize: `function`
:param join: function to join tokens into a string
:type join: `function`
:rtype: pandas.Series
"""
ngram_tokens = tokenize(row[constants.NGRAM_FIELDNAME])
sub_ngram1 = join(ngram_tokens[:-1])
sub_ngram2 = join(ngram_tokens[1:])
count = constants.COUNT_FIELDNAME
discard = False
# For performance reasons, avoid searching through matches
# unless necessary.
status1 = matches.get(sub_ngram1)
if status1 == 0:
discard = True
else:
status2 = matches.get(sub_ngram2)
if status2 == 0:
discard = True
elif (status1 is None) ^ (status2 is None):
discard = True
if discard:
row[count] = 0
return row | python | def _check_diff_result(row, matches, tokenize, join):
"""Returns `row`, possibly with its count changed to 0, depending on
the status of the n-grams that compose it.
The n-gram represented in `row` can be decomposed into two
(n-1)-grams. If neither sub-n-gram is present in `matches`, do
not change the count since this is a new difference.
If both sub-n-grams are present with a positive count, do not
change the count as it is composed entirely of sub-ngrams and
therefore not filler.
Otherwise, change the count to 0 as the n-gram is filler.
:param row: result row of the n-gram to check
:type row: pandas.Series
:param matches: (n-1)-grams and their associated counts to check
against
:type matches: `dict`
:param tokenize: function to tokenize a string
:type tokenize: `function`
:param join: function to join tokens into a string
:type join: `function`
:rtype: pandas.Series
"""
ngram_tokens = tokenize(row[constants.NGRAM_FIELDNAME])
sub_ngram1 = join(ngram_tokens[:-1])
sub_ngram2 = join(ngram_tokens[1:])
count = constants.COUNT_FIELDNAME
discard = False
# For performance reasons, avoid searching through matches
# unless necessary.
status1 = matches.get(sub_ngram1)
if status1 == 0:
discard = True
else:
status2 = matches.get(sub_ngram2)
if status2 == 0:
discard = True
elif (status1 is None) ^ (status2 is None):
discard = True
if discard:
row[count] = 0
return row | [
"def",
"_check_diff_result",
"(",
"row",
",",
"matches",
",",
"tokenize",
",",
"join",
")",
":",
"ngram_tokens",
"=",
"tokenize",
"(",
"row",
"[",
"constants",
".",
"NGRAM_FIELDNAME",
"]",
")",
"sub_ngram1",
"=",
"join",
"(",
"ngram_tokens",
"[",
":",
"-",... | Returns `row`, possibly with its count changed to 0, depending on
the status of the n-grams that compose it.
The n-gram represented in `row` can be decomposed into two
(n-1)-grams. If neither sub-n-gram is present in `matches`, do
not change the count since this is a new difference.
If both sub-n-grams are present with a positive count, do not
change the count as it is composed entirely of sub-ngrams and
therefore not filler.
Otherwise, change the count to 0 as the n-gram is filler.
:param row: result row of the n-gram to check
:type row: pandas.Series
:param matches: (n-1)-grams and their associated counts to check
against
:type matches: `dict`
:param tokenize: function to tokenize a string
:type tokenize: `function`
:param join: function to join tokens into a string
:type join: `function`
:rtype: pandas.Series | [
"Returns",
"row",
"possibly",
"with",
"its",
"count",
"changed",
"to",
"0",
"depending",
"on",
"the",
"status",
"of",
"the",
"n",
"-",
"grams",
"that",
"compose",
"it",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L197-L241 | train | 48,381 |
ajenhl/tacl | tacl/data_store.py | DataStore.counts | def counts(self, catalogue, output_fh):
"""Returns `output_fh` populated with CSV results giving
n-gram counts of the witnesses of the works in `catalogue`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = list(self._set_labels(catalogue))
label_placeholders = self._get_placeholders(labels)
query = constants.SELECT_COUNTS_SQL.format(label_placeholders)
self._logger.info('Running counts query')
self._logger.debug('Query: {}\nLabels: {}'.format(query, labels))
cursor = self._conn.execute(query, labels)
return self._csv(cursor, constants.COUNTS_FIELDNAMES, output_fh) | python | def counts(self, catalogue, output_fh):
"""Returns `output_fh` populated with CSV results giving
n-gram counts of the witnesses of the works in `catalogue`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = list(self._set_labels(catalogue))
label_placeholders = self._get_placeholders(labels)
query = constants.SELECT_COUNTS_SQL.format(label_placeholders)
self._logger.info('Running counts query')
self._logger.debug('Query: {}\nLabels: {}'.format(query, labels))
cursor = self._conn.execute(query, labels)
return self._csv(cursor, constants.COUNTS_FIELDNAMES, output_fh) | [
"def",
"counts",
"(",
"self",
",",
"catalogue",
",",
"output_fh",
")",
":",
"labels",
"=",
"list",
"(",
"self",
".",
"_set_labels",
"(",
"catalogue",
")",
")",
"label_placeholders",
"=",
"self",
".",
"_get_placeholders",
"(",
"labels",
")",
"query",
"=",
... | Returns `output_fh` populated with CSV results giving
n-gram counts of the witnesses of the works in `catalogue`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"giving",
"n",
"-",
"gram",
"counts",
"of",
"the",
"witnesses",
"of",
"the",
"works",
"in",
"catalogue",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L243-L260 | train | 48,382 |
ajenhl/tacl | tacl/data_store.py | DataStore._csv | def _csv(self, cursor, fieldnames, output_fh):
"""Writes the rows of `cursor` in CSV format to `output_fh`
and returns it.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:param output_fh: file to write data to
:type output_fh: file object
:rtype: file object
"""
self._logger.info('Finished query; outputting results in CSV format')
# Specify a lineterminator to avoid an extra \r being added on
# Windows; see
# https://stackoverflow.com/questions/3191528/csv-in-python-adding-extra-carriage-return
if sys.platform in ('win32', 'cygwin') and output_fh is sys.stdout:
writer = csv.writer(output_fh, lineterminator='\n')
else:
writer = csv.writer(output_fh)
writer.writerow(fieldnames)
for row in cursor:
writer.writerow(row)
self._logger.info('Finished outputting results')
return output_fh | python | def _csv(self, cursor, fieldnames, output_fh):
"""Writes the rows of `cursor` in CSV format to `output_fh`
and returns it.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:param output_fh: file to write data to
:type output_fh: file object
:rtype: file object
"""
self._logger.info('Finished query; outputting results in CSV format')
# Specify a lineterminator to avoid an extra \r being added on
# Windows; see
# https://stackoverflow.com/questions/3191528/csv-in-python-adding-extra-carriage-return
if sys.platform in ('win32', 'cygwin') and output_fh is sys.stdout:
writer = csv.writer(output_fh, lineterminator='\n')
else:
writer = csv.writer(output_fh)
writer.writerow(fieldnames)
for row in cursor:
writer.writerow(row)
self._logger.info('Finished outputting results')
return output_fh | [
"def",
"_csv",
"(",
"self",
",",
"cursor",
",",
"fieldnames",
",",
"output_fh",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Finished query; outputting results in CSV format'",
")",
"# Specify a lineterminator to avoid an extra \\r being added on",
"# Windows; see"... | Writes the rows of `cursor` in CSV format to `output_fh`
and returns it.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:param output_fh: file to write data to
:type output_fh: file object
:rtype: file object | [
"Writes",
"the",
"rows",
"of",
"cursor",
"in",
"CSV",
"format",
"to",
"output_fh",
"and",
"returns",
"it",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L266-L291 | train | 48,383 |
ajenhl/tacl | tacl/data_store.py | DataStore._csv_temp | def _csv_temp(self, cursor, fieldnames):
"""Writes the rows of `cursor` in CSV format to a temporary file and
returns the path to that file.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:rtype: `str`
"""
temp_fd, temp_path = tempfile.mkstemp(text=True)
with open(temp_fd, 'w', encoding='utf-8', newline='') as results_fh:
self._csv(cursor, fieldnames, results_fh)
return temp_path | python | def _csv_temp(self, cursor, fieldnames):
"""Writes the rows of `cursor` in CSV format to a temporary file and
returns the path to that file.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:rtype: `str`
"""
temp_fd, temp_path = tempfile.mkstemp(text=True)
with open(temp_fd, 'w', encoding='utf-8', newline='') as results_fh:
self._csv(cursor, fieldnames, results_fh)
return temp_path | [
"def",
"_csv_temp",
"(",
"self",
",",
"cursor",
",",
"fieldnames",
")",
":",
"temp_fd",
",",
"temp_path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"text",
"=",
"True",
")",
"with",
"open",
"(",
"temp_fd",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
",",
... | Writes the rows of `cursor` in CSV format to a temporary file and
returns the path to that file.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type fieldnames: `list`
:rtype: `str` | [
"Writes",
"the",
"rows",
"of",
"cursor",
"in",
"CSV",
"format",
"to",
"a",
"temporary",
"file",
"and",
"returns",
"the",
"path",
"to",
"that",
"file",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L293-L307 | train | 48,384 |
ajenhl/tacl | tacl/data_store.py | DataStore._delete_text_ngrams | def _delete_text_ngrams(self, text_id):
"""Deletes all n-grams associated with `text_id` from the data
store.
:param text_id: database ID of text
:type text_id: `int`
"""
with self._conn:
self._conn.execute(constants.DELETE_TEXT_NGRAMS_SQL, [text_id])
self._conn.execute(constants.DELETE_TEXT_HAS_NGRAMS_SQL, [text_id]) | python | def _delete_text_ngrams(self, text_id):
"""Deletes all n-grams associated with `text_id` from the data
store.
:param text_id: database ID of text
:type text_id: `int`
"""
with self._conn:
self._conn.execute(constants.DELETE_TEXT_NGRAMS_SQL, [text_id])
self._conn.execute(constants.DELETE_TEXT_HAS_NGRAMS_SQL, [text_id]) | [
"def",
"_delete_text_ngrams",
"(",
"self",
",",
"text_id",
")",
":",
"with",
"self",
".",
"_conn",
":",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"DELETE_TEXT_NGRAMS_SQL",
",",
"[",
"text_id",
"]",
")",
"self",
".",
"_conn",
".",
"exec... | Deletes all n-grams associated with `text_id` from the data
store.
:param text_id: database ID of text
:type text_id: `int` | [
"Deletes",
"all",
"n",
"-",
"grams",
"associated",
"with",
"text_id",
"from",
"the",
"data",
"store",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L309-L319 | train | 48,385 |
ajenhl/tacl | tacl/data_store.py | DataStore._diff | def _diff(self, cursor, tokenizer, output_fh):
"""Returns output_fh with diff results that have been reduced.
Uses a temporary file to store the results from `cursor`
before being reduced, in order to not have the results stored
in memory twice.
:param cursor: database cursor containing raw diff data
:type cursor: `sqlite3.Cursor`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:type output_fh: file-like object
:rtype: file-like object
"""
temp_path = self._csv_temp(cursor, constants.QUERY_FIELDNAMES)
output_fh = self._reduce_diff_results(temp_path, tokenizer, output_fh)
try:
os.remove(temp_path)
except OSError as e:
self._logger.error('Failed to remove temporary file containing '
'unreduced results: {}'.format(e))
return output_fh | python | def _diff(self, cursor, tokenizer, output_fh):
"""Returns output_fh with diff results that have been reduced.
Uses a temporary file to store the results from `cursor`
before being reduced, in order to not have the results stored
in memory twice.
:param cursor: database cursor containing raw diff data
:type cursor: `sqlite3.Cursor`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:type output_fh: file-like object
:rtype: file-like object
"""
temp_path = self._csv_temp(cursor, constants.QUERY_FIELDNAMES)
output_fh = self._reduce_diff_results(temp_path, tokenizer, output_fh)
try:
os.remove(temp_path)
except OSError as e:
self._logger.error('Failed to remove temporary file containing '
'unreduced results: {}'.format(e))
return output_fh | [
"def",
"_diff",
"(",
"self",
",",
"cursor",
",",
"tokenizer",
",",
"output_fh",
")",
":",
"temp_path",
"=",
"self",
".",
"_csv_temp",
"(",
"cursor",
",",
"constants",
".",
"QUERY_FIELDNAMES",
")",
"output_fh",
"=",
"self",
".",
"_reduce_diff_results",
"(",
... | Returns output_fh with diff results that have been reduced.
Uses a temporary file to store the results from `cursor`
before being reduced, in order to not have the results stored
in memory twice.
:param cursor: database cursor containing raw diff data
:type cursor: `sqlite3.Cursor`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"with",
"diff",
"results",
"that",
"have",
"been",
"reduced",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L321-L343 | train | 48,386 |
ajenhl/tacl | tacl/data_store.py | DataStore.diff | def diff(self, catalogue, tokenizer, output_fh):
"""Returns `output_fh` populated with CSV results giving the n-grams
that are unique to the witnesses of each labelled set of works
in `catalogue`.
Note that this is not the same as the symmetric difference of
these sets, except in the case where there are only two
labels.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = self._sort_labels(self._set_labels(catalogue))
if len(labels) < 2:
raise MalformedQueryError(
constants.INSUFFICIENT_LABELS_QUERY_ERROR)
label_placeholders = self._get_placeholders(labels)
query = constants.SELECT_DIFF_SQL.format(label_placeholders,
label_placeholders)
parameters = labels + labels
self._logger.info('Running diff query')
self._logger.debug('Query: {}\nLabels: {}'.format(query, labels))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._diff(cursor, tokenizer, output_fh) | python | def diff(self, catalogue, tokenizer, output_fh):
"""Returns `output_fh` populated with CSV results giving the n-grams
that are unique to the witnesses of each labelled set of works
in `catalogue`.
Note that this is not the same as the symmetric difference of
these sets, except in the case where there are only two
labels.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = self._sort_labels(self._set_labels(catalogue))
if len(labels) < 2:
raise MalformedQueryError(
constants.INSUFFICIENT_LABELS_QUERY_ERROR)
label_placeholders = self._get_placeholders(labels)
query = constants.SELECT_DIFF_SQL.format(label_placeholders,
label_placeholders)
parameters = labels + labels
self._logger.info('Running diff query')
self._logger.debug('Query: {}\nLabels: {}'.format(query, labels))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._diff(cursor, tokenizer, output_fh) | [
"def",
"diff",
"(",
"self",
",",
"catalogue",
",",
"tokenizer",
",",
"output_fh",
")",
":",
"labels",
"=",
"self",
".",
"_sort_labels",
"(",
"self",
".",
"_set_labels",
"(",
"catalogue",
")",
")",
"if",
"len",
"(",
"labels",
")",
"<",
"2",
":",
"rais... | Returns `output_fh` populated with CSV results giving the n-grams
that are unique to the witnesses of each labelled set of works
in `catalogue`.
Note that this is not the same as the symmetric difference of
these sets, except in the case where there are only two
labels.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"giving",
"the",
"n",
"-",
"grams",
"that",
"are",
"unique",
"to",
"the",
"witnesses",
"of",
"each",
"labelled",
"set",
"of",
"works",
"in",
"catalogue",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L345-L375 | train | 48,387 |
ajenhl/tacl | tacl/data_store.py | DataStore.diff_asymmetric | def diff_asymmetric(self, catalogue, prime_label, tokenizer, output_fh):
"""Returns `output_fh` populated with CSV results giving the
difference in n-grams between the witnesses of labelled sets
of works in `catalogue`, limited to those works labelled with
`prime_label`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param prime_label: label to limit results to
:type prime_label: `str`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = list(self._set_labels(catalogue))
if len(labels) < 2:
raise MalformedQueryError(
constants.INSUFFICIENT_LABELS_QUERY_ERROR)
try:
labels.remove(prime_label)
except ValueError:
raise MalformedQueryError(constants.LABEL_NOT_IN_CATALOGUE_ERROR)
label_placeholders = self._get_placeholders(labels)
query = constants.SELECT_DIFF_ASYMMETRIC_SQL.format(label_placeholders)
parameters = [prime_label, prime_label] + labels
self._logger.info('Running asymmetric diff query')
self._logger.debug('Query: {}\nLabels: {}\nPrime label: {}'.format(
query, labels, prime_label))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._diff(cursor, tokenizer, output_fh) | python | def diff_asymmetric(self, catalogue, prime_label, tokenizer, output_fh):
"""Returns `output_fh` populated with CSV results giving the
difference in n-grams between the witnesses of labelled sets
of works in `catalogue`, limited to those works labelled with
`prime_label`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param prime_label: label to limit results to
:type prime_label: `str`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = list(self._set_labels(catalogue))
if len(labels) < 2:
raise MalformedQueryError(
constants.INSUFFICIENT_LABELS_QUERY_ERROR)
try:
labels.remove(prime_label)
except ValueError:
raise MalformedQueryError(constants.LABEL_NOT_IN_CATALOGUE_ERROR)
label_placeholders = self._get_placeholders(labels)
query = constants.SELECT_DIFF_ASYMMETRIC_SQL.format(label_placeholders)
parameters = [prime_label, prime_label] + labels
self._logger.info('Running asymmetric diff query')
self._logger.debug('Query: {}\nLabels: {}\nPrime label: {}'.format(
query, labels, prime_label))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._diff(cursor, tokenizer, output_fh) | [
"def",
"diff_asymmetric",
"(",
"self",
",",
"catalogue",
",",
"prime_label",
",",
"tokenizer",
",",
"output_fh",
")",
":",
"labels",
"=",
"list",
"(",
"self",
".",
"_set_labels",
"(",
"catalogue",
")",
")",
"if",
"len",
"(",
"labels",
")",
"<",
"2",
":... | Returns `output_fh` populated with CSV results giving the
difference in n-grams between the witnesses of labelled sets
of works in `catalogue`, limited to those works labelled with
`prime_label`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param prime_label: label to limit results to
:type prime_label: `str`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"giving",
"the",
"difference",
"in",
"n",
"-",
"grams",
"between",
"the",
"witnesses",
"of",
"labelled",
"sets",
"of",
"works",
"in",
"catalogue",
"limited",
"to",
"those",
"works",
"labelled",
"wi... | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L377-L410 | train | 48,388 |
ajenhl/tacl | tacl/data_store.py | DataStore.diff_supplied | def diff_supplied(self, results_filenames, labels, tokenizer, output_fh):
"""Returns `output_fh` populated with CSV results giving the n-grams
that are unique to the witnesses in each set of works in
`results_sets`, using the labels in `labels`.
Note that this is not the same as the symmetric difference of
these sets, except in the case where there are only two
labels.
:param results_filenames: list of results filenames to be diffed
:type results_filenames: `list` of `str`
:param labels: labels to be applied to the results_sets
:type labels: `list`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
self._add_temporary_results_sets(results_filenames, labels)
query = constants.SELECT_DIFF_SUPPLIED_SQL
self._logger.info('Running supplied diff query')
self._logger.debug('Query: {}'.format(query))
self._log_query_plan(query, [])
cursor = self._conn.execute(query)
return self._diff(cursor, tokenizer, output_fh) | python | def diff_supplied(self, results_filenames, labels, tokenizer, output_fh):
"""Returns `output_fh` populated with CSV results giving the n-grams
that are unique to the witnesses in each set of works in
`results_sets`, using the labels in `labels`.
Note that this is not the same as the symmetric difference of
these sets, except in the case where there are only two
labels.
:param results_filenames: list of results filenames to be diffed
:type results_filenames: `list` of `str`
:param labels: labels to be applied to the results_sets
:type labels: `list`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
self._add_temporary_results_sets(results_filenames, labels)
query = constants.SELECT_DIFF_SUPPLIED_SQL
self._logger.info('Running supplied diff query')
self._logger.debug('Query: {}'.format(query))
self._log_query_plan(query, [])
cursor = self._conn.execute(query)
return self._diff(cursor, tokenizer, output_fh) | [
"def",
"diff_supplied",
"(",
"self",
",",
"results_filenames",
",",
"labels",
",",
"tokenizer",
",",
"output_fh",
")",
":",
"self",
".",
"_add_temporary_results_sets",
"(",
"results_filenames",
",",
"labels",
")",
"query",
"=",
"constants",
".",
"SELECT_DIFF_SUPPL... | Returns `output_fh` populated with CSV results giving the n-grams
that are unique to the witnesses in each set of works in
`results_sets`, using the labels in `labels`.
Note that this is not the same as the symmetric difference of
these sets, except in the case where there are only two
labels.
:param results_filenames: list of results filenames to be diffed
:type results_filenames: `list` of `str`
:param labels: labels to be applied to the results_sets
:type labels: `list`
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"giving",
"the",
"n",
"-",
"grams",
"that",
"are",
"unique",
"to",
"the",
"witnesses",
"in",
"each",
"set",
"of",
"works",
"in",
"results_sets",
"using",
"the",
"labels",
"in",
"labels",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L412-L438 | train | 48,389 |
ajenhl/tacl | tacl/data_store.py | DataStore._drop_indices | def _drop_indices(self):
"""Drops the database indices relating to n-grams."""
self._logger.info('Dropping database indices')
self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL)
self._logger.info('Finished dropping database indices') | python | def _drop_indices(self):
"""Drops the database indices relating to n-grams."""
self._logger.info('Dropping database indices')
self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL)
self._logger.info('Finished dropping database indices') | [
"def",
"_drop_indices",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Dropping database indices'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"DROP_TEXTNGRAM_INDEX_SQL",
")",
"self",
".",
"_logger",
".",
"info",
"(... | Drops the database indices relating to n-grams. | [
"Drops",
"the",
"database",
"indices",
"relating",
"to",
"n",
"-",
"grams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L440-L444 | train | 48,390 |
ajenhl/tacl | tacl/data_store.py | DataStore._get_text_id | def _get_text_id(self, witness):
"""Returns the database ID of the Text record for `witness`.
This may require creating such a record.
If `text`\'s checksum does not match an existing record's
checksum, the record's checksum is updated and all associated
TextNGram and TextHasNGram records are deleted.
:param witness: witness to add a record for
:type witness: `WitnessText`
:rtype: `int`
"""
name, siglum = witness.get_names()
text_record = self._conn.execute(constants.SELECT_TEXT_SQL,
[name, siglum]).fetchone()
if text_record is None:
text_id = self._add_text_record(witness)
else:
text_id = text_record['id']
if text_record['checksum'] != witness.get_checksum():
filename = witness.get_filename()
self._logger.info('Text {} has changed since it was added to '
'the database'.format(filename))
self._update_text_record(witness, text_id)
self._logger.info('Deleting potentially out-of-date n-grams')
self._delete_text_ngrams(text_id)
return text_id | python | def _get_text_id(self, witness):
"""Returns the database ID of the Text record for `witness`.
This may require creating such a record.
If `text`\'s checksum does not match an existing record's
checksum, the record's checksum is updated and all associated
TextNGram and TextHasNGram records are deleted.
:param witness: witness to add a record for
:type witness: `WitnessText`
:rtype: `int`
"""
name, siglum = witness.get_names()
text_record = self._conn.execute(constants.SELECT_TEXT_SQL,
[name, siglum]).fetchone()
if text_record is None:
text_id = self._add_text_record(witness)
else:
text_id = text_record['id']
if text_record['checksum'] != witness.get_checksum():
filename = witness.get_filename()
self._logger.info('Text {} has changed since it was added to '
'the database'.format(filename))
self._update_text_record(witness, text_id)
self._logger.info('Deleting potentially out-of-date n-grams')
self._delete_text_ngrams(text_id)
return text_id | [
"def",
"_get_text_id",
"(",
"self",
",",
"witness",
")",
":",
"name",
",",
"siglum",
"=",
"witness",
".",
"get_names",
"(",
")",
"text_record",
"=",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"SELECT_TEXT_SQL",
",",
"[",
"name",
",",
... | Returns the database ID of the Text record for `witness`.
This may require creating such a record.
If `text`\'s checksum does not match an existing record's
checksum, the record's checksum is updated and all associated
TextNGram and TextHasNGram records are deleted.
:param witness: witness to add a record for
:type witness: `WitnessText`
:rtype: `int` | [
"Returns",
"the",
"database",
"ID",
"of",
"the",
"Text",
"record",
"for",
"witness",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L471-L499 | train | 48,391 |
ajenhl/tacl | tacl/data_store.py | DataStore._has_ngrams | def _has_ngrams(self, text_id, size):
"""Returns True if a text has existing records for n-grams of
size `size`.
:param text_id: database ID of text to check
:type text_id: `int`
:param size: size of n-grams
:type size: `int`
:rtype: `bool`
"""
if self._conn.execute(constants.SELECT_HAS_NGRAMS_SQL,
[text_id, size]).fetchone() is None:
return False
return True | python | def _has_ngrams(self, text_id, size):
"""Returns True if a text has existing records for n-grams of
size `size`.
:param text_id: database ID of text to check
:type text_id: `int`
:param size: size of n-grams
:type size: `int`
:rtype: `bool`
"""
if self._conn.execute(constants.SELECT_HAS_NGRAMS_SQL,
[text_id, size]).fetchone() is None:
return False
return True | [
"def",
"_has_ngrams",
"(",
"self",
",",
"text_id",
",",
"size",
")",
":",
"if",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"SELECT_HAS_NGRAMS_SQL",
",",
"[",
"text_id",
",",
"size",
"]",
")",
".",
"fetchone",
"(",
")",
"is",
"None",
... | Returns True if a text has existing records for n-grams of
size `size`.
:param text_id: database ID of text to check
:type text_id: `int`
:param size: size of n-grams
:type size: `int`
:rtype: `bool` | [
"Returns",
"True",
"if",
"a",
"text",
"has",
"existing",
"records",
"for",
"n",
"-",
"grams",
"of",
"size",
"size",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L501-L515 | train | 48,392 |
ajenhl/tacl | tacl/data_store.py | DataStore.intersection | def intersection(self, catalogue, output_fh):
"""Returns `output_fh` populated with CSV results giving the
intersection in n-grams of the witnesses of labelled sets of
works in `catalogue`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = self._sort_labels(self._set_labels(catalogue))
if len(labels) < 2:
raise MalformedQueryError(
constants.INSUFFICIENT_LABELS_QUERY_ERROR)
label_placeholders = self._get_placeholders(labels)
subquery = self._get_intersection_subquery(labels)
query = constants.SELECT_INTERSECT_SQL.format(label_placeholders,
subquery)
parameters = labels + labels
self._logger.info('Running intersection query')
self._logger.debug('Query: {}\nLabels: {}'.format(query, labels))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._csv(cursor, constants.QUERY_FIELDNAMES, output_fh) | python | def intersection(self, catalogue, output_fh):
"""Returns `output_fh` populated with CSV results giving the
intersection in n-grams of the witnesses of labelled sets of
works in `catalogue`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = self._sort_labels(self._set_labels(catalogue))
if len(labels) < 2:
raise MalformedQueryError(
constants.INSUFFICIENT_LABELS_QUERY_ERROR)
label_placeholders = self._get_placeholders(labels)
subquery = self._get_intersection_subquery(labels)
query = constants.SELECT_INTERSECT_SQL.format(label_placeholders,
subquery)
parameters = labels + labels
self._logger.info('Running intersection query')
self._logger.debug('Query: {}\nLabels: {}'.format(query, labels))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._csv(cursor, constants.QUERY_FIELDNAMES, output_fh) | [
"def",
"intersection",
"(",
"self",
",",
"catalogue",
",",
"output_fh",
")",
":",
"labels",
"=",
"self",
".",
"_sort_labels",
"(",
"self",
".",
"_set_labels",
"(",
"catalogue",
")",
")",
"if",
"len",
"(",
"labels",
")",
"<",
"2",
":",
"raise",
"Malform... | Returns `output_fh` populated with CSV results giving the
intersection in n-grams of the witnesses of labelled sets of
works in `catalogue`.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"giving",
"the",
"intersection",
"in",
"n",
"-",
"grams",
"of",
"the",
"witnesses",
"of",
"labelled",
"sets",
"of",
"works",
"in",
"catalogue",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L531-L556 | train | 48,393 |
ajenhl/tacl | tacl/data_store.py | DataStore.intersection_supplied | def intersection_supplied(self, results_filenames, labels, output_fh):
"""Returns `output_fh` populated with CSV results giving the n-grams
that are common to witnesses in every set of works in
`results_sets`, using the labels in `labels`.
:param results_filenames: list of results to be diffed
:type results_filenames: `list` of `str`
:param labels: labels to be applied to the results_sets
:type labels: `list`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
self._add_temporary_results_sets(results_filenames, labels)
query = constants.SELECT_INTERSECT_SUPPLIED_SQL
parameters = [len(labels)]
self._logger.info('Running supplied intersect query')
self._logger.debug('Query: {}\nNumber of labels: {}'.format(
query, parameters[0]))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._csv(cursor, constants.QUERY_FIELDNAMES, output_fh) | python | def intersection_supplied(self, results_filenames, labels, output_fh):
"""Returns `output_fh` populated with CSV results giving the n-grams
that are common to witnesses in every set of works in
`results_sets`, using the labels in `labels`.
:param results_filenames: list of results to be diffed
:type results_filenames: `list` of `str`
:param labels: labels to be applied to the results_sets
:type labels: `list`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object
"""
self._add_temporary_results_sets(results_filenames, labels)
query = constants.SELECT_INTERSECT_SUPPLIED_SQL
parameters = [len(labels)]
self._logger.info('Running supplied intersect query')
self._logger.debug('Query: {}\nNumber of labels: {}'.format(
query, parameters[0]))
self._log_query_plan(query, parameters)
cursor = self._conn.execute(query, parameters)
return self._csv(cursor, constants.QUERY_FIELDNAMES, output_fh) | [
"def",
"intersection_supplied",
"(",
"self",
",",
"results_filenames",
",",
"labels",
",",
"output_fh",
")",
":",
"self",
".",
"_add_temporary_results_sets",
"(",
"results_filenames",
",",
"labels",
")",
"query",
"=",
"constants",
".",
"SELECT_INTERSECT_SUPPLIED_SQL",... | Returns `output_fh` populated with CSV results giving the n-grams
that are common to witnesses in every set of works in
`results_sets`, using the labels in `labels`.
:param results_filenames: list of results to be diffed
:type results_filenames: `list` of `str`
:param labels: labels to be applied to the results_sets
:type labels: `list`
:param output_fh: object to output results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"giving",
"the",
"n",
"-",
"grams",
"that",
"are",
"common",
"to",
"witnesses",
"in",
"every",
"set",
"of",
"works",
"in",
"results_sets",
"using",
"the",
"labels",
"in",
"labels",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L558-L580 | train | 48,394 |
ajenhl/tacl | tacl/data_store.py | DataStore._reduce_diff_results | def _reduce_diff_results(self, matches_path, tokenizer, output_fh):
"""Returns `output_fh` populated with a reduced set of data from
`matches_fh`.
Diff results typically contain a lot of filler results that
serve only to hide real differences. If one text has a single
extra token than another, the diff between them will have
results for every n-gram containing that extra token, which is
not helpful. This method removes these filler results by
'reducing down' the results.
:param matches_path: filepath or buffer of CSV results to be reduced
:type matches_path: `str` or file-like object
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to write results to
:type output_fh: file-like object
:rtype: file-like object
"""
self._logger.info('Removing filler results')
# For performance, perform the attribute accesses once.
tokenize = tokenizer.tokenize
join = tokenizer.joiner.join
results = []
previous_witness = (None, None)
previous_data = {}
# Calculate the index of ngram and count columns in a Pandas
# named tuple row, as used below. The +1 is due to the tuple
# having the row index as the first element.
ngram_index = constants.QUERY_FIELDNAMES.index(
constants.NGRAM_FIELDNAME) + 1
count_index = constants.QUERY_FIELDNAMES.index(
constants.COUNT_FIELDNAME) + 1
# Operate over individual witnesses and sizes, so that there
# is no possible results pollution between them.
grouped = pd.read_csv(matches_path, encoding='utf-8',
na_filter=False).groupby(
[constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME,
constants.SIZE_FIELDNAME])
for (work, siglum, size), group in grouped:
if (work, siglum) != previous_witness:
previous_matches = group
previous_witness = (work, siglum)
else:
self._logger.debug(
'Reducing down {} {}-grams for {} {}'.format(
len(group.index), size, work, siglum))
if previous_matches.empty:
reduced_count = 0
else:
previous_matches = group.apply(
self._check_diff_result, axis=1,
args=(previous_data, tokenize, join))
reduced_count = len(previous_matches[previous_matches[
constants.COUNT_FIELDNAME] != 0].index)
self._logger.debug('Reduced down to {} grams'.format(
reduced_count))
# Put the previous matches into a form that is more
# performant for the lookups made in _check_diff_result.
previous_data = {}
for row in previous_matches.itertuples():
previous_data[row[ngram_index]] = row[count_index]
if not previous_matches.empty:
results.append(previous_matches[previous_matches[
constants.COUNT_FIELDNAME] != 0])
reduced_results = pd.concat(results, ignore_index=True).reindex(
columns=constants.QUERY_FIELDNAMES)
reduced_results.to_csv(output_fh, encoding='utf-8', float_format='%d',
index=False)
return output_fh | python | def _reduce_diff_results(self, matches_path, tokenizer, output_fh):
"""Returns `output_fh` populated with a reduced set of data from
`matches_fh`.
Diff results typically contain a lot of filler results that
serve only to hide real differences. If one text has a single
extra token than another, the diff between them will have
results for every n-gram containing that extra token, which is
not helpful. This method removes these filler results by
'reducing down' the results.
:param matches_path: filepath or buffer of CSV results to be reduced
:type matches_path: `str` or file-like object
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to write results to
:type output_fh: file-like object
:rtype: file-like object
"""
self._logger.info('Removing filler results')
# For performance, perform the attribute accesses once.
tokenize = tokenizer.tokenize
join = tokenizer.joiner.join
results = []
previous_witness = (None, None)
previous_data = {}
# Calculate the index of ngram and count columns in a Pandas
# named tuple row, as used below. The +1 is due to the tuple
# having the row index as the first element.
ngram_index = constants.QUERY_FIELDNAMES.index(
constants.NGRAM_FIELDNAME) + 1
count_index = constants.QUERY_FIELDNAMES.index(
constants.COUNT_FIELDNAME) + 1
# Operate over individual witnesses and sizes, so that there
# is no possible results pollution between them.
grouped = pd.read_csv(matches_path, encoding='utf-8',
na_filter=False).groupby(
[constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME,
constants.SIZE_FIELDNAME])
for (work, siglum, size), group in grouped:
if (work, siglum) != previous_witness:
previous_matches = group
previous_witness = (work, siglum)
else:
self._logger.debug(
'Reducing down {} {}-grams for {} {}'.format(
len(group.index), size, work, siglum))
if previous_matches.empty:
reduced_count = 0
else:
previous_matches = group.apply(
self._check_diff_result, axis=1,
args=(previous_data, tokenize, join))
reduced_count = len(previous_matches[previous_matches[
constants.COUNT_FIELDNAME] != 0].index)
self._logger.debug('Reduced down to {} grams'.format(
reduced_count))
# Put the previous matches into a form that is more
# performant for the lookups made in _check_diff_result.
previous_data = {}
for row in previous_matches.itertuples():
previous_data[row[ngram_index]] = row[count_index]
if not previous_matches.empty:
results.append(previous_matches[previous_matches[
constants.COUNT_FIELDNAME] != 0])
reduced_results = pd.concat(results, ignore_index=True).reindex(
columns=constants.QUERY_FIELDNAMES)
reduced_results.to_csv(output_fh, encoding='utf-8', float_format='%d',
index=False)
return output_fh | [
"def",
"_reduce_diff_results",
"(",
"self",
",",
"matches_path",
",",
"tokenizer",
",",
"output_fh",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Removing filler results'",
")",
"# For performance, perform the attribute accesses once.",
"tokenize",
"=",
"tokeni... | Returns `output_fh` populated with a reduced set of data from
`matches_fh`.
Diff results typically contain a lot of filler results that
serve only to hide real differences. If one text has a single
extra token than another, the diff between them will have
results for every n-gram containing that extra token, which is
not helpful. This method removes these filler results by
'reducing down' the results.
:param matches_path: filepath or buffer of CSV results to be reduced
:type matches_path: `str` or file-like object
:param tokenizer: tokenizer for the n-grams
:type tokenizer: `Tokenizer`
:param output_fh: object to write results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"a",
"reduced",
"set",
"of",
"data",
"from",
"matches_fh",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L589-L659 | train | 48,395 |
ajenhl/tacl | tacl/data_store.py | DataStore.search | def search(self, catalogue, ngrams, output_fh):
"""Returns `output_fh` populated with CSV results for each n-gram in
`ngrams` that occurs within labelled witnesses in `catalogue`.
If `ngrams` is empty, include all n-grams.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param ngrams: n-grams to search for
:type ngrams: `list` of `str`
:param output_fh: object to write results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = list(self._set_labels(catalogue))
label_placeholders = self._get_placeholders(labels)
if ngrams:
self._add_temporary_ngrams(ngrams)
query = constants.SELECT_SEARCH_SQL.format(label_placeholders)
else:
query = constants.SELECT_SEARCH_ALL_SQL.format(label_placeholders)
self._logger.info('Running search query')
self._logger.debug('Query: {}\nN-grams: {}'.format(
query, ', '.join(ngrams)))
self._log_query_plan(query, labels)
cursor = self._conn.execute(query, labels)
return self._csv(cursor, constants.QUERY_FIELDNAMES, output_fh) | python | def search(self, catalogue, ngrams, output_fh):
"""Returns `output_fh` populated with CSV results for each n-gram in
`ngrams` that occurs within labelled witnesses in `catalogue`.
If `ngrams` is empty, include all n-grams.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param ngrams: n-grams to search for
:type ngrams: `list` of `str`
:param output_fh: object to write results to
:type output_fh: file-like object
:rtype: file-like object
"""
labels = list(self._set_labels(catalogue))
label_placeholders = self._get_placeholders(labels)
if ngrams:
self._add_temporary_ngrams(ngrams)
query = constants.SELECT_SEARCH_SQL.format(label_placeholders)
else:
query = constants.SELECT_SEARCH_ALL_SQL.format(label_placeholders)
self._logger.info('Running search query')
self._logger.debug('Query: {}\nN-grams: {}'.format(
query, ', '.join(ngrams)))
self._log_query_plan(query, labels)
cursor = self._conn.execute(query, labels)
return self._csv(cursor, constants.QUERY_FIELDNAMES, output_fh) | [
"def",
"search",
"(",
"self",
",",
"catalogue",
",",
"ngrams",
",",
"output_fh",
")",
":",
"labels",
"=",
"list",
"(",
"self",
".",
"_set_labels",
"(",
"catalogue",
")",
")",
"label_placeholders",
"=",
"self",
".",
"_get_placeholders",
"(",
"labels",
")",
... | Returns `output_fh` populated with CSV results for each n-gram in
`ngrams` that occurs within labelled witnesses in `catalogue`.
If `ngrams` is empty, include all n-grams.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:param ngrams: n-grams to search for
:type ngrams: `list` of `str`
:param output_fh: object to write results to
:type output_fh: file-like object
:rtype: file-like object | [
"Returns",
"output_fh",
"populated",
"with",
"CSV",
"results",
"for",
"each",
"n",
"-",
"gram",
"in",
"ngrams",
"that",
"occurs",
"within",
"labelled",
"witnesses",
"in",
"catalogue",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L661-L688 | train | 48,396 |
ajenhl/tacl | tacl/data_store.py | DataStore._set_labels | def _set_labels(self, catalogue):
"""Returns a dictionary of the unique labels in `catalogue` and the
count of all tokens associated with each, and sets the record
of each Text to its corresponding label.
Texts that do not have a label specified are set to the empty
string.
Token counts are included in the results to allow for
semi-accurate sorting based on corpora size.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:rtype: `dict`
"""
with self._conn:
self._conn.execute(constants.UPDATE_LABELS_SQL, [''])
labels = {}
for work, label in catalogue.items():
self._conn.execute(constants.UPDATE_LABEL_SQL, [label, work])
cursor = self._conn.execute(
constants.SELECT_TEXT_TOKEN_COUNT_SQL, [work])
token_count = cursor.fetchone()['token_count']
labels[label] = labels.get(label, 0) + token_count
return labels | python | def _set_labels(self, catalogue):
"""Returns a dictionary of the unique labels in `catalogue` and the
count of all tokens associated with each, and sets the record
of each Text to its corresponding label.
Texts that do not have a label specified are set to the empty
string.
Token counts are included in the results to allow for
semi-accurate sorting based on corpora size.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:rtype: `dict`
"""
with self._conn:
self._conn.execute(constants.UPDATE_LABELS_SQL, [''])
labels = {}
for work, label in catalogue.items():
self._conn.execute(constants.UPDATE_LABEL_SQL, [label, work])
cursor = self._conn.execute(
constants.SELECT_TEXT_TOKEN_COUNT_SQL, [work])
token_count = cursor.fetchone()['token_count']
labels[label] = labels.get(label, 0) + token_count
return labels | [
"def",
"_set_labels",
"(",
"self",
",",
"catalogue",
")",
":",
"with",
"self",
".",
"_conn",
":",
"self",
".",
"_conn",
".",
"execute",
"(",
"constants",
".",
"UPDATE_LABELS_SQL",
",",
"[",
"''",
"]",
")",
"labels",
"=",
"{",
"}",
"for",
"work",
",",... | Returns a dictionary of the unique labels in `catalogue` and the
count of all tokens associated with each, and sets the record
of each Text to its corresponding label.
Texts that do not have a label specified are set to the empty
string.
Token counts are included in the results to allow for
semi-accurate sorting based on corpora size.
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:rtype: `dict` | [
"Returns",
"a",
"dictionary",
"of",
"the",
"unique",
"labels",
"in",
"catalogue",
"and",
"the",
"count",
"of",
"all",
"tokens",
"associated",
"with",
"each",
"and",
"sets",
"the",
"record",
"of",
"each",
"Text",
"to",
"its",
"corresponding",
"label",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L690-L715 | train | 48,397 |
ajenhl/tacl | tacl/data_store.py | DataStore._update_text_record | def _update_text_record(self, witness, text_id):
"""Updates the record with `text_id` with `witness`\'s checksum and
token count.
:param withness: witness to update from
:type witness: `WitnessText`
:param text_id: database ID of Text record
:type text_id: `int`
"""
checksum = witness.get_checksum()
token_count = len(witness.get_tokens())
with self._conn:
self._conn.execute(constants.UPDATE_TEXT_SQL,
[checksum, token_count, text_id]) | python | def _update_text_record(self, witness, text_id):
"""Updates the record with `text_id` with `witness`\'s checksum and
token count.
:param withness: witness to update from
:type witness: `WitnessText`
:param text_id: database ID of Text record
:type text_id: `int`
"""
checksum = witness.get_checksum()
token_count = len(witness.get_tokens())
with self._conn:
self._conn.execute(constants.UPDATE_TEXT_SQL,
[checksum, token_count, text_id]) | [
"def",
"_update_text_record",
"(",
"self",
",",
"witness",
",",
"text_id",
")",
":",
"checksum",
"=",
"witness",
".",
"get_checksum",
"(",
")",
"token_count",
"=",
"len",
"(",
"witness",
".",
"get_tokens",
"(",
")",
")",
"with",
"self",
".",
"_conn",
":"... | Updates the record with `text_id` with `witness`\'s checksum and
token count.
:param withness: witness to update from
:type witness: `WitnessText`
:param text_id: database ID of Text record
:type text_id: `int` | [
"Updates",
"the",
"record",
"with",
"text_id",
"with",
"witness",
"\\",
"s",
"checksum",
"and",
"token",
"count",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L732-L746 | train | 48,398 |
ajenhl/tacl | tacl/data_store.py | DataStore.validate | def validate(self, corpus, catalogue):
"""Returns True if all of the files labelled in `catalogue`
are up-to-date in the database.
:param corpus: corpus of works
:type corpus: `Corpus`
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:rtype: `bool`
"""
is_valid = True
for name in catalogue:
count = 0
# It is unfortunate that this creates WitnessText objects
# for each work, since that involves reading the file.
for witness in corpus.get_witnesses(name):
count += 1
name, siglum = witness.get_names()
filename = witness.get_filename()
row = self._conn.execute(constants.SELECT_TEXT_SQL,
[name, siglum]).fetchone()
if row is None:
is_valid = False
self._logger.warning(
'No record (or n-grams) exists for {} in '
'the database'.format(filename))
elif row['checksum'] != witness.get_checksum():
is_valid = False
self._logger.warning(
'{} has changed since its n-grams were '
'added to the database'.format(filename))
if count == 0:
raise FileNotFoundError(
constants.CATALOGUE_WORK_NOT_IN_CORPUS_ERROR.format(
name))
return is_valid | python | def validate(self, corpus, catalogue):
"""Returns True if all of the files labelled in `catalogue`
are up-to-date in the database.
:param corpus: corpus of works
:type corpus: `Corpus`
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:rtype: `bool`
"""
is_valid = True
for name in catalogue:
count = 0
# It is unfortunate that this creates WitnessText objects
# for each work, since that involves reading the file.
for witness in corpus.get_witnesses(name):
count += 1
name, siglum = witness.get_names()
filename = witness.get_filename()
row = self._conn.execute(constants.SELECT_TEXT_SQL,
[name, siglum]).fetchone()
if row is None:
is_valid = False
self._logger.warning(
'No record (or n-grams) exists for {} in '
'the database'.format(filename))
elif row['checksum'] != witness.get_checksum():
is_valid = False
self._logger.warning(
'{} has changed since its n-grams were '
'added to the database'.format(filename))
if count == 0:
raise FileNotFoundError(
constants.CATALOGUE_WORK_NOT_IN_CORPUS_ERROR.format(
name))
return is_valid | [
"def",
"validate",
"(",
"self",
",",
"corpus",
",",
"catalogue",
")",
":",
"is_valid",
"=",
"True",
"for",
"name",
"in",
"catalogue",
":",
"count",
"=",
"0",
"# It is unfortunate that this creates WitnessText objects",
"# for each work, since that involves reading the fil... | Returns True if all of the files labelled in `catalogue`
are up-to-date in the database.
:param corpus: corpus of works
:type corpus: `Corpus`
:param catalogue: catalogue matching filenames to labels
:type catalogue: `Catalogue`
:rtype: `bool` | [
"Returns",
"True",
"if",
"all",
"of",
"the",
"files",
"labelled",
"in",
"catalogue",
"are",
"up",
"-",
"to",
"-",
"date",
"in",
"the",
"database",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L748-L784 | train | 48,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.