repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L228-L243
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L246-L254
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L257-L274
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L277-L294
ajenhl/tacl
tacl/__main__.py
generate_results_subparser
def generate_results_subparser(subparsers): """Adds a sub-command parser to `subparsers` to manipulate CSV results data.""" parser = subparsers.add_parser( 'results', description=constants.RESULTS_DESCRIPTION, epilog=constants.RESULTS_EPILOG, formatter_class=ParagraphFormatter, help=constants.RESULTS_HELP) utils.add_common_arguments(parser) parser.set_defaults(func=results) be_group = parser.add_argument_group('bifurcated extend') be_group.add_argument('-b', '--bifurcated-extend', dest='bifurcated_extend', metavar='CORPUS', help=constants.RESULTS_BIFURCATED_EXTEND_HELP) be_group.add_argument('--max-be-count', dest='bifurcated_extend_size', help=constants.RESULTS_BIFURCATED_EXTEND_MAX_HELP, metavar='COUNT', type=int) parser.add_argument('-e', '--extend', dest='extend', help=constants.RESULTS_EXTEND_HELP, metavar='CORPUS') parser.add_argument('--excise', help=constants.RESULTS_EXCISE_HELP, metavar='NGRAM', type=str) parser.add_argument('-l', '--label', dest='label', help=constants.RESULTS_LABEL_HELP, metavar='LABEL') parser.add_argument('--min-count', dest='min_count', help=constants.RESULTS_MINIMUM_COUNT_HELP, metavar='COUNT', type=int) parser.add_argument('--max-count', dest='max_count', help=constants.RESULTS_MAXIMUM_COUNT_HELP, metavar='COUNT', type=int) parser.add_argument('--min-count-work', dest='min_count_work', help=constants.RESULTS_MINIMUM_COUNT_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--max-count-work', dest='max_count_work', help=constants.RESULTS_MAXIMUM_COUNT_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--min-size', dest='min_size', help=constants.RESULTS_MINIMUM_SIZE_HELP, metavar='SIZE', type=int) parser.add_argument('--max-size', dest='max_size', help=constants.RESULTS_MAXIMUM_SIZE_HELP, metavar='SIZE', type=int) parser.add_argument('--min-works', dest='min_works', help=constants.RESULTS_MINIMUM_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--max-works', dest='max_works', help=constants.RESULTS_MAXIMUM_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--ngrams', dest='ngrams', help=constants.RESULTS_NGRAMS_HELP, metavar='NGRAMS') parser.add_argument('--reciprocal', action='store_true', help=constants.RESULTS_RECIPROCAL_HELP) parser.add_argument('--reduce', action='store_true', help=constants.RESULTS_REDUCE_HELP) parser.add_argument('--relabel', help=constants.RESULTS_RELABEL_HELP, metavar='CATALOGUE') parser.add_argument('--remove', help=constants.RESULTS_REMOVE_HELP, metavar='LABEL', type=str) parser.add_argument('--sort', action='store_true', help=constants.RESULTS_SORT_HELP) utils.add_tokenizer_argument(parser) parser.add_argument('-z', '--zero-fill', dest='zero_fill', help=constants.RESULTS_ZERO_FILL_HELP, metavar='CORPUS') parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP, metavar='RESULTS') unsafe_group = parser.add_argument_group( constants.RESULTS_UNSAFE_GROUP_TITLE, constants.RESULTS_UNSAFE_GROUP_DESCRIPTION) unsafe_group.add_argument('--add-label-count', action='store_true', help=constants.RESULTS_ADD_LABEL_COUNT_HELP) unsafe_group.add_argument('--add-label-work-count', action='store_true', help=constants.RESULTS_ADD_LABEL_WORK_COUNT_HELP) unsafe_group.add_argument('--collapse-witnesses', action='store_true', help=constants.RESULTS_COLLAPSE_WITNESSES_HELP) unsafe_group.add_argument('--group-by-ngram', dest='group_by_ngram', help=constants.RESULTS_GROUP_BY_NGRAM_HELP, metavar='CATALOGUE') unsafe_group.add_argument('--group-by-witness', action='store_true', help=constants.RESULTS_GROUP_BY_WITNESS_HELP)
python
def generate_results_subparser(subparsers): """Adds a sub-command parser to `subparsers` to manipulate CSV results data.""" parser = subparsers.add_parser( 'results', description=constants.RESULTS_DESCRIPTION, epilog=constants.RESULTS_EPILOG, formatter_class=ParagraphFormatter, help=constants.RESULTS_HELP) utils.add_common_arguments(parser) parser.set_defaults(func=results) be_group = parser.add_argument_group('bifurcated extend') be_group.add_argument('-b', '--bifurcated-extend', dest='bifurcated_extend', metavar='CORPUS', help=constants.RESULTS_BIFURCATED_EXTEND_HELP) be_group.add_argument('--max-be-count', dest='bifurcated_extend_size', help=constants.RESULTS_BIFURCATED_EXTEND_MAX_HELP, metavar='COUNT', type=int) parser.add_argument('-e', '--extend', dest='extend', help=constants.RESULTS_EXTEND_HELP, metavar='CORPUS') parser.add_argument('--excise', help=constants.RESULTS_EXCISE_HELP, metavar='NGRAM', type=str) parser.add_argument('-l', '--label', dest='label', help=constants.RESULTS_LABEL_HELP, metavar='LABEL') parser.add_argument('--min-count', dest='min_count', help=constants.RESULTS_MINIMUM_COUNT_HELP, metavar='COUNT', type=int) parser.add_argument('--max-count', dest='max_count', help=constants.RESULTS_MAXIMUM_COUNT_HELP, metavar='COUNT', type=int) parser.add_argument('--min-count-work', dest='min_count_work', help=constants.RESULTS_MINIMUM_COUNT_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--max-count-work', dest='max_count_work', help=constants.RESULTS_MAXIMUM_COUNT_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--min-size', dest='min_size', help=constants.RESULTS_MINIMUM_SIZE_HELP, metavar='SIZE', type=int) parser.add_argument('--max-size', dest='max_size', help=constants.RESULTS_MAXIMUM_SIZE_HELP, metavar='SIZE', type=int) parser.add_argument('--min-works', dest='min_works', help=constants.RESULTS_MINIMUM_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--max-works', dest='max_works', help=constants.RESULTS_MAXIMUM_WORK_HELP, metavar='COUNT', type=int) parser.add_argument('--ngrams', dest='ngrams', help=constants.RESULTS_NGRAMS_HELP, metavar='NGRAMS') parser.add_argument('--reciprocal', action='store_true', help=constants.RESULTS_RECIPROCAL_HELP) parser.add_argument('--reduce', action='store_true', help=constants.RESULTS_REDUCE_HELP) parser.add_argument('--relabel', help=constants.RESULTS_RELABEL_HELP, metavar='CATALOGUE') parser.add_argument('--remove', help=constants.RESULTS_REMOVE_HELP, metavar='LABEL', type=str) parser.add_argument('--sort', action='store_true', help=constants.RESULTS_SORT_HELP) utils.add_tokenizer_argument(parser) parser.add_argument('-z', '--zero-fill', dest='zero_fill', help=constants.RESULTS_ZERO_FILL_HELP, metavar='CORPUS') parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP, metavar='RESULTS') unsafe_group = parser.add_argument_group( constants.RESULTS_UNSAFE_GROUP_TITLE, constants.RESULTS_UNSAFE_GROUP_DESCRIPTION) unsafe_group.add_argument('--add-label-count', action='store_true', help=constants.RESULTS_ADD_LABEL_COUNT_HELP) unsafe_group.add_argument('--add-label-work-count', action='store_true', help=constants.RESULTS_ADD_LABEL_WORK_COUNT_HELP) unsafe_group.add_argument('--collapse-witnesses', action='store_true', help=constants.RESULTS_COLLAPSE_WITNESSES_HELP) unsafe_group.add_argument('--group-by-ngram', dest='group_by_ngram', help=constants.RESULTS_GROUP_BY_NGRAM_HELP, metavar='CATALOGUE') unsafe_group.add_argument('--group-by-witness', action='store_true', help=constants.RESULTS_GROUP_BY_WITNESS_HELP)
[ "def", "generate_results_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'results'", ",", "description", "=", "constants", ".", "RESULTS_DESCRIPTION", ",", "epilog", "=", "constants", ".", "RESULTS_EPILOG", ",", "form...
Adds a sub-command parser to `subparsers` to manipulate CSV results data.
[ "Adds", "a", "sub", "-", "command", "parser", "to", "subparsers", "to", "manipulate", "CSV", "results", "data", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L297-L374
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L377-L390
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L401-L411
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L414-L426
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L429-L440
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L443-L454
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L457-L481
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L484-L492
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L495-L501
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L504-L515
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L518-L524
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L527-L539
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L606-L615
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/__main__.py#L618-L622
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" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/http_meta.py#L23-L52
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" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/transport_meta.py#L21-L37
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" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/transport_meta.py#L45-L71
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L74-L94
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L96-L117
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L119-L143
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L145-L164
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L166-L179
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L216-L234
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L247-L277
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L279-L307
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L309-L353
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L355-L389
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L391-L418
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/jitc.py#L420-L443
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L44-L48
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L50-L72
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L74-L85
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L101-L114
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L121-L142
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L144-L160
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L162-L183
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L185-L194
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L197-L241
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L243-L260
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L266-L291
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L293-L307
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L309-L319
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L321-L343
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L345-L375
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...
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L377-L410
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L412-L438
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L440-L444
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L471-L499
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L501-L515
ajenhl/tacl
tacl/data_store.py
DataStore._initialise_database
def _initialise_database(self): """Creates the database schema. This will not create tables or indices that already exist and is safe to be called on an existing database. """ self._logger.info('Creating database schema, if necessary') self._conn.execute(constants.CREATE_TABLE_TEXT_SQL) self._conn.execute(constants.CREATE_TABLE_TEXTNGRAM_SQL) self._conn.execute(constants.CREATE_TABLE_TEXTHASNGRAM_SQL) self._conn.execute(constants.CREATE_INDEX_TEXTHASNGRAM_SQL) self._conn.execute(constants.CREATE_INDEX_TEXT_SQL)
python
def _initialise_database(self): """Creates the database schema. This will not create tables or indices that already exist and is safe to be called on an existing database. """ self._logger.info('Creating database schema, if necessary') self._conn.execute(constants.CREATE_TABLE_TEXT_SQL) self._conn.execute(constants.CREATE_TABLE_TEXTNGRAM_SQL) self._conn.execute(constants.CREATE_TABLE_TEXTHASNGRAM_SQL) self._conn.execute(constants.CREATE_INDEX_TEXTHASNGRAM_SQL) self._conn.execute(constants.CREATE_INDEX_TEXT_SQL)
[ "def", "_initialise_database", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Creating database schema, if necessary'", ")", "self", ".", "_conn", ".", "execute", "(", "constants", ".", "CREATE_TABLE_TEXT_SQL", ")", "self", ".", "_conn", ".",...
Creates the database schema. This will not create tables or indices that already exist and is safe to be called on an existing database.
[ "Creates", "the", "database", "schema", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L517-L529
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L531-L556
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L558-L580
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L589-L659
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L661-L688
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L690-L715
ajenhl/tacl
tacl/data_store.py
DataStore._sort_labels
def _sort_labels(label_data): """Returns the labels in `label_data` sorted in descending order according to the 'size' (total token count) of their referent corpora. :param label_data: labels (with their token counts) to sort :type: `dict` :rtype: `list` """ labels = list(label_data) labels.sort(key=label_data.get, reverse=True) return labels
python
def _sort_labels(label_data): """Returns the labels in `label_data` sorted in descending order according to the 'size' (total token count) of their referent corpora. :param label_data: labels (with their token counts) to sort :type: `dict` :rtype: `list` """ labels = list(label_data) labels.sort(key=label_data.get, reverse=True) return labels
[ "def", "_sort_labels", "(", "label_data", ")", ":", "labels", "=", "list", "(", "label_data", ")", "labels", ".", "sort", "(", "key", "=", "label_data", ".", "get", ",", "reverse", "=", "True", ")", "return", "labels" ]
Returns the labels in `label_data` sorted in descending order according to the 'size' (total token count) of their referent corpora. :param label_data: labels (with their token counts) to sort :type: `dict` :rtype: `list`
[ "Returns", "the", "labels", "in", "label_data", "sorted", "in", "descending", "order", "according", "to", "the", "size", "(", "total", "token", "count", ")", "of", "their", "referent", "corpora", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L718-L730
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L732-L746
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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L748-L784
ajenhl/tacl
tacl/sequence.py
Sequence._format_alignment
def _format_alignment(self, a1, a2): """Returns `a1` marked up with HTML spans around characters that are also at the same index in `a2`. :param a1: text sequence from one witness :type a1: `str` :param a2: text sequence from another witness :type a2: `str` :rtype: `str` """ html = [] for index, char in enumerate(a1): output = self._substitutes.get(char, char) if a2[index] == char: html.append('<span class="match">{}</span>'.format(output)) elif char != '-': html.append(output) return ''.join(html)
python
def _format_alignment(self, a1, a2): """Returns `a1` marked up with HTML spans around characters that are also at the same index in `a2`. :param a1: text sequence from one witness :type a1: `str` :param a2: text sequence from another witness :type a2: `str` :rtype: `str` """ html = [] for index, char in enumerate(a1): output = self._substitutes.get(char, char) if a2[index] == char: html.append('<span class="match">{}</span>'.format(output)) elif char != '-': html.append(output) return ''.join(html)
[ "def", "_format_alignment", "(", "self", ",", "a1", ",", "a2", ")", ":", "html", "=", "[", "]", "for", "index", ",", "char", "in", "enumerate", "(", "a1", ")", ":", "output", "=", "self", ".", "_substitutes", ".", "get", "(", "char", ",", "char", ...
Returns `a1` marked up with HTML spans around characters that are also at the same index in `a2`. :param a1: text sequence from one witness :type a1: `str` :param a2: text sequence from another witness :type a2: `str` :rtype: `str`
[ "Returns", "a1", "marked", "up", "with", "HTML", "spans", "around", "characters", "that", "are", "also", "at", "the", "same", "index", "in", "a2", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L24-L42
ajenhl/tacl
tacl/sequence.py
Sequence.render
def render(self): """Returns a tuple of HTML fragments rendering each element of the sequence.""" f1 = self._format_alignment(self._alignment[0], self._alignment[1]) f2 = self._format_alignment(self._alignment[1], self._alignment[0]) return f1, f2
python
def render(self): """Returns a tuple of HTML fragments rendering each element of the sequence.""" f1 = self._format_alignment(self._alignment[0], self._alignment[1]) f2 = self._format_alignment(self._alignment[1], self._alignment[0]) return f1, f2
[ "def", "render", "(", "self", ")", ":", "f1", "=", "self", ".", "_format_alignment", "(", "self", ".", "_alignment", "[", "0", "]", ",", "self", ".", "_alignment", "[", "1", "]", ")", "f2", "=", "self", ".", "_format_alignment", "(", "self", ".", "...
Returns a tuple of HTML fragments rendering each element of the sequence.
[ "Returns", "a", "tuple", "of", "HTML", "fragments", "rendering", "each", "element", "of", "the", "sequence", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L44-L49
ajenhl/tacl
tacl/sequence.py
SequenceReport.generate
def generate(self, output_dir, minimum_size): """Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type minimum_size: `int` """ self._output_dir = output_dir # Get a list of the files in the matches, grouped by label # (ordered by number of works). labels = list(self._matches.groupby([constants.LABEL_FIELDNAME])[ constants.WORK_FIELDNAME].nunique().index) original_ngrams = self._matches[ self._matches[ constants.SIZE_FIELDNAME] >= minimum_size].sort_values( by=constants.SIZE_FIELDNAME, ascending=False)[ constants.NGRAM_FIELDNAME].unique() ngrams = [] for original_ngram in original_ngrams: ngrams.append(self._get_text(Text(original_ngram, self._tokenizer))) # Generate sequences for each witness in every combination of # (different) labels. for index, primary_label in enumerate(labels): for secondary_label in labels[index+1:]: self._generate_sequences(primary_label, secondary_label, ngrams)
python
def generate(self, output_dir, minimum_size): """Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type minimum_size: `int` """ self._output_dir = output_dir # Get a list of the files in the matches, grouped by label # (ordered by number of works). labels = list(self._matches.groupby([constants.LABEL_FIELDNAME])[ constants.WORK_FIELDNAME].nunique().index) original_ngrams = self._matches[ self._matches[ constants.SIZE_FIELDNAME] >= minimum_size].sort_values( by=constants.SIZE_FIELDNAME, ascending=False)[ constants.NGRAM_FIELDNAME].unique() ngrams = [] for original_ngram in original_ngrams: ngrams.append(self._get_text(Text(original_ngram, self._tokenizer))) # Generate sequences for each witness in every combination of # (different) labels. for index, primary_label in enumerate(labels): for secondary_label in labels[index+1:]: self._generate_sequences(primary_label, secondary_label, ngrams)
[ "def", "generate", "(", "self", ",", "output_dir", ",", "minimum_size", ")", ":", "self", ".", "_output_dir", "=", "output_dir", "# Get a list of the files in the matches, grouped by label", "# (ordered by number of works).", "labels", "=", "list", "(", "self", ".", "_m...
Generates sequence reports and writes them to the output directory. :param output_dir: directory to output reports to :type output_dir: `str` :param minimum_size: minimum size of n-grams to create sequences for :type minimum_size: `int`
[ "Generates", "sequence", "reports", "and", "writes", "them", "to", "the", "output", "directory", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L68-L96
ajenhl/tacl
tacl/sequence.py
SequenceReport._generate_sequence
def _generate_sequence(self, t1, t1_span, t2, t2_span, context_length, covered_spans): """Returns an aligned sequence (or None) between extract `t1_span` of witness text `t1` and extract `t2_span` of witness text `t2`. Adds the span of the aligned sequence, if any, to `covered_spans` (which, being mutable, is modified in place without needing to be returned). This method repeats the alignment process, increasing the context length until the alignment score (the measure of how much the two sequences align) drops below a certain point or it is not possible to increase the context length. :param t1: text content of first witness :type t1: `str` :param t1_span: start and end indices within `t1` to align :type t1_span: 2-`tuple` of `int` :param t2: text content of second witness :type t2: `str` :param t2_span: start and end indices within `t2` to align :type t2_span: 2-`tuple` of `int` :param context_length: length of context on either side of the spans to include in the sequence :type context_length: `int` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` """ old_length = 0 self._logger.debug('Match found; generating new sequence') while True: s1, span1 = self._get_text_sequence(t1, t1_span, context_length) s2, span2 = self._get_text_sequence(t2, t2_span, context_length) length = len(s1) alignment = pairwise2.align.globalms( s1, s2, constants.IDENTICAL_CHARACTER_SCORE, constants.DIFFERENT_CHARACTER_SCORE, constants.OPEN_GAP_PENALTY, constants.EXTEND_GAP_PENALTY)[0] context_length = length score = alignment[2] / length if not alignment: return None elif score < constants.SCORE_THRESHOLD or length == old_length: break else: self._logger.debug('Score: {}'.format(score)) old_length = length covered_spans[0].append(span1) covered_spans[1].append(span2) return Sequence(alignment, self._reverse_substitutes, t1_span[0])
python
def _generate_sequence(self, t1, t1_span, t2, t2_span, context_length, covered_spans): """Returns an aligned sequence (or None) between extract `t1_span` of witness text `t1` and extract `t2_span` of witness text `t2`. Adds the span of the aligned sequence, if any, to `covered_spans` (which, being mutable, is modified in place without needing to be returned). This method repeats the alignment process, increasing the context length until the alignment score (the measure of how much the two sequences align) drops below a certain point or it is not possible to increase the context length. :param t1: text content of first witness :type t1: `str` :param t1_span: start and end indices within `t1` to align :type t1_span: 2-`tuple` of `int` :param t2: text content of second witness :type t2: `str` :param t2_span: start and end indices within `t2` to align :type t2_span: 2-`tuple` of `int` :param context_length: length of context on either side of the spans to include in the sequence :type context_length: `int` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` """ old_length = 0 self._logger.debug('Match found; generating new sequence') while True: s1, span1 = self._get_text_sequence(t1, t1_span, context_length) s2, span2 = self._get_text_sequence(t2, t2_span, context_length) length = len(s1) alignment = pairwise2.align.globalms( s1, s2, constants.IDENTICAL_CHARACTER_SCORE, constants.DIFFERENT_CHARACTER_SCORE, constants.OPEN_GAP_PENALTY, constants.EXTEND_GAP_PENALTY)[0] context_length = length score = alignment[2] / length if not alignment: return None elif score < constants.SCORE_THRESHOLD or length == old_length: break else: self._logger.debug('Score: {}'.format(score)) old_length = length covered_spans[0].append(span1) covered_spans[1].append(span2) return Sequence(alignment, self._reverse_substitutes, t1_span[0])
[ "def", "_generate_sequence", "(", "self", ",", "t1", ",", "t1_span", ",", "t2", ",", "t2_span", ",", "context_length", ",", "covered_spans", ")", ":", "old_length", "=", "0", "self", ".", "_logger", ".", "debug", "(", "'Match found; generating new sequence'", ...
Returns an aligned sequence (or None) between extract `t1_span` of witness text `t1` and extract `t2_span` of witness text `t2`. Adds the span of the aligned sequence, if any, to `covered_spans` (which, being mutable, is modified in place without needing to be returned). This method repeats the alignment process, increasing the context length until the alignment score (the measure of how much the two sequences align) drops below a certain point or it is not possible to increase the context length. :param t1: text content of first witness :type t1: `str` :param t1_span: start and end indices within `t1` to align :type t1_span: 2-`tuple` of `int` :param t2: text content of second witness :type t2: `str` :param t2_span: start and end indices within `t2` to align :type t2_span: 2-`tuple` of `int` :param context_length: length of context on either side of the spans to include in the sequence :type context_length: `int` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
[ "Returns", "an", "aligned", "sequence", "(", "or", "None", ")", "between", "extract", "t1_span", "of", "witness", "text", "t1", "and", "extract", "t2_span", "of", "witness", "text", "t2", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L98-L149
ajenhl/tacl
tacl/sequence.py
SequenceReport._generate_sequences
def _generate_sequences(self, primary_label, secondary_label, ngrams): """Generates aligned sequences between each witness labelled `primary_label` and each witness labelled `secondary_label`, based around `ngrams`. :param primary_label: label for one side of the pairs of witnesses to align :type primary_label: `str` :param secondary_label: label for the other side of the pairs of witnesses to align :type secondary_label: `str` :param ngrams: n-grams to base sequences off :type ngrams: `list` of `str` """ cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME] primary_works = self._matches[self._matches[ constants.LABEL_FIELDNAME] == primary_label][ cols].drop_duplicates() secondary_works = self._matches[self._matches[ constants.LABEL_FIELDNAME] == secondary_label][ cols].drop_duplicates() for index, (work1, siglum1) in primary_works.iterrows(): text1 = self._get_text(self._corpus.get_witness(work1, siglum1)) label1 = '{}_{}'.format(work1, siglum1) for index, (work2, siglum2) in secondary_works.iterrows(): text2 = self._get_text(self._corpus.get_witness( work2, siglum2)) label2 = '{}_{}'.format(work2, siglum2) self._generate_sequences_for_texts(label1, text1, label2, text2, ngrams)
python
def _generate_sequences(self, primary_label, secondary_label, ngrams): """Generates aligned sequences between each witness labelled `primary_label` and each witness labelled `secondary_label`, based around `ngrams`. :param primary_label: label for one side of the pairs of witnesses to align :type primary_label: `str` :param secondary_label: label for the other side of the pairs of witnesses to align :type secondary_label: `str` :param ngrams: n-grams to base sequences off :type ngrams: `list` of `str` """ cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME] primary_works = self._matches[self._matches[ constants.LABEL_FIELDNAME] == primary_label][ cols].drop_duplicates() secondary_works = self._matches[self._matches[ constants.LABEL_FIELDNAME] == secondary_label][ cols].drop_duplicates() for index, (work1, siglum1) in primary_works.iterrows(): text1 = self._get_text(self._corpus.get_witness(work1, siglum1)) label1 = '{}_{}'.format(work1, siglum1) for index, (work2, siglum2) in secondary_works.iterrows(): text2 = self._get_text(self._corpus.get_witness( work2, siglum2)) label2 = '{}_{}'.format(work2, siglum2) self._generate_sequences_for_texts(label1, text1, label2, text2, ngrams)
[ "def", "_generate_sequences", "(", "self", ",", "primary_label", ",", "secondary_label", ",", "ngrams", ")", ":", "cols", "=", "[", "constants", ".", "WORK_FIELDNAME", ",", "constants", ".", "SIGLUM_FIELDNAME", "]", "primary_works", "=", "self", ".", "_matches",...
Generates aligned sequences between each witness labelled `primary_label` and each witness labelled `secondary_label`, based around `ngrams`. :param primary_label: label for one side of the pairs of witnesses to align :type primary_label: `str` :param secondary_label: label for the other side of the pairs of witnesses to align :type secondary_label: `str` :param ngrams: n-grams to base sequences off :type ngrams: `list` of `str`
[ "Generates", "aligned", "sequences", "between", "each", "witness", "labelled", "primary_label", "and", "each", "witness", "labelled", "secondary_label", "based", "around", "ngrams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L151-L181
ajenhl/tacl
tacl/sequence.py
SequenceReport._generate_sequences_for_ngram
def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans): """Generates aligned sequences for the texts `t1` and `t2`, based around `ngram`. Does not generate sequences that occur within `covered_spans`. :param t1: text content of first witness :type t1: `str` :param t2: text content of second witness :type t2: `str` :param ngram: n-gram to base sequences on :type ngram: `str` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` """ self._logger.debug('Generating sequences for n-gram "{}"'.format( ngram)) pattern = re.compile(re.escape(ngram)) context_length = len(ngram) t1_spans = [match.span() for match in pattern.finditer(t1)] t2_spans = [match.span() for match in pattern.finditer(t2)] sequences = [] self._logger.debug(t1) for t1_span in t1_spans: for t2_span in t2_spans: if self._is_inside(t1_span, t2_span, covered_spans): self._logger.debug( 'Skipping match due to existing coverage') continue sequence = self._generate_sequence( t1, t1_span, t2, t2_span, context_length, covered_spans) if sequence: sequences.append(sequence) return sequences
python
def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans): """Generates aligned sequences for the texts `t1` and `t2`, based around `ngram`. Does not generate sequences that occur within `covered_spans`. :param t1: text content of first witness :type t1: `str` :param t2: text content of second witness :type t2: `str` :param ngram: n-gram to base sequences on :type ngram: `str` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` """ self._logger.debug('Generating sequences for n-gram "{}"'.format( ngram)) pattern = re.compile(re.escape(ngram)) context_length = len(ngram) t1_spans = [match.span() for match in pattern.finditer(t1)] t2_spans = [match.span() for match in pattern.finditer(t2)] sequences = [] self._logger.debug(t1) for t1_span in t1_spans: for t2_span in t2_spans: if self._is_inside(t1_span, t2_span, covered_spans): self._logger.debug( 'Skipping match due to existing coverage') continue sequence = self._generate_sequence( t1, t1_span, t2, t2_span, context_length, covered_spans) if sequence: sequences.append(sequence) return sequences
[ "def", "_generate_sequences_for_ngram", "(", "self", ",", "t1", ",", "t2", ",", "ngram", ",", "covered_spans", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Generating sequences for n-gram \"{}\"'", ".", "format", "(", "ngram", ")", ")", "pattern", "=...
Generates aligned sequences for the texts `t1` and `t2`, based around `ngram`. Does not generate sequences that occur within `covered_spans`. :param t1: text content of first witness :type t1: `str` :param t2: text content of second witness :type t2: `str` :param ngram: n-gram to base sequences on :type ngram: `str` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
[ "Generates", "aligned", "sequences", "for", "the", "texts", "t1", "and", "t2", "based", "around", "ngram", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L183-L218
ajenhl/tacl
tacl/sequence.py
SequenceReport._generate_sequences_for_texts
def _generate_sequences_for_texts(self, l1, t1, l2, t2, ngrams): """Generates and outputs aligned sequences for the texts `t1` and `t2` from `ngrams`. :param l1: label of first witness :type l1: `str` :param t1: text content of first witness :type t1: `str` :param l2: label of second witness :type l2: `str` :param t2: text content of second witness :type t2: `str` :param ngrams: n-grams to base sequences on :type ngrams: `list` of `str` """ # self._subsitutes is gradually populated as each text is # processed, so this needs to be regenerated each time. self._reverse_substitutes = dict((v, k) for k, v in self._substitutes.items()) sequences = [] # Keep track of spans within each text that have been covered # by an aligned sequence, to ensure that they aren't reported # more than once. The first sub-list contains span indices for # text t1, the second for t2. covered_spans = [[], []] for ngram in ngrams: sequences.extend(self._generate_sequences_for_ngram( t1, t2, ngram, covered_spans)) if sequences: sequences.sort(key=lambda x: x.start_index) context = {'l1': l1, 'l2': l2, 'sequences': sequences} report_name = '{}-{}.html'.format(l1, l2) os.makedirs(self._output_dir, exist_ok=True) self._write(context, self._output_dir, report_name)
python
def _generate_sequences_for_texts(self, l1, t1, l2, t2, ngrams): """Generates and outputs aligned sequences for the texts `t1` and `t2` from `ngrams`. :param l1: label of first witness :type l1: `str` :param t1: text content of first witness :type t1: `str` :param l2: label of second witness :type l2: `str` :param t2: text content of second witness :type t2: `str` :param ngrams: n-grams to base sequences on :type ngrams: `list` of `str` """ # self._subsitutes is gradually populated as each text is # processed, so this needs to be regenerated each time. self._reverse_substitutes = dict((v, k) for k, v in self._substitutes.items()) sequences = [] # Keep track of spans within each text that have been covered # by an aligned sequence, to ensure that they aren't reported # more than once. The first sub-list contains span indices for # text t1, the second for t2. covered_spans = [[], []] for ngram in ngrams: sequences.extend(self._generate_sequences_for_ngram( t1, t2, ngram, covered_spans)) if sequences: sequences.sort(key=lambda x: x.start_index) context = {'l1': l1, 'l2': l2, 'sequences': sequences} report_name = '{}-{}.html'.format(l1, l2) os.makedirs(self._output_dir, exist_ok=True) self._write(context, self._output_dir, report_name)
[ "def", "_generate_sequences_for_texts", "(", "self", ",", "l1", ",", "t1", ",", "l2", ",", "t2", ",", "ngrams", ")", ":", "# self._subsitutes is gradually populated as each text is", "# processed, so this needs to be regenerated each time.", "self", ".", "_reverse_substitutes...
Generates and outputs aligned sequences for the texts `t1` and `t2` from `ngrams`. :param l1: label of first witness :type l1: `str` :param t1: text content of first witness :type t1: `str` :param l2: label of second witness :type l2: `str` :param t2: text content of second witness :type t2: `str` :param ngrams: n-grams to base sequences on :type ngrams: `list` of `str`
[ "Generates", "and", "outputs", "aligned", "sequences", "for", "the", "texts", "t1", "and", "t2", "from", "ngrams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L220-L254
ajenhl/tacl
tacl/sequence.py
SequenceReport._get_text
def _get_text(self, text): """Returns the text content of `text`, with all multi-character tokens replaced with a single character. Substitutions are recorded in self._substitutes. :param text: text to get content from :type text: `Text` :rtype: `str` """ tokens = text.get_tokens() for i, token in enumerate(tokens): if len(token) > 1: char = chr(self._char_code) substitute = self._substitutes.setdefault(token, char) if substitute == char: self._char_code += 1 tokens[i] = substitute return self._tokenizer.joiner.join(tokens)
python
def _get_text(self, text): """Returns the text content of `text`, with all multi-character tokens replaced with a single character. Substitutions are recorded in self._substitutes. :param text: text to get content from :type text: `Text` :rtype: `str` """ tokens = text.get_tokens() for i, token in enumerate(tokens): if len(token) > 1: char = chr(self._char_code) substitute = self._substitutes.setdefault(token, char) if substitute == char: self._char_code += 1 tokens[i] = substitute return self._tokenizer.joiner.join(tokens)
[ "def", "_get_text", "(", "self", ",", "text", ")", ":", "tokens", "=", "text", ".", "get_tokens", "(", ")", "for", "i", ",", "token", "in", "enumerate", "(", "tokens", ")", ":", "if", "len", "(", "token", ")", ">", "1", ":", "char", "=", "chr", ...
Returns the text content of `text`, with all multi-character tokens replaced with a single character. Substitutions are recorded in self._substitutes. :param text: text to get content from :type text: `Text` :rtype: `str`
[ "Returns", "the", "text", "content", "of", "text", "with", "all", "multi", "-", "character", "tokens", "replaced", "with", "a", "single", "character", ".", "Substitutions", "are", "recorded", "in", "self", ".", "_substitutes", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L256-L274
ajenhl/tacl
tacl/sequence.py
SequenceReport._get_text_sequence
def _get_text_sequence(self, text, span, context_length): """Returns the subset of `text` encompassed by `span`, plus `context_length` characters before and after. :param text: text to extract the sequence from :type text: `str` :param span: start and end indices within `text` :type span: 2-`tuple` of `int` :param context_length: length of context on either side of `span` to include in the extract :type context_length: `int` """ start = max(0, span[0] - context_length) end = min(len(text), span[1] + context_length) return text[start:end], (start, end)
python
def _get_text_sequence(self, text, span, context_length): """Returns the subset of `text` encompassed by `span`, plus `context_length` characters before and after. :param text: text to extract the sequence from :type text: `str` :param span: start and end indices within `text` :type span: 2-`tuple` of `int` :param context_length: length of context on either side of `span` to include in the extract :type context_length: `int` """ start = max(0, span[0] - context_length) end = min(len(text), span[1] + context_length) return text[start:end], (start, end)
[ "def", "_get_text_sequence", "(", "self", ",", "text", ",", "span", ",", "context_length", ")", ":", "start", "=", "max", "(", "0", ",", "span", "[", "0", "]", "-", "context_length", ")", "end", "=", "min", "(", "len", "(", "text", ")", ",", "span"...
Returns the subset of `text` encompassed by `span`, plus `context_length` characters before and after. :param text: text to extract the sequence from :type text: `str` :param span: start and end indices within `text` :type span: 2-`tuple` of `int` :param context_length: length of context on either side of `span` to include in the extract :type context_length: `int`
[ "Returns", "the", "subset", "of", "text", "encompassed", "by", "span", "plus", "context_length", "characters", "before", "and", "after", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L276-L291
ajenhl/tacl
tacl/sequence.py
SequenceReport._is_inside
def _is_inside(self, span1, span2, covered_spans): """Returns True if both `span1` and `span2` fall within `covered_spans`. :param span1: start and end indices of a span :type span1: 2-`tuple` of `int` :param span2: start and end indices of a span :type span2: 2-`tuple` of `int` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` :rtype: `bool` """ if self._is_span_inside(span1, covered_spans[0]) and \ self._is_span_inside(span2, covered_spans[1]): return True return False
python
def _is_inside(self, span1, span2, covered_spans): """Returns True if both `span1` and `span2` fall within `covered_spans`. :param span1: start and end indices of a span :type span1: 2-`tuple` of `int` :param span2: start and end indices of a span :type span2: 2-`tuple` of `int` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` :rtype: `bool` """ if self._is_span_inside(span1, covered_spans[0]) and \ self._is_span_inside(span2, covered_spans[1]): return True return False
[ "def", "_is_inside", "(", "self", ",", "span1", ",", "span2", ",", "covered_spans", ")", ":", "if", "self", ".", "_is_span_inside", "(", "span1", ",", "covered_spans", "[", "0", "]", ")", "and", "self", ".", "_is_span_inside", "(", "span2", ",", "covered...
Returns True if both `span1` and `span2` fall within `covered_spans`. :param span1: start and end indices of a span :type span1: 2-`tuple` of `int` :param span2: start and end indices of a span :type span2: 2-`tuple` of `int` :param covered_spans: lists of start and end indices for parts of the texts already covered by a sequence :type covered_spans: `list` of two `list`s of 2-`tuple` of `int` :rtype: `bool`
[ "Returns", "True", "if", "both", "span1", "and", "span2", "fall", "within", "covered_spans", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L293-L310
ajenhl/tacl
tacl/sequence.py
SequenceReport._is_span_inside
def _is_span_inside(self, span, covered_spans): """Returns True if `span` falls within `covered_spans`. :param span: start and end indices of a span :type span: 2-`tuple` of `int` :param covered_spans: list of start and end indices for parts of the text already covered by a sequence :type covered_spans: `list` of 2-`tuple` of `int` :rtype: `bool` """ start = span[0] end = span[1] for c_start, c_end in covered_spans: if start >= c_start and end <= c_end: return True return False
python
def _is_span_inside(self, span, covered_spans): """Returns True if `span` falls within `covered_spans`. :param span: start and end indices of a span :type span: 2-`tuple` of `int` :param covered_spans: list of start and end indices for parts of the text already covered by a sequence :type covered_spans: `list` of 2-`tuple` of `int` :rtype: `bool` """ start = span[0] end = span[1] for c_start, c_end in covered_spans: if start >= c_start and end <= c_end: return True return False
[ "def", "_is_span_inside", "(", "self", ",", "span", ",", "covered_spans", ")", ":", "start", "=", "span", "[", "0", "]", "end", "=", "span", "[", "1", "]", "for", "c_start", ",", "c_end", "in", "covered_spans", ":", "if", "start", ">=", "c_start", "a...
Returns True if `span` falls within `covered_spans`. :param span: start and end indices of a span :type span: 2-`tuple` of `int` :param covered_spans: list of start and end indices for parts of the text already covered by a sequence :type covered_spans: `list` of 2-`tuple` of `int` :rtype: `bool`
[ "Returns", "True", "if", "span", "falls", "within", "covered_spans", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L312-L328
ajenhl/tacl
tacl/cli/utils.py
add_corpus_arguments
def add_corpus_arguments(parser): """Adds common arguments for commands making use of a corpus to `parser`.""" add_tokenizer_argument(parser) parser.add_argument('corpus', help=constants.DB_CORPUS_HELP, metavar='CORPUS')
python
def add_corpus_arguments(parser): """Adds common arguments for commands making use of a corpus to `parser`.""" add_tokenizer_argument(parser) parser.add_argument('corpus', help=constants.DB_CORPUS_HELP, metavar='CORPUS')
[ "def", "add_corpus_arguments", "(", "parser", ")", ":", "add_tokenizer_argument", "(", "parser", ")", "parser", ".", "add_argument", "(", "'corpus'", ",", "help", "=", "constants", ".", "DB_CORPUS_HELP", ",", "metavar", "=", "'CORPUS'", ")" ]
Adds common arguments for commands making use of a corpus to `parser`.
[ "Adds", "common", "arguments", "for", "commands", "making", "use", "of", "a", "corpus", "to", "parser", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L18-L23
ajenhl/tacl
tacl/cli/utils.py
add_db_arguments
def add_db_arguments(parser, db_option=False): """Adds common arguments for the database sub-commands to `parser`. `db_option` provides a means to work around https://bugs.python.org/issue9338 whereby a positional argument that follows an optional argument with nargs='+' will not be recognised. When `db_optional` is True, create the database argument as a required optional argument, rather than a positional argument. """ parser.add_argument('-m', '--memory', action='store_true', help=constants.DB_MEMORY_HELP) parser.add_argument('-r', '--ram', default=3, help=constants.DB_RAM_HELP, type=int) if db_option: parser.add_argument('-d', '--db', help=constants.DB_DATABASE_HELP, metavar='DATABASE', required=True) else: parser.add_argument('db', help=constants.DB_DATABASE_HELP, metavar='DATABASE')
python
def add_db_arguments(parser, db_option=False): """Adds common arguments for the database sub-commands to `parser`. `db_option` provides a means to work around https://bugs.python.org/issue9338 whereby a positional argument that follows an optional argument with nargs='+' will not be recognised. When `db_optional` is True, create the database argument as a required optional argument, rather than a positional argument. """ parser.add_argument('-m', '--memory', action='store_true', help=constants.DB_MEMORY_HELP) parser.add_argument('-r', '--ram', default=3, help=constants.DB_RAM_HELP, type=int) if db_option: parser.add_argument('-d', '--db', help=constants.DB_DATABASE_HELP, metavar='DATABASE', required=True) else: parser.add_argument('db', help=constants.DB_DATABASE_HELP, metavar='DATABASE')
[ "def", "add_db_arguments", "(", "parser", ",", "db_option", "=", "False", ")", ":", "parser", ".", "add_argument", "(", "'-m'", ",", "'--memory'", ",", "action", "=", "'store_true'", ",", "help", "=", "constants", ".", "DB_MEMORY_HELP", ")", "parser", ".", ...
Adds common arguments for the database sub-commands to `parser`. `db_option` provides a means to work around https://bugs.python.org/issue9338 whereby a positional argument that follows an optional argument with nargs='+' will not be recognised. When `db_optional` is True, create the database argument as a required optional argument, rather than a positional argument.
[ "Adds", "common", "arguments", "for", "the", "database", "sub", "-", "commands", "to", "parser", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L26-L47
ajenhl/tacl
tacl/cli/utils.py
add_supplied_query_arguments
def add_supplied_query_arguments(parser): """Adds common arguments for supplied query sub-commands to `parser`.""" parser.add_argument('-l', '--labels', help=constants.SUPPLIED_LABELS_HELP, nargs='+', required=True) parser.add_argument('-s', '--supplied', help=constants.SUPPLIED_RESULTS_HELP, metavar='RESULTS', nargs='+', required=True)
python
def add_supplied_query_arguments(parser): """Adds common arguments for supplied query sub-commands to `parser`.""" parser.add_argument('-l', '--labels', help=constants.SUPPLIED_LABELS_HELP, nargs='+', required=True) parser.add_argument('-s', '--supplied', help=constants.SUPPLIED_RESULTS_HELP, metavar='RESULTS', nargs='+', required=True)
[ "def", "add_supplied_query_arguments", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-l'", ",", "'--labels'", ",", "help", "=", "constants", ".", "SUPPLIED_LABELS_HELP", ",", "nargs", "=", "'+'", ",", "required", "=", "True", ")", "parser", ...
Adds common arguments for supplied query sub-commands to `parser`.
[ "Adds", "common", "arguments", "for", "supplied", "query", "sub", "-", "commands", "to", "parser", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L56-L63
ajenhl/tacl
tacl/cli/utils.py
configure_logging
def configure_logging(verbose, logger): """Configures the logging used.""" if not verbose: log_level = logging.WARNING elif verbose == 1: log_level = logging.INFO else: log_level = logging.DEBUG logger.setLevel(log_level) ch = colorlog.StreamHandler() ch.setLevel(log_level) formatter = colorlog.ColoredFormatter( '%(log_color)s%(asctime)s %(name)s %(levelname)s: %(message)s') ch.setFormatter(formatter) logger.addHandler(ch)
python
def configure_logging(verbose, logger): """Configures the logging used.""" if not verbose: log_level = logging.WARNING elif verbose == 1: log_level = logging.INFO else: log_level = logging.DEBUG logger.setLevel(log_level) ch = colorlog.StreamHandler() ch.setLevel(log_level) formatter = colorlog.ColoredFormatter( '%(log_color)s%(asctime)s %(name)s %(levelname)s: %(message)s') ch.setFormatter(formatter) logger.addHandler(ch)
[ "def", "configure_logging", "(", "verbose", ",", "logger", ")", ":", "if", "not", "verbose", ":", "log_level", "=", "logging", ".", "WARNING", "elif", "verbose", "==", "1", ":", "log_level", "=", "logging", ".", "INFO", "else", ":", "log_level", "=", "lo...
Configures the logging used.
[ "Configures", "the", "logging", "used", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L73-L87
ajenhl/tacl
tacl/cli/utils.py
get_catalogue
def get_catalogue(args): """Returns a `tacl.Catalogue`.""" catalogue = tacl.Catalogue() catalogue.load(args.catalogue) return catalogue
python
def get_catalogue(args): """Returns a `tacl.Catalogue`.""" catalogue = tacl.Catalogue() catalogue.load(args.catalogue) return catalogue
[ "def", "get_catalogue", "(", "args", ")", ":", "catalogue", "=", "tacl", ".", "Catalogue", "(", ")", "catalogue", ".", "load", "(", "args", ".", "catalogue", ")", "return", "catalogue" ]
Returns a `tacl.Catalogue`.
[ "Returns", "a", "tacl", ".", "Catalogue", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L90-L94
ajenhl/tacl
tacl/cli/utils.py
get_corpus
def get_corpus(args): """Returns a `tacl.Corpus`.""" tokenizer = get_tokenizer(args) return tacl.Corpus(args.corpus, tokenizer)
python
def get_corpus(args): """Returns a `tacl.Corpus`.""" tokenizer = get_tokenizer(args) return tacl.Corpus(args.corpus, tokenizer)
[ "def", "get_corpus", "(", "args", ")", ":", "tokenizer", "=", "get_tokenizer", "(", "args", ")", "return", "tacl", ".", "Corpus", "(", "args", ".", "corpus", ",", "tokenizer", ")" ]
Returns a `tacl.Corpus`.
[ "Returns", "a", "tacl", ".", "Corpus", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L97-L100
ajenhl/tacl
tacl/cli/utils.py
get_data_store
def get_data_store(args): """Returns a `tacl.DataStore`.""" return tacl.DataStore(args.db, args.memory, args.ram)
python
def get_data_store(args): """Returns a `tacl.DataStore`.""" return tacl.DataStore(args.db, args.memory, args.ram)
[ "def", "get_data_store", "(", "args", ")", ":", "return", "tacl", ".", "DataStore", "(", "args", ".", "db", ",", "args", ".", "memory", ",", "args", ".", "ram", ")" ]
Returns a `tacl.DataStore`.
[ "Returns", "a", "tacl", ".", "DataStore", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L103-L105
ajenhl/tacl
tacl/cli/utils.py
get_ngrams
def get_ngrams(path): """Returns a list of n-grams read from the file at `path`.""" with open(path, encoding='utf-8') as fh: ngrams = [ngram.strip() for ngram in fh.readlines()] return ngrams
python
def get_ngrams(path): """Returns a list of n-grams read from the file at `path`.""" with open(path, encoding='utf-8') as fh: ngrams = [ngram.strip() for ngram in fh.readlines()] return ngrams
[ "def", "get_ngrams", "(", "path", ")", ":", "with", "open", "(", "path", ",", "encoding", "=", "'utf-8'", ")", "as", "fh", ":", "ngrams", "=", "[", "ngram", ".", "strip", "(", ")", "for", "ngram", "in", "fh", ".", "readlines", "(", ")", "]", "ret...
Returns a list of n-grams read from the file at `path`.
[ "Returns", "a", "list", "of", "n", "-", "grams", "read", "from", "the", "file", "at", "path", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L108-L112
ajenhl/tacl
tacl/text.py
Text.excise
def excise(self, ngrams, replacement): """Returns the token content of this text with every occurrence of each n-gram in `ngrams` replaced with `replacement`. The replacing is performed on each n-gram by descending order of length. :param ngrams: n-grams to be replaced :type ngrams: `list` of `str` :param replacement: replacement string :type replacement: `str` :rtype: `str` """ content = self.get_token_content() ngrams.sort(key=len, reverse=True) for ngram in ngrams: content = content.replace(ngram, replacement) return content
python
def excise(self, ngrams, replacement): """Returns the token content of this text with every occurrence of each n-gram in `ngrams` replaced with `replacement`. The replacing is performed on each n-gram by descending order of length. :param ngrams: n-grams to be replaced :type ngrams: `list` of `str` :param replacement: replacement string :type replacement: `str` :rtype: `str` """ content = self.get_token_content() ngrams.sort(key=len, reverse=True) for ngram in ngrams: content = content.replace(ngram, replacement) return content
[ "def", "excise", "(", "self", ",", "ngrams", ",", "replacement", ")", ":", "content", "=", "self", ".", "get_token_content", "(", ")", "ngrams", ".", "sort", "(", "key", "=", "len", ",", "reverse", "=", "True", ")", "for", "ngram", "in", "ngrams", ":...
Returns the token content of this text with every occurrence of each n-gram in `ngrams` replaced with `replacement`. The replacing is performed on each n-gram by descending order of length. :param ngrams: n-grams to be replaced :type ngrams: `list` of `str` :param replacement: replacement string :type replacement: `str` :rtype: `str`
[ "Returns", "the", "token", "content", "of", "this", "text", "with", "every", "occurrence", "of", "each", "n", "-", "gram", "in", "ngrams", "replaced", "with", "replacement", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L22-L40
ajenhl/tacl
tacl/text.py
Text.get_ngrams
def get_ngrams(self, minimum, maximum, skip_sizes=None): """Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param skip_sizes: sizes to not generate n-grams for :type skip_sizes: `list` of `int` :rtype: `generator` """ skip_sizes = skip_sizes or [] tokens = self.get_tokens() for size in range(minimum, maximum + 1): if size not in skip_sizes: ngrams = collections.Counter(self._ngrams(tokens, size)) yield (size, ngrams)
python
def get_ngrams(self, minimum, maximum, skip_sizes=None): """Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param skip_sizes: sizes to not generate n-grams for :type skip_sizes: `list` of `int` :rtype: `generator` """ skip_sizes = skip_sizes or [] tokens = self.get_tokens() for size in range(minimum, maximum + 1): if size not in skip_sizes: ngrams = collections.Counter(self._ngrams(tokens, size)) yield (size, ngrams)
[ "def", "get_ngrams", "(", "self", ",", "minimum", ",", "maximum", ",", "skip_sizes", "=", "None", ")", ":", "skip_sizes", "=", "skip_sizes", "or", "[", "]", "tokens", "=", "self", ".", "get_tokens", "(", ")", "for", "size", "in", "range", "(", "minimum...
Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param skip_sizes: sizes to not generate n-grams for :type skip_sizes: `list` of `int` :rtype: `generator`
[ "Returns", "a", "generator", "supplying", "the", "n", "-", "grams", "(", "minimum", "<", "=", "n", "<", "=", "maximum", ")", "for", "this", "text", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L50-L72
ajenhl/tacl
tacl/text.py
Text._ngrams
def _ngrams(self, sequence, degree): """Returns the n-grams generated from `sequence`. Based on the ngrams function from the Natural Language Toolkit. Each n-gram in the returned list is a string with whitespace removed. :param sequence: the source data to be converted into n-grams :type sequence: sequence :param degree: the degree of the n-grams :type degree: `int` :rtype: `list` of `str` """ count = max(0, len(sequence) - degree + 1) # The extra split and join are due to having to handle # whitespace within a CBETA token (eg, [(禾*尤)\n/上/日]). return [self._tokenizer.joiner.join( self._tokenizer.joiner.join(sequence[i:i+degree]).split()) for i in range(count)]
python
def _ngrams(self, sequence, degree): """Returns the n-grams generated from `sequence`. Based on the ngrams function from the Natural Language Toolkit. Each n-gram in the returned list is a string with whitespace removed. :param sequence: the source data to be converted into n-grams :type sequence: sequence :param degree: the degree of the n-grams :type degree: `int` :rtype: `list` of `str` """ count = max(0, len(sequence) - degree + 1) # The extra split and join are due to having to handle # whitespace within a CBETA token (eg, [(禾*尤)\n/上/日]). return [self._tokenizer.joiner.join( self._tokenizer.joiner.join(sequence[i:i+degree]).split()) for i in range(count)]
[ "def", "_ngrams", "(", "self", ",", "sequence", ",", "degree", ")", ":", "count", "=", "max", "(", "0", ",", "len", "(", "sequence", ")", "-", "degree", "+", "1", ")", "# The extra split and join are due to having to handle", "# whitespace within a CBETA token (eg...
Returns the n-grams generated from `sequence`. Based on the ngrams function from the Natural Language Toolkit. Each n-gram in the returned list is a string with whitespace removed. :param sequence: the source data to be converted into n-grams :type sequence: sequence :param degree: the degree of the n-grams :type degree: `int` :rtype: `list` of `str`
[ "Returns", "the", "n", "-", "grams", "generated", "from", "sequence", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L91-L112
ajenhl/tacl
tacl/text.py
FilteredWitnessText.get_filter_ngrams_pattern
def get_filter_ngrams_pattern(filter_ngrams): """Returns a compiled regular expression matching on any of the n-grams in `filter_ngrams`. :param filter_ngrams: n-grams to use in regular expression :type filter_ngrams: `list` of `str` :rtype: `_sre.SRE_Pattern` """ return re.compile('|'.join([re.escape(ngram) for ngram in filter_ngrams]))
python
def get_filter_ngrams_pattern(filter_ngrams): """Returns a compiled regular expression matching on any of the n-grams in `filter_ngrams`. :param filter_ngrams: n-grams to use in regular expression :type filter_ngrams: `list` of `str` :rtype: `_sre.SRE_Pattern` """ return re.compile('|'.join([re.escape(ngram) for ngram in filter_ngrams]))
[ "def", "get_filter_ngrams_pattern", "(", "filter_ngrams", ")", ":", "return", "re", ".", "compile", "(", "'|'", ".", "join", "(", "[", "re", ".", "escape", "(", "ngram", ")", "for", "ngram", "in", "filter_ngrams", "]", ")", ")" ]
Returns a compiled regular expression matching on any of the n-grams in `filter_ngrams`. :param filter_ngrams: n-grams to use in regular expression :type filter_ngrams: `list` of `str` :rtype: `_sre.SRE_Pattern`
[ "Returns", "a", "compiled", "regular", "expression", "matching", "on", "any", "of", "the", "n", "-", "grams", "in", "filter_ngrams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L161-L171
ajenhl/tacl
tacl/text.py
FilteredWitnessText.get_ngrams
def get_ngrams(self, minimum, maximum, filter_ngrams): """Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param filter_ngrams: n-grams that must be contained by the generated n-grams :type filter_ngrams: `list` :rtype: `generator` """ tokens = self.get_tokens() filter_pattern = self.get_filter_ngrams_pattern(filter_ngrams) for size in range(minimum, maximum + 1): ngrams = collections.Counter( self._ngrams(tokens, size, filter_pattern)) yield (size, ngrams)
python
def get_ngrams(self, minimum, maximum, filter_ngrams): """Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param filter_ngrams: n-grams that must be contained by the generated n-grams :type filter_ngrams: `list` :rtype: `generator` """ tokens = self.get_tokens() filter_pattern = self.get_filter_ngrams_pattern(filter_ngrams) for size in range(minimum, maximum + 1): ngrams = collections.Counter( self._ngrams(tokens, size, filter_pattern)) yield (size, ngrams)
[ "def", "get_ngrams", "(", "self", ",", "minimum", ",", "maximum", ",", "filter_ngrams", ")", ":", "tokens", "=", "self", ".", "get_tokens", "(", ")", "filter_pattern", "=", "self", ".", "get_filter_ngrams_pattern", "(", "filter_ngrams", ")", "for", "size", "...
Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` :param filter_ngrams: n-grams that must be contained by the generated n-grams :type filter_ngrams: `list` :rtype: `generator`
[ "Returns", "a", "generator", "supplying", "the", "n", "-", "grams", "(", "minimum", "<", "=", "n", "<", "=", "maximum", ")", "for", "this", "text", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L173-L196
peeringdb/django-peeringdb
django_peeringdb/client_adaptor/backend.py
Backend.set_relation_many_to_many
def set_relation_many_to_many(self, obj, field_name, objs): "Set a many-to-many field on an object" relation = getattr(obj, field_name) if hasattr(relation, 'set'): relation.set(objs) # Django 2.x else: setattr(obj, field_name, objs)
python
def set_relation_many_to_many(self, obj, field_name, objs): "Set a many-to-many field on an object" relation = getattr(obj, field_name) if hasattr(relation, 'set'): relation.set(objs) # Django 2.x else: setattr(obj, field_name, objs)
[ "def", "set_relation_many_to_many", "(", "self", ",", "obj", ",", "field_name", ",", "objs", ")", ":", "relation", "=", "getattr", "(", "obj", ",", "field_name", ")", "if", "hasattr", "(", "relation", ",", "'set'", ")", ":", "relation", ".", "set", "(", ...
Set a many-to-many field on an object
[ "Set", "a", "many", "-", "to", "-", "many", "field", "on", "an", "object" ]
train
https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/backend.py#L136-L142
peeringdb/django-peeringdb
django_peeringdb/client_adaptor/backend.py
Backend.detect_missing_relations
def detect_missing_relations(self, obj, exc): """ Parse error messages and collect the missing-relationship errors as a dict of Resource -> {id set} """ missing = defaultdict(set) for name, err in exc.error_dict.items(): # check if it was a relationship that doesnt exist locally pattern = r".+ with id (\d+) does not exist.+" m = re.match(pattern, str(err)) if m: field = obj._meta.get_field(name) res = self.get_resource(field.related_model) missing[res].add(int(m.group(1))) return missing
python
def detect_missing_relations(self, obj, exc): """ Parse error messages and collect the missing-relationship errors as a dict of Resource -> {id set} """ missing = defaultdict(set) for name, err in exc.error_dict.items(): # check if it was a relationship that doesnt exist locally pattern = r".+ with id (\d+) does not exist.+" m = re.match(pattern, str(err)) if m: field = obj._meta.get_field(name) res = self.get_resource(field.related_model) missing[res].add(int(m.group(1))) return missing
[ "def", "detect_missing_relations", "(", "self", ",", "obj", ",", "exc", ")", ":", "missing", "=", "defaultdict", "(", "set", ")", "for", "name", ",", "err", "in", "exc", ".", "error_dict", ".", "items", "(", ")", ":", "# check if it was a relationship that d...
Parse error messages and collect the missing-relationship errors as a dict of Resource -> {id set}
[ "Parse", "error", "messages", "and", "collect", "the", "missing", "-", "relationship", "errors", "as", "a", "dict", "of", "Resource", "-", ">", "{", "id", "set", "}" ]
train
https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/backend.py#L157-L171
peeringdb/django-peeringdb
django_peeringdb/client_adaptor/backend.py
Backend.detect_uniqueness_error
def detect_uniqueness_error(self, exc): """ Parse error, and if it describes any violations of a uniqueness constraint, return the corresponding fields, else None """ pattern = r"(\w+) with this (\w+) already exists" fields = [] if isinstance(exc, IntegrityError): return self._detect_integrity_error(exc) assert isinstance(exc, ValidationError), TypeError for name, err in exc.error_dict.items(): if re.search(pattern, str(err)): fields.append(name) return fields or None
python
def detect_uniqueness_error(self, exc): """ Parse error, and if it describes any violations of a uniqueness constraint, return the corresponding fields, else None """ pattern = r"(\w+) with this (\w+) already exists" fields = [] if isinstance(exc, IntegrityError): return self._detect_integrity_error(exc) assert isinstance(exc, ValidationError), TypeError for name, err in exc.error_dict.items(): if re.search(pattern, str(err)): fields.append(name) return fields or None
[ "def", "detect_uniqueness_error", "(", "self", ",", "exc", ")", ":", "pattern", "=", "r\"(\\w+) with this (\\w+) already exists\"", "fields", "=", "[", "]", "if", "isinstance", "(", "exc", ",", "IntegrityError", ")", ":", "return", "self", ".", "_detect_integrity_...
Parse error, and if it describes any violations of a uniqueness constraint, return the corresponding fields, else None
[ "Parse", "error", "and", "if", "it", "describes", "any", "violations", "of", "a", "uniqueness", "constraint", "return", "the", "corresponding", "fields", "else", "None" ]
train
https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/backend.py#L173-L188
SuperCowPowers/chains
chains/links/tls_meta.py
TLSMeta.tls_meta_data
def tls_meta_data(self): """Pull out the TLS metadata for each flow in the input_stream""" # For each flow process the contents for flow in self.input_stream: # Just TCP for now if flow['protocol'] != 'TCP': continue # Client to Server if flow['direction'] == 'CTS': # Try to process the payload as a set of TLS records try: tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload']) if bytes_consumed != len(flow['payload']): logger.warning('Incomplete TLS record at the end...') # Process the TLS records flow['tls'] = {'type':'TLS_CTS', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}} except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception): flow['tls'] = None # Server to Client else: try: tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload']) if bytes_consumed != len(flow['payload']): logger.warning('Incomplete TLS record at the end...') # Process the TLS records flow['tls'] = {'type':'TLS_STC', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}} except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception): flow['tls'] = None # All done yield flow
python
def tls_meta_data(self): """Pull out the TLS metadata for each flow in the input_stream""" # For each flow process the contents for flow in self.input_stream: # Just TCP for now if flow['protocol'] != 'TCP': continue # Client to Server if flow['direction'] == 'CTS': # Try to process the payload as a set of TLS records try: tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload']) if bytes_consumed != len(flow['payload']): logger.warning('Incomplete TLS record at the end...') # Process the TLS records flow['tls'] = {'type':'TLS_CTS', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}} except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception): flow['tls'] = None # Server to Client else: try: tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload']) if bytes_consumed != len(flow['payload']): logger.warning('Incomplete TLS record at the end...') # Process the TLS records flow['tls'] = {'type':'TLS_STC', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}} except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception): flow['tls'] = None # All done yield flow
[ "def", "tls_meta_data", "(", "self", ")", ":", "# For each flow process the contents", "for", "flow", "in", "self", ".", "input_stream", ":", "# Just TCP for now", "if", "flow", "[", "'protocol'", "]", "!=", "'TCP'", ":", "continue", "# Client to Server", "if", "f...
Pull out the TLS metadata for each flow in the input_stream
[ "Pull", "out", "the", "TLS", "metadata", "for", "each", "flow", "in", "the", "input_stream" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/tls_meta.py#L22-L59
SuperCowPowers/chains
chains/utils/data_utils.py
make_dict
def make_dict(obj): """This method creates a dictionary out of a non-builtin object""" # Recursion base case if is_builtin(obj) or isinstance(obj, OrderedDict): return obj output_dict = {} for key in dir(obj): if not key.startswith('__') and not callable(getattr(obj, key)): attr = getattr(obj, key) if isinstance(attr, list): output_dict[key] = [] for item in attr: output_dict[key].append(make_dict(item)) else: output_dict[key] = make_dict(attr) # All done return output_dict
python
def make_dict(obj): """This method creates a dictionary out of a non-builtin object""" # Recursion base case if is_builtin(obj) or isinstance(obj, OrderedDict): return obj output_dict = {} for key in dir(obj): if not key.startswith('__') and not callable(getattr(obj, key)): attr = getattr(obj, key) if isinstance(attr, list): output_dict[key] = [] for item in attr: output_dict[key].append(make_dict(item)) else: output_dict[key] = make_dict(attr) # All done return output_dict
[ "def", "make_dict", "(", "obj", ")", ":", "# Recursion base case", "if", "is_builtin", "(", "obj", ")", "or", "isinstance", "(", "obj", ",", "OrderedDict", ")", ":", "return", "obj", "output_dict", "=", "{", "}", "for", "key", "in", "dir", "(", "obj", ...
This method creates a dictionary out of a non-builtin object
[ "This", "method", "creates", "a", "dictionary", "out", "of", "a", "non", "-", "builtin", "object" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/data_utils.py#L9-L28
SuperCowPowers/chains
chains/utils/data_utils.py
get_value
def get_value(data, key): """Follow the dot notation to get the proper field, then perform the action Args: data: the data as a dictionary (required to be a dictionary) key: the key (as dot notation) into the data that gives the field (IP.src) Returns: the value of the field(subfield) if it exist, otherwise None """ ref = data try: for subkey in key.split('.'): if isinstance(ref, dict): ref = ref[subkey] else: print('CRITICAL: Cannot use subkey %s on non-dictionary element' % subkey) return None return ref # In general KeyErrors are expected except KeyError: return None
python
def get_value(data, key): """Follow the dot notation to get the proper field, then perform the action Args: data: the data as a dictionary (required to be a dictionary) key: the key (as dot notation) into the data that gives the field (IP.src) Returns: the value of the field(subfield) if it exist, otherwise None """ ref = data try: for subkey in key.split('.'): if isinstance(ref, dict): ref = ref[subkey] else: print('CRITICAL: Cannot use subkey %s on non-dictionary element' % subkey) return None return ref # In general KeyErrors are expected except KeyError: return None
[ "def", "get_value", "(", "data", ",", "key", ")", ":", "ref", "=", "data", "try", ":", "for", "subkey", "in", "key", ".", "split", "(", "'.'", ")", ":", "if", "isinstance", "(", "ref", ",", "dict", ")", ":", "ref", "=", "ref", "[", "subkey", "]...
Follow the dot notation to get the proper field, then perform the action Args: data: the data as a dictionary (required to be a dictionary) key: the key (as dot notation) into the data that gives the field (IP.src) Returns: the value of the field(subfield) if it exist, otherwise None
[ "Follow", "the", "dot", "notation", "to", "get", "the", "proper", "field", "then", "perform", "the", "action" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/data_utils.py#L33-L55
ajenhl/tacl
tacl/statistics_report.py
StatisticsReport.csv
def csv(self, fh): """Writes the report data to `fh` in CSV format and returns it. :param fh: file to write data to :type fh: file object :rtype: file object """ self._stats.to_csv(fh, encoding='utf-8', index=False) return fh
python
def csv(self, fh): """Writes the report data to `fh` in CSV format and returns it. :param fh: file to write data to :type fh: file object :rtype: file object """ self._stats.to_csv(fh, encoding='utf-8', index=False) return fh
[ "def", "csv", "(", "self", ",", "fh", ")", ":", "self", ".", "_stats", ".", "to_csv", "(", "fh", ",", "encoding", "=", "'utf-8'", ",", "index", "=", "False", ")", "return", "fh" ]
Writes the report data to `fh` in CSV format and returns it. :param fh: file to write data to :type fh: file object :rtype: file object
[ "Writes", "the", "report", "data", "to", "fh", "in", "CSV", "format", "and", "returns", "it", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L19-L28
ajenhl/tacl
tacl/statistics_report.py
StatisticsReport.generate_statistics
def generate_statistics(self): """Replaces result rows with summary statistics about the results. These statistics give the filename, total matching tokens, percentage of matching tokens and label for each witness in the results. """ matches = self._matches witness_fields = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME] witnesses = matches[witness_fields].drop_duplicates() rows = [] for index, (work, siglum, label) in witnesses.iterrows(): witness = self._corpus.get_witness(work, siglum) witness_matches = matches[ (matches[constants.WORK_FIELDNAME] == work) & (matches[constants.SIGLUM_FIELDNAME] == siglum)] total_count, matching_count = self._process_witness( witness, witness_matches) percentage = matching_count / total_count * 100 rows.append({constants.WORK_FIELDNAME: work, constants.SIGLUM_FIELDNAME: siglum, constants.COUNT_TOKENS_FIELDNAME: matching_count, constants.TOTAL_TOKENS_FIELDNAME: total_count, constants.PERCENTAGE_FIELDNAME: percentage, constants.LABEL_FIELDNAME: label}) self._stats = pd.DataFrame( rows, columns=constants.STATISTICS_FIELDNAMES)
python
def generate_statistics(self): """Replaces result rows with summary statistics about the results. These statistics give the filename, total matching tokens, percentage of matching tokens and label for each witness in the results. """ matches = self._matches witness_fields = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME, constants.LABEL_FIELDNAME] witnesses = matches[witness_fields].drop_duplicates() rows = [] for index, (work, siglum, label) in witnesses.iterrows(): witness = self._corpus.get_witness(work, siglum) witness_matches = matches[ (matches[constants.WORK_FIELDNAME] == work) & (matches[constants.SIGLUM_FIELDNAME] == siglum)] total_count, matching_count = self._process_witness( witness, witness_matches) percentage = matching_count / total_count * 100 rows.append({constants.WORK_FIELDNAME: work, constants.SIGLUM_FIELDNAME: siglum, constants.COUNT_TOKENS_FIELDNAME: matching_count, constants.TOTAL_TOKENS_FIELDNAME: total_count, constants.PERCENTAGE_FIELDNAME: percentage, constants.LABEL_FIELDNAME: label}) self._stats = pd.DataFrame( rows, columns=constants.STATISTICS_FIELDNAMES)
[ "def", "generate_statistics", "(", "self", ")", ":", "matches", "=", "self", ".", "_matches", "witness_fields", "=", "[", "constants", ".", "WORK_FIELDNAME", ",", "constants", ".", "SIGLUM_FIELDNAME", ",", "constants", ".", "LABEL_FIELDNAME", "]", "witnesses", "...
Replaces result rows with summary statistics about the results. These statistics give the filename, total matching tokens, percentage of matching tokens and label for each witness in the results.
[ "Replaces", "result", "rows", "with", "summary", "statistics", "about", "the", "results", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L30-L58
ajenhl/tacl
tacl/statistics_report.py
StatisticsReport._generate_text_from_slices
def _generate_text_from_slices(self, full_text, slices): """Return a single string consisting of the parts specified in `slices` joined together by the tokenizer's joining string. :param full_text: the text to be sliced :type full_text: `str` :param slices: list of slice indices to apply to `full_text` :type slices: `list` of `list`\s :rtype: `str` """ sliced_text = [] for start, end in slices: sliced_text.append(full_text[start:end]) return self._tokenizer.joiner.join(sliced_text)
python
def _generate_text_from_slices(self, full_text, slices): """Return a single string consisting of the parts specified in `slices` joined together by the tokenizer's joining string. :param full_text: the text to be sliced :type full_text: `str` :param slices: list of slice indices to apply to `full_text` :type slices: `list` of `list`\s :rtype: `str` """ sliced_text = [] for start, end in slices: sliced_text.append(full_text[start:end]) return self._tokenizer.joiner.join(sliced_text)
[ "def", "_generate_text_from_slices", "(", "self", ",", "full_text", ",", "slices", ")", ":", "sliced_text", "=", "[", "]", "for", "start", ",", "end", "in", "slices", ":", "sliced_text", ".", "append", "(", "full_text", "[", "start", ":", "end", "]", ")"...
Return a single string consisting of the parts specified in `slices` joined together by the tokenizer's joining string. :param full_text: the text to be sliced :type full_text: `str` :param slices: list of slice indices to apply to `full_text` :type slices: `list` of `list`\s :rtype: `str`
[ "Return", "a", "single", "string", "consisting", "of", "the", "parts", "specified", "in", "slices", "joined", "together", "by", "the", "tokenizer", "s", "joining", "string", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L60-L74
ajenhl/tacl
tacl/statistics_report.py
StatisticsReport._merge_slices
def _merge_slices(match_slices): """Return a list of slice indices lists derived from `match_slices` with no overlaps.""" # Sort by earliest range, then by largest range. match_slices.sort(key=lambda x: (x[0], -x[1])) merged_slices = [match_slices.pop(0)] for slice_indices in match_slices: last_end = merged_slices[-1][1] if slice_indices[0] <= last_end: if slice_indices[1] > last_end: merged_slices[-1][1] = slice_indices[1] else: merged_slices.append(slice_indices) return merged_slices
python
def _merge_slices(match_slices): """Return a list of slice indices lists derived from `match_slices` with no overlaps.""" # Sort by earliest range, then by largest range. match_slices.sort(key=lambda x: (x[0], -x[1])) merged_slices = [match_slices.pop(0)] for slice_indices in match_slices: last_end = merged_slices[-1][1] if slice_indices[0] <= last_end: if slice_indices[1] > last_end: merged_slices[-1][1] = slice_indices[1] else: merged_slices.append(slice_indices) return merged_slices
[ "def", "_merge_slices", "(", "match_slices", ")", ":", "# Sort by earliest range, then by largest range.", "match_slices", ".", "sort", "(", "key", "=", "lambda", "x", ":", "(", "x", "[", "0", "]", ",", "-", "x", "[", "1", "]", ")", ")", "merged_slices", "...
Return a list of slice indices lists derived from `match_slices` with no overlaps.
[ "Return", "a", "list", "of", "slice", "indices", "lists", "derived", "from", "match_slices", "with", "no", "overlaps", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L77-L90
ajenhl/tacl
tacl/statistics_report.py
StatisticsReport._process_witness
def _process_witness(self, witness, matches): """Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int` """ # In order to provide a correct count of matched tokens, # avoiding the twin dangers of counting the same token # multiple times due to being part of multiple n-grams (which # can happen even in reduced results) and not counting tokens # due to an n-gram overlapping with itself or another n-gram, # a bit of work is required. # # Using regular expressions, get the slice indices for all # matches (including overlapping ones) for all matching # n-grams. Merge these slices together (without overlap) and # create a Text using that text, which can then be tokenised # and the tokens counted. tokens = witness.get_tokens() full_text = witness.get_token_content() fields = [constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME] match_slices = [] for index, (ngram, size) in matches[fields].iterrows(): pattern = re.compile(re.escape(ngram)) # Because the same n-gram may overlap itself ("heh" in the # string "heheh"), re.findall cannot be used. start = 0 while True: match = pattern.search(full_text, start) if match is None: break match_slices.append([match.start(), match.end()]) start = match.start() + 1 merged_slices = self._merge_slices(match_slices) match_content = self._generate_text_from_slices( full_text, merged_slices) match_text = Text(match_content, self._tokenizer) return len(tokens), len(match_text.get_tokens())
python
def _process_witness(self, witness, matches): """Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int` """ # In order to provide a correct count of matched tokens, # avoiding the twin dangers of counting the same token # multiple times due to being part of multiple n-grams (which # can happen even in reduced results) and not counting tokens # due to an n-gram overlapping with itself or another n-gram, # a bit of work is required. # # Using regular expressions, get the slice indices for all # matches (including overlapping ones) for all matching # n-grams. Merge these slices together (without overlap) and # create a Text using that text, which can then be tokenised # and the tokens counted. tokens = witness.get_tokens() full_text = witness.get_token_content() fields = [constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME] match_slices = [] for index, (ngram, size) in matches[fields].iterrows(): pattern = re.compile(re.escape(ngram)) # Because the same n-gram may overlap itself ("heh" in the # string "heheh"), re.findall cannot be used. start = 0 while True: match = pattern.search(full_text, start) if match is None: break match_slices.append([match.start(), match.end()]) start = match.start() + 1 merged_slices = self._merge_slices(match_slices) match_content = self._generate_text_from_slices( full_text, merged_slices) match_text = Text(match_content, self._tokenizer) return len(tokens), len(match_text.get_tokens())
[ "def", "_process_witness", "(", "self", ",", "witness", ",", "matches", ")", ":", "# In order to provide a correct count of matched tokens,", "# avoiding the twin dangers of counting the same token", "# multiple times due to being part of multiple n-grams (which", "# can happen even in red...
Return the counts of total tokens and matching tokens in `witness`. :param witness: witness text :type witness: `tacl.WitnessText` :param matches: n-gram matches :type matches: `pandas.DataFrame` :rtype: `tuple` of `int`
[ "Return", "the", "counts", "of", "total", "tokens", "and", "matching", "tokens", "in", "witness", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L92-L133
ajenhl/tacl
tacl/stripper.py
Stripper.get_witnesses
def get_witnesses(self, source_tree): """Returns a list of all witnesses of variant readings in `source_tree` along with their XML ids. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `list` of `tuple` """ witnesses = [] witness_elements = source_tree.xpath( '/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/' 'tei:listWit/tei:witness', namespaces=constants.NAMESPACES) for witness_element in witness_elements: witnesses.append((witness_element.text, witness_element.get(constants.XML + 'id'))) if not witnesses: witnesses = [(constants.BASE_WITNESS, constants.BASE_WITNESS_ID)] return witnesses
python
def get_witnesses(self, source_tree): """Returns a list of all witnesses of variant readings in `source_tree` along with their XML ids. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `list` of `tuple` """ witnesses = [] witness_elements = source_tree.xpath( '/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/' 'tei:listWit/tei:witness', namespaces=constants.NAMESPACES) for witness_element in witness_elements: witnesses.append((witness_element.text, witness_element.get(constants.XML + 'id'))) if not witnesses: witnesses = [(constants.BASE_WITNESS, constants.BASE_WITNESS_ID)] return witnesses
[ "def", "get_witnesses", "(", "self", ",", "source_tree", ")", ":", "witnesses", "=", "[", "]", "witness_elements", "=", "source_tree", ".", "xpath", "(", "'/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/'", "'tei:listWit/tei:witness'", ",", "namespaces", "=", "constan...
Returns a list of all witnesses of variant readings in `source_tree` along with their XML ids. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `list` of `tuple`
[ "Returns", "a", "list", "of", "all", "witnesses", "of", "variant", "readings", "in", "source_tree", "along", "with", "their", "XML", "ids", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/stripper.py#L31-L49
SuperCowPowers/chains
examples/tag_example.py
run
def run(iface_name=None, bpf=None, summary=None, max_packets=50): """Run the Simple Packet Printer Example""" # Create the classes streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets) meta = packet_meta.PacketMeta() rdns = reverse_dns.ReverseDNS() tags = packet_tags.PacketTags() tmeta = transport_meta.TransportMeta() printer = packet_summary.PacketSummary() # Set up the chain meta.link(streamer) rdns.link(meta) tags.link(rdns) tmeta.link(tags) printer.link(tmeta) # Pull the chain printer.pull()
python
def run(iface_name=None, bpf=None, summary=None, max_packets=50): """Run the Simple Packet Printer Example""" # Create the classes streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets) meta = packet_meta.PacketMeta() rdns = reverse_dns.ReverseDNS() tags = packet_tags.PacketTags() tmeta = transport_meta.TransportMeta() printer = packet_summary.PacketSummary() # Set up the chain meta.link(streamer) rdns.link(meta) tags.link(rdns) tmeta.link(tags) printer.link(tmeta) # Pull the chain printer.pull()
[ "def", "run", "(", "iface_name", "=", "None", ",", "bpf", "=", "None", ",", "summary", "=", "None", ",", "max_packets", "=", "50", ")", ":", "# Create the classes", "streamer", "=", "packet_streamer", ".", "PacketStreamer", "(", "iface_name", "=", "iface_nam...
Run the Simple Packet Printer Example
[ "Run", "the", "Simple", "Packet", "Printer", "Example" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/examples/tag_example.py#L10-L29
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport.generate
def generate(self, output_dir, catalogue, results, label): """Generates the report, writing it to `output_dir`.""" data = results.get_raw_data() labels = catalogue.ordered_labels ngrams = self._generate_results(output_dir, labels, data) ngram_table = self._generate_ngram_table(output_dir, labels, data) corpus_table = self._generate_corpus_table(labels, ngrams) context = {'corpus_table': corpus_table, 'focus_label': label, 'labels': labels, 'ngram_table': ngram_table, 'sep': os.sep} report_name = 'lifetime-{}.html'.format(label) self._write(context, output_dir, report_name)
python
def generate(self, output_dir, catalogue, results, label): """Generates the report, writing it to `output_dir`.""" data = results.get_raw_data() labels = catalogue.ordered_labels ngrams = self._generate_results(output_dir, labels, data) ngram_table = self._generate_ngram_table(output_dir, labels, data) corpus_table = self._generate_corpus_table(labels, ngrams) context = {'corpus_table': corpus_table, 'focus_label': label, 'labels': labels, 'ngram_table': ngram_table, 'sep': os.sep} report_name = 'lifetime-{}.html'.format(label) self._write(context, output_dir, report_name)
[ "def", "generate", "(", "self", ",", "output_dir", ",", "catalogue", ",", "results", ",", "label", ")", ":", "data", "=", "results", ".", "get_raw_data", "(", ")", "labels", "=", "catalogue", ".", "ordered_labels", "ngrams", "=", "self", ".", "_generate_re...
Generates the report, writing it to `output_dir`.
[ "Generates", "the", "report", "writing", "it", "to", "output_dir", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L30-L40