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/lifetime_report.py | LifetimeReport._generate_corpus_table | def _generate_corpus_table(self, labels, ngrams):
"""Returns an HTML table containing data on each corpus' n-grams."""
html = []
for label in labels:
html.append(self._render_corpus_row(label, ngrams))
return '\n'.join(html) | python | def _generate_corpus_table(self, labels, ngrams):
"""Returns an HTML table containing data on each corpus' n-grams."""
html = []
for label in labels:
html.append(self._render_corpus_row(label, ngrams))
return '\n'.join(html) | [
"def",
"_generate_corpus_table",
"(",
"self",
",",
"labels",
",",
"ngrams",
")",
":",
"html",
"=",
"[",
"]",
"for",
"label",
"in",
"labels",
":",
"html",
".",
"append",
"(",
"self",
".",
"_render_corpus_row",
"(",
"label",
",",
"ngrams",
")",
")",
"ret... | Returns an HTML table containing data on each corpus' n-grams. | [
"Returns",
"an",
"HTML",
"table",
"containing",
"data",
"on",
"each",
"corpus",
"n",
"-",
"grams",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L42-L47 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport._generate_ngram_table | def _generate_ngram_table(self, output_dir, labels, results):
"""Returns an HTML table containing data on each n-gram in
`results`."""
html = []
grouped = results.groupby(constants.NGRAM_FIELDNAME)
row_template = self._generate_ngram_row_template(labels)
for name, group i... | python | def _generate_ngram_table(self, output_dir, labels, results):
"""Returns an HTML table containing data on each n-gram in
`results`."""
html = []
grouped = results.groupby(constants.NGRAM_FIELDNAME)
row_template = self._generate_ngram_row_template(labels)
for name, group i... | [
"def",
"_generate_ngram_table",
"(",
"self",
",",
"output_dir",
",",
"labels",
",",
"results",
")",
":",
"html",
"=",
"[",
"]",
"grouped",
"=",
"results",
".",
"groupby",
"(",
"constants",
".",
"NGRAM_FIELDNAME",
")",
"row_template",
"=",
"self",
".",
"_ge... | Returns an HTML table containing data on each n-gram in
`results`. | [
"Returns",
"an",
"HTML",
"table",
"containing",
"data",
"on",
"each",
"n",
"-",
"gram",
"in",
"results",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L49-L58 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport._generate_ngram_row_template | def _generate_ngram_row_template(self, labels):
"""Returns the HTML template for a row in the n-gram table."""
cells = ['<td>{ngram}</td>']
for label in labels:
cells.append('<td>{{{}}}</td>'.format(label))
return '\n'.join(cells) | python | def _generate_ngram_row_template(self, labels):
"""Returns the HTML template for a row in the n-gram table."""
cells = ['<td>{ngram}</td>']
for label in labels:
cells.append('<td>{{{}}}</td>'.format(label))
return '\n'.join(cells) | [
"def",
"_generate_ngram_row_template",
"(",
"self",
",",
"labels",
")",
":",
"cells",
"=",
"[",
"'<td>{ngram}</td>'",
"]",
"for",
"label",
"in",
"labels",
":",
"cells",
".",
"append",
"(",
"'<td>{{{}}}</td>'",
".",
"format",
"(",
"label",
")",
")",
"return",... | Returns the HTML template for a row in the n-gram table. | [
"Returns",
"the",
"HTML",
"template",
"for",
"a",
"row",
"in",
"the",
"n",
"-",
"gram",
"table",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L60-L65 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport._generate_results | def _generate_results(self, output_dir, labels, results):
"""Creates multiple results files in `output_dir` based on `results`.
For each label in `labels`, create three results file,
containing those n-grams with that label that first occurred,
only occurred, and last occurred in that l... | python | def _generate_results(self, output_dir, labels, results):
"""Creates multiple results files in `output_dir` based on `results`.
For each label in `labels`, create three results file,
containing those n-grams with that label that first occurred,
only occurred, and last occurred in that l... | [
"def",
"_generate_results",
"(",
"self",
",",
"output_dir",
",",
"labels",
",",
"results",
")",
":",
"ngrams",
"=",
"{",
"}",
"for",
"idx",
",",
"label",
"in",
"enumerate",
"(",
"labels",
")",
":",
"now_results",
"=",
"results",
"[",
"results",
"[",
"c... | Creates multiple results files in `output_dir` based on `results`.
For each label in `labels`, create three results file,
containing those n-grams with that label that first occurred,
only occurred, and last occurred in that label. | [
"Creates",
"multiple",
"results",
"files",
"in",
"output_dir",
"based",
"on",
"results",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L67-L103 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport._render_corpus_row | def _render_corpus_row(self, label, ngrams):
"""Returns the HTML for a corpus row."""
row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n'
'<td>{last}</td>\n</tr>')
cell_data = {'label': label}
for period in ('first', 'only', 'last'):
cell_data[... | python | def _render_corpus_row(self, label, ngrams):
"""Returns the HTML for a corpus row."""
row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n'
'<td>{last}</td>\n</tr>')
cell_data = {'label': label}
for period in ('first', 'only', 'last'):
cell_data[... | [
"def",
"_render_corpus_row",
"(",
"self",
",",
"label",
",",
"ngrams",
")",
":",
"row",
"=",
"(",
"'<tr>\\n<td>{label}</td>\\n<td>{first}</td>\\n<td>{only}</td>\\n'",
"'<td>{last}</td>\\n</tr>'",
")",
"cell_data",
"=",
"{",
"'label'",
":",
"label",
"}",
"for",
"period... | Returns the HTML for a corpus row. | [
"Returns",
"the",
"HTML",
"for",
"a",
"corpus",
"row",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L105-L112 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport._render_ngram_row | def _render_ngram_row(self, ngram, ngram_group, row_template, labels):
"""Returns the HTML for an n-gram row."""
cell_data = {'ngram': ngram}
label_data = {}
for label in labels:
label_data[label] = []
work_grouped = ngram_group.groupby(constants.WORK_FIELDNAME)
... | python | def _render_ngram_row(self, ngram, ngram_group, row_template, labels):
"""Returns the HTML for an n-gram row."""
cell_data = {'ngram': ngram}
label_data = {}
for label in labels:
label_data[label] = []
work_grouped = ngram_group.groupby(constants.WORK_FIELDNAME)
... | [
"def",
"_render_ngram_row",
"(",
"self",
",",
"ngram",
",",
"ngram_group",
",",
"row_template",
",",
"labels",
")",
":",
"cell_data",
"=",
"{",
"'ngram'",
":",
"ngram",
"}",
"label_data",
"=",
"{",
"}",
"for",
"label",
"in",
"labels",
":",
"label_data",
... | Returns the HTML for an n-gram row. | [
"Returns",
"the",
"HTML",
"for",
"an",
"n",
"-",
"gram",
"row",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L114-L134 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport._save_results | def _save_results(self, output_dir, label, results, ngrams, type_label):
"""Saves `results` filtered by `label` and `ngram` to `output_dir`.
:param output_dir: directory to save results to
:type output_dir: `str`
:param label: catalogue label of results, used in saved filename
:... | python | def _save_results(self, output_dir, label, results, ngrams, type_label):
"""Saves `results` filtered by `label` and `ngram` to `output_dir`.
:param output_dir: directory to save results to
:type output_dir: `str`
:param label: catalogue label of results, used in saved filename
:... | [
"def",
"_save_results",
"(",
"self",
",",
"output_dir",
",",
"label",
",",
"results",
",",
"ngrams",
",",
"type_label",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'{}-{}.csv'",
".",
"format",
"(",
"label",
",",
"typ... | Saves `results` filtered by `label` and `ngram` to `output_dir`.
:param output_dir: directory to save results to
:type output_dir: `str`
:param label: catalogue label of results, used in saved filename
:type label: `str`
:param results: results to filter and save
:type r... | [
"Saves",
"results",
"filtered",
"by",
"label",
"and",
"ngram",
"to",
"output_dir",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L136-L154 |
SuperCowPowers/chains | chains/links/link.py | Link.link | def link(self, stream_instance):
"""Set my input stream"""
if isinstance(stream_instance, collections.Iterable):
self.input_stream = stream_instance
elif getattr(stream_instance, 'output_stream', None):
self.input_stream = stream_instance.output_stream
else:
... | python | def link(self, stream_instance):
"""Set my input stream"""
if isinstance(stream_instance, collections.Iterable):
self.input_stream = stream_instance
elif getattr(stream_instance, 'output_stream', None):
self.input_stream = stream_instance.output_stream
else:
... | [
"def",
"link",
"(",
"self",
",",
"stream_instance",
")",
":",
"if",
"isinstance",
"(",
"stream_instance",
",",
"collections",
".",
"Iterable",
")",
":",
"self",
".",
"input_stream",
"=",
"stream_instance",
"elif",
"getattr",
"(",
"stream_instance",
",",
"'outp... | Set my input stream | [
"Set",
"my",
"input",
"stream"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/link.py#L18-L25 |
ajenhl/tacl | tacl/catalogue.py | Catalogue.generate | def generate(self, path, label):
"""Creates default data from the corpus at `path`, marking all
works with `label`.
:param path: path to a corpus directory
:type path: `str`
:param label: label to categorise each work as
:type label: `str`
"""
for filena... | python | def generate(self, path, label):
"""Creates default data from the corpus at `path`, marking all
works with `label`.
:param path: path to a corpus directory
:type path: `str`
:param label: label to categorise each work as
:type label: `str`
"""
for filena... | [
"def",
"generate",
"(",
"self",
",",
"path",
",",
"label",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"self",
"[",
"filename",
"]",
"=",
"label"
] | Creates default data from the corpus at `path`, marking all
works with `label`.
:param path: path to a corpus directory
:type path: `str`
:param label: label to categorise each work as
:type label: `str` | [
"Creates",
"default",
"data",
"from",
"the",
"corpus",
"at",
"path",
"marking",
"all",
"works",
"with",
"label",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L15-L26 |
ajenhl/tacl | tacl/catalogue.py | Catalogue.get_works_by_label | def get_works_by_label(self, label):
"""Returns a list of works associated with `label`.
:param label: label of works to be returned
:type label: `str`
:rtype: `list` of `str`
"""
return [work for work, c_label in self.items() if c_label == label] | python | def get_works_by_label(self, label):
"""Returns a list of works associated with `label`.
:param label: label of works to be returned
:type label: `str`
:rtype: `list` of `str`
"""
return [work for work, c_label in self.items() if c_label == label] | [
"def",
"get_works_by_label",
"(",
"self",
",",
"label",
")",
":",
"return",
"[",
"work",
"for",
"work",
",",
"c_label",
"in",
"self",
".",
"items",
"(",
")",
"if",
"c_label",
"==",
"label",
"]"
] | Returns a list of works associated with `label`.
:param label: label of works to be returned
:type label: `str`
:rtype: `list` of `str` | [
"Returns",
"a",
"list",
"of",
"works",
"associated",
"with",
"label",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L28-L36 |
ajenhl/tacl | tacl/catalogue.py | Catalogue.load | def load(self, path):
"""Loads the data from `path` into the catalogue.
:param path: path to catalogue file
:type path: `str`
"""
fieldnames = ['work', 'label']
with open(path, 'r', encoding='utf-8', newline='') as fh:
reader = csv.DictReader(fh, delimiter='... | python | def load(self, path):
"""Loads the data from `path` into the catalogue.
:param path: path to catalogue file
:type path: `str`
"""
fieldnames = ['work', 'label']
with open(path, 'r', encoding='utf-8', newline='') as fh:
reader = csv.DictReader(fh, delimiter='... | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"fieldnames",
"=",
"[",
"'work'",
",",
"'label'",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
",",
"newline",
"=",
"''",
")",
"as",
"fh",
":",
"reader",
"=",
"c... | Loads the data from `path` into the catalogue.
:param path: path to catalogue file
:type path: `str` | [
"Loads",
"the",
"data",
"from",
"path",
"into",
"the",
"catalogue",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L60-L79 |
ajenhl/tacl | tacl/catalogue.py | Catalogue.relabel | def relabel(self, label_map):
"""Returns a copy of the catalogue with the labels remapped according
to `label_map`.
`label_map` is a dictionary mapping existing labels to new
labels. Any existing label that is not given a mapping is
deleted from the resulting catalogue.
... | python | def relabel(self, label_map):
"""Returns a copy of the catalogue with the labels remapped according
to `label_map`.
`label_map` is a dictionary mapping existing labels to new
labels. Any existing label that is not given a mapping is
deleted from the resulting catalogue.
... | [
"def",
"relabel",
"(",
"self",
",",
"label_map",
")",
":",
"catalogue",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"to_delete",
"=",
"set",
"(",
")",
"for",
"work",
",",
"old_label",
"in",
"catalogue",
".",
"items",
"(",
")",
":",
"if",
"old_lab... | Returns a copy of the catalogue with the labels remapped according
to `label_map`.
`label_map` is a dictionary mapping existing labels to new
labels. Any existing label that is not given a mapping is
deleted from the resulting catalogue.
:param label_map: mapping of labels to n... | [
"Returns",
"a",
"copy",
"of",
"the",
"catalogue",
"with",
"the",
"labels",
"remapped",
"according",
"to",
"label_map",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L81-L103 |
ajenhl/tacl | tacl/catalogue.py | Catalogue.remove_label | def remove_label(self, label):
"""Removes `label` from the catalogue, by removing all works carrying
it.
:param label: label to remove
:type label: `str`
"""
works_to_delete = []
for work, work_label in self.items():
if work_label == label:
... | python | def remove_label(self, label):
"""Removes `label` from the catalogue, by removing all works carrying
it.
:param label: label to remove
:type label: `str`
"""
works_to_delete = []
for work, work_label in self.items():
if work_label == label:
... | [
"def",
"remove_label",
"(",
"self",
",",
"label",
")",
":",
"works_to_delete",
"=",
"[",
"]",
"for",
"work",
",",
"work_label",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"work_label",
"==",
"label",
":",
"works_to_delete",
".",
"append",
"(",
"w... | Removes `label` from the catalogue, by removing all works carrying
it.
:param label: label to remove
:type label: `str` | [
"Removes",
"label",
"from",
"the",
"catalogue",
"by",
"removing",
"all",
"works",
"carrying",
"it",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L105-L120 |
ajenhl/tacl | tacl/catalogue.py | Catalogue.save | def save(self, path):
"""Saves this catalogue's data to `path`.
:param path: file path to save catalogue data to
:type path: `str`
"""
writer = csv.writer(open(path, 'w', newline=''), delimiter=' ')
rows = list(self.items())
rows.sort(key=lambda x: x[0])
... | python | def save(self, path):
"""Saves this catalogue's data to `path`.
:param path: file path to save catalogue data to
:type path: `str`
"""
writer = csv.writer(open(path, 'w', newline=''), delimiter=' ')
rows = list(self.items())
rows.sort(key=lambda x: x[0])
... | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"open",
"(",
"path",
",",
"'w'",
",",
"newline",
"=",
"''",
")",
",",
"delimiter",
"=",
"' '",
")",
"rows",
"=",
"list",
"(",
"self",
".",
"items",
"("... | Saves this catalogue's data to `path`.
:param path: file path to save catalogue data to
:type path: `str` | [
"Saves",
"this",
"catalogue",
"s",
"data",
"to",
"path",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L122-L132 |
SuperCowPowers/chains | chains/links/dns_meta.py | DNSMeta.dns_meta_data | def dns_meta_data(self):
"""Pull out the dns metadata for packet/transport in the input_stream"""
# For each packet process the contents
for packet in self.input_stream:
# Skip packets without transport info (ARP/ICMP/IGMP/whatever)
if 'transport' not in packet:
... | python | def dns_meta_data(self):
"""Pull out the dns metadata for packet/transport in the input_stream"""
# For each packet process the contents
for packet in self.input_stream:
# Skip packets without transport info (ARP/ICMP/IGMP/whatever)
if 'transport' not in packet:
... | [
"def",
"dns_meta_data",
"(",
"self",
")",
":",
"# For each packet process the contents",
"for",
"packet",
"in",
"self",
".",
"input_stream",
":",
"# Skip packets without transport info (ARP/ICMP/IGMP/whatever)",
"if",
"'transport'",
"not",
"in",
"packet",
":",
"continue",
... | Pull out the dns metadata for packet/transport in the input_stream | [
"Pull",
"out",
"the",
"dns",
"metadata",
"for",
"packet",
"/",
"transport",
"in",
"the",
"input_stream"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L43-L61 |
SuperCowPowers/chains | chains/links/dns_meta.py | DNSMeta._dns_info_mapper | def _dns_info_mapper(self, raw_dns):
"""The method maps the specific fields/flags in a DNS record to human readable form"""
output = {}
# Indentification
output['identification'] = raw_dns['id']
# Pull out all the flags
flags = {}
flags['type'] = 'query' if raw_... | python | def _dns_info_mapper(self, raw_dns):
"""The method maps the specific fields/flags in a DNS record to human readable form"""
output = {}
# Indentification
output['identification'] = raw_dns['id']
# Pull out all the flags
flags = {}
flags['type'] = 'query' if raw_... | [
"def",
"_dns_info_mapper",
"(",
"self",
",",
"raw_dns",
")",
":",
"output",
"=",
"{",
"}",
"# Indentification",
"output",
"[",
"'identification'",
"]",
"=",
"raw_dns",
"[",
"'id'",
"]",
"# Pull out all the flags",
"flags",
"=",
"{",
"}",
"flags",
"[",
"'type... | The method maps the specific fields/flags in a DNS record to human readable form | [
"The",
"method",
"maps",
"the",
"specific",
"fields",
"/",
"flags",
"in",
"a",
"DNS",
"record",
"to",
"human",
"readable",
"form"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L63-L126 |
SuperCowPowers/chains | chains/links/dns_meta.py | DNSMeta._dns_weird | def _dns_weird(self, record):
"""Look for weird stuff in dns record using a set of criteria to mark the weird stuff"""
weird = {}
# Zero should always be 0
if record['flags']['zero'] != 0:
weird['zero'] = record['flags']['zero']
# Trucated may indicate an exfil
... | python | def _dns_weird(self, record):
"""Look for weird stuff in dns record using a set of criteria to mark the weird stuff"""
weird = {}
# Zero should always be 0
if record['flags']['zero'] != 0:
weird['zero'] = record['flags']['zero']
# Trucated may indicate an exfil
... | [
"def",
"_dns_weird",
"(",
"self",
",",
"record",
")",
":",
"weird",
"=",
"{",
"}",
"# Zero should always be 0",
"if",
"record",
"[",
"'flags'",
"]",
"[",
"'zero'",
"]",
"!=",
"0",
":",
"weird",
"[",
"'zero'",
"]",
"=",
"record",
"[",
"'flags'",
"]",
... | Look for weird stuff in dns record using a set of criteria to mark the weird stuff | [
"Look",
"for",
"weird",
"stuff",
"in",
"dns",
"record",
"using",
"a",
"set",
"of",
"criteria",
"to",
"mark",
"the",
"weird",
"stuff"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L128-L176 |
ajenhl/tacl | tacl/corpus.py | Corpus.get_sigla | def get_sigla(self, work):
"""Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str`
"""
return [os.path.splitext(os.path.basename(path))[0]
for path in glob.glob(os.path.join(self._path, work, ... | python | def get_sigla(self, work):
"""Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str`
"""
return [os.path.splitext(os.path.basename(path))[0]
for path in glob.glob(os.path.join(self._path, work, ... | [
"def",
"get_sigla",
"(",
"self",
",",
"work",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
... | Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str` | [
"Returns",
"a",
"list",
"of",
"all",
"of",
"the",
"sigla",
"for",
"work",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L24-L33 |
ajenhl/tacl | tacl/corpus.py | Corpus.get_witness | def get_witness(self, work, siglum, text_class=WitnessText):
"""Returns a `WitnessText` representing the file associated with
`work` and `siglum`.
Combined, `work` and `siglum` form the basis of a filename for
retrieving the text.
:param work: name of work
:type work: `... | python | def get_witness(self, work, siglum, text_class=WitnessText):
"""Returns a `WitnessText` representing the file associated with
`work` and `siglum`.
Combined, `work` and `siglum` form the basis of a filename for
retrieving the text.
:param work: name of work
:type work: `... | [
"def",
"get_witness",
"(",
"self",
",",
"work",
",",
"siglum",
",",
"text_class",
"=",
"WitnessText",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work",
",",
"siglum",
"+",
"'.txt'",
")",
"self",
".",
"_logger",
".",
"debug",
"("... | Returns a `WitnessText` representing the file associated with
`work` and `siglum`.
Combined, `work` and `siglum` form the basis of a filename for
retrieving the text.
:param work: name of work
:type work: `str`
:param siglum: siglum of witness
:type siglum: `str... | [
"Returns",
"a",
"WitnessText",
"representing",
"the",
"file",
"associated",
"with",
"work",
"and",
"siglum",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L35-L55 |
ajenhl/tacl | tacl/corpus.py | Corpus.get_witnesses | def get_witnesses(self, name='*'):
"""Returns a generator supplying `WitnessText` objects for each work
in the corpus.
:rtype: `generator` of `WitnessText`
"""
for filepath in glob.glob(os.path.join(self._path, name, '*.txt')):
if os.path.isfile(filepath):
... | python | def get_witnesses(self, name='*'):
"""Returns a generator supplying `WitnessText` objects for each work
in the corpus.
:rtype: `generator` of `WitnessText`
"""
for filepath in glob.glob(os.path.join(self._path, name, '*.txt')):
if os.path.isfile(filepath):
... | [
"def",
"get_witnesses",
"(",
"self",
",",
"name",
"=",
"'*'",
")",
":",
"for",
"filepath",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"name",
",",
"'*.txt'",
")",
")",
":",
"if",
"os",
".",
"... | Returns a generator supplying `WitnessText` objects for each work
in the corpus.
:rtype: `generator` of `WitnessText` | [
"Returns",
"a",
"generator",
"supplying",
"WitnessText",
"objects",
"for",
"each",
"work",
"in",
"the",
"corpus",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L57-L68 |
ajenhl/tacl | tacl/corpus.py | Corpus.get_works | def get_works(self):
"""Returns a list of the names of all works in the corpus.
:rtype: `list` of `str`
"""
return [os.path.split(filepath)[1] for filepath in
glob.glob(os.path.join(self._path, '*'))
if os.path.isdir(filepath)] | python | def get_works(self):
"""Returns a list of the names of all works in the corpus.
:rtype: `list` of `str`
"""
return [os.path.split(filepath)[1] for filepath in
glob.glob(os.path.join(self._path, '*'))
if os.path.isdir(filepath)] | [
"def",
"get_works",
"(",
"self",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"split",
"(",
"filepath",
")",
"[",
"1",
"]",
"for",
"filepath",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"... | Returns a list of the names of all works in the corpus.
:rtype: `list` of `str` | [
"Returns",
"a",
"list",
"of",
"the",
"names",
"of",
"all",
"works",
"in",
"the",
"corpus",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L70-L78 |
ajenhl/tacl | tacl/decorators.py | requires_columns | def requires_columns(required_cols):
"""Decorator that raises a `MalformedResultsError` if any of
`required_cols` is not present as a column in the matches of the
`Results` object bearing the decorated method.
:param required_cols: names of required columns
:type required_cols: `list` of `str`
... | python | def requires_columns(required_cols):
"""Decorator that raises a `MalformedResultsError` if any of
`required_cols` is not present as a column in the matches of the
`Results` object bearing the decorated method.
:param required_cols: names of required columns
:type required_cols: `list` of `str`
... | [
"def",
"requires_columns",
"(",
"required_cols",
")",
":",
"def",
"dec",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"actual_cols",
"=",
"list",
"(",
"args",
"[",
... | Decorator that raises a `MalformedResultsError` if any of
`required_cols` is not present as a column in the matches of the
`Results` object bearing the decorated method.
:param required_cols: names of required columns
:type required_cols: `list` of `str` | [
"Decorator",
"that",
"raises",
"a",
"MalformedResultsError",
"if",
"any",
"of",
"required_cols",
"is",
"not",
"present",
"as",
"a",
"column",
"in",
"the",
"matches",
"of",
"the",
"Results",
"object",
"bearing",
"the",
"decorated",
"method",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/decorators.py#L7-L30 |
SuperCowPowers/chains | chains/links/reverse_dns.py | ReverseDNS.process_for_rdns | def process_for_rdns(self):
"""Look through my input stream for the fields in ip_field_list and
try to do a reverse dns lookup on those fields.
"""
# For each packet process the contents
for item in self.input_stream:
# Do for both the src and dst
for... | python | def process_for_rdns(self):
"""Look through my input stream for the fields in ip_field_list and
try to do a reverse dns lookup on those fields.
"""
# For each packet process the contents
for item in self.input_stream:
# Do for both the src and dst
for... | [
"def",
"process_for_rdns",
"(",
"self",
")",
":",
"# For each packet process the contents",
"for",
"item",
"in",
"self",
".",
"input_stream",
":",
"# Do for both the src and dst",
"for",
"endpoint",
"in",
"[",
"'src'",
",",
"'dst'",
"]",
":",
"# Sanity check (might be... | Look through my input stream for the fields in ip_field_list and
try to do a reverse dns lookup on those fields. | [
"Look",
"through",
"my",
"input",
"stream",
"for",
"the",
"fields",
"in",
"ip_field_list",
"and",
"try",
"to",
"do",
"a",
"reverse",
"dns",
"lookup",
"on",
"those",
"fields",
"."
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/reverse_dns.py#L26-L68 |
ajenhl/tacl | tacl/colour.py | hsv_to_rgb | def hsv_to_rgb(h, s, v):
"""Convert a colour specified in HSV (hue, saturation, value) to an
RGB string.
Based on the algorithm at
https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
:param h: hue, a value between 0 and 1
:type h: `int`
:param s: saturation, a value between 0 and 1... | python | def hsv_to_rgb(h, s, v):
"""Convert a colour specified in HSV (hue, saturation, value) to an
RGB string.
Based on the algorithm at
https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
:param h: hue, a value between 0 and 1
:type h: `int`
:param s: saturation, a value between 0 and 1... | [
"def",
"hsv_to_rgb",
"(",
"h",
",",
"s",
",",
"v",
")",
":",
"c",
"=",
"v",
"*",
"s",
"hp",
"=",
"h",
"*",
"6",
"x",
"=",
"c",
"*",
"(",
"1",
"-",
"abs",
"(",
"hp",
"%",
"2",
"-",
"1",
")",
")",
"if",
"hp",
"<",
"1",
":",
"r",
",",
... | Convert a colour specified in HSV (hue, saturation, value) to an
RGB string.
Based on the algorithm at
https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
:param h: hue, a value between 0 and 1
:type h: `int`
:param s: saturation, a value between 0 and 1
:type s: `int`
:param v... | [
"Convert",
"a",
"colour",
"specified",
"in",
"HSV",
"(",
"hue",
"saturation",
"value",
")",
"to",
"an",
"RGB",
"string",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/colour.py#L4-L37 |
ajenhl/tacl | tacl/colour.py | generate_colours | def generate_colours(n):
"""Return a list of `n` distinct colours, each represented as an RGB
string suitable for use in CSS.
Based on the code at
http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
:param n: number of colours to generate
:type n: `int`
:rtype... | python | def generate_colours(n):
"""Return a list of `n` distinct colours, each represented as an RGB
string suitable for use in CSS.
Based on the code at
http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
:param n: number of colours to generate
:type n: `int`
:rtype... | [
"def",
"generate_colours",
"(",
"n",
")",
":",
"colours",
"=",
"[",
"]",
"golden_ratio_conjugate",
"=",
"0.618033988749895",
"h",
"=",
"0.8",
"# Initial hue",
"s",
"=",
"0.7",
"# Fixed saturation",
"v",
"=",
"0.95",
"# Fixed value",
"for",
"i",
"in",
"range",
... | Return a list of `n` distinct colours, each represented as an RGB
string suitable for use in CSS.
Based on the code at
http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
:param n: number of colours to generate
:type n: `int`
:rtype: `list` of `str` | [
"Return",
"a",
"list",
"of",
"n",
"distinct",
"colours",
"each",
"represented",
"as",
"an",
"RGB",
"string",
"suitable",
"for",
"use",
"in",
"CSS",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/colour.py#L40-L61 |
SuperCowPowers/chains | chains/links/packet_tags.py | PacketTags.tag_stuff | def tag_stuff(self):
"""Look through my input stream for the fields to be tagged"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Make sure it has a tags field (which is a set)
if 'tags' not in item:
item['tags'] = s... | python | def tag_stuff(self):
"""Look through my input stream for the fields to be tagged"""
# For each packet in the pcap process the contents
for item in self.input_stream:
# Make sure it has a tags field (which is a set)
if 'tags' not in item:
item['tags'] = s... | [
"def",
"tag_stuff",
"(",
"self",
")",
":",
"# For each packet in the pcap process the contents",
"for",
"item",
"in",
"self",
".",
"input_stream",
":",
"# Make sure it has a tags field (which is a set)",
"if",
"'tags'",
"not",
"in",
"item",
":",
"item",
"[",
"'tags'",
... | Look through my input stream for the fields to be tagged | [
"Look",
"through",
"my",
"input",
"stream",
"for",
"the",
"fields",
"to",
"be",
"tagged"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_tags.py#L29-L47 |
SuperCowPowers/chains | chains/links/packet_tags.py | PacketTags._tag_net_direction | def _tag_net_direction(data):
"""Create a tag based on the direction of the traffic"""
# IP or IPv6
src = data['packet']['src_domain']
dst = data['packet']['dst_domain']
if src == 'internal':
if dst == 'internal' or 'multicast' in dst or 'broadcast' in dst:
... | python | def _tag_net_direction(data):
"""Create a tag based on the direction of the traffic"""
# IP or IPv6
src = data['packet']['src_domain']
dst = data['packet']['dst_domain']
if src == 'internal':
if dst == 'internal' or 'multicast' in dst or 'broadcast' in dst:
... | [
"def",
"_tag_net_direction",
"(",
"data",
")",
":",
"# IP or IPv6",
"src",
"=",
"data",
"[",
"'packet'",
"]",
"[",
"'src_domain'",
"]",
"dst",
"=",
"data",
"[",
"'packet'",
"]",
"[",
"'dst_domain'",
"]",
"if",
"src",
"==",
"'internal'",
":",
"if",
"dst",... | Create a tag based on the direction of the traffic | [
"Create",
"a",
"tag",
"based",
"on",
"the",
"direction",
"of",
"the",
"traffic"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_tags.py#L50-L64 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpus.get_witnesses | def get_witnesses(self, source_tree):
"""Returns a sorted list of all witnesses of readings in
`source_tree`, and the elements that bear @wit attributes.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `tuple` of `list`\s
... | python | def get_witnesses(self, source_tree):
"""Returns a sorted list of all witnesses of readings in
`source_tree`, and the elements that bear @wit attributes.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `tuple` of `list`\s
... | [
"def",
"get_witnesses",
"(",
"self",
",",
"source_tree",
")",
":",
"witnesses",
"=",
"set",
"(",
")",
"bearers",
"=",
"source_tree",
".",
"xpath",
"(",
"'//tei:app/tei:*[@wit]'",
",",
"namespaces",
"=",
"constants",
".",
"NAMESPACES",
")",
"for",
"bearer",
"... | Returns a sorted list of all witnesses of readings in
`source_tree`, and the elements that bear @wit attributes.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `tuple` of `list`\s | [
"Returns",
"a",
"sorted",
"list",
"of",
"all",
"witnesses",
"of",
"readings",
"in",
"source_tree",
"and",
"the",
"elements",
"that",
"bear",
"@wit",
"attributes",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L101-L117 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpus._handle_witnesses | def _handle_witnesses(self, root):
"""Returns `root` with a witness list added to the TEI header and @wit
values changed to references."""
witnesses, bearers = self.get_witnesses(root)
if not witnesses:
return root
source_desc = root.xpath(
'/tei:teiCorpus... | python | def _handle_witnesses(self, root):
"""Returns `root` with a witness list added to the TEI header and @wit
values changed to references."""
witnesses, bearers = self.get_witnesses(root)
if not witnesses:
return root
source_desc = root.xpath(
'/tei:teiCorpus... | [
"def",
"_handle_witnesses",
"(",
"self",
",",
"root",
")",
":",
"witnesses",
",",
"bearers",
"=",
"self",
".",
"get_witnesses",
"(",
"root",
")",
"if",
"not",
"witnesses",
":",
"return",
"root",
"source_desc",
"=",
"root",
".",
"xpath",
"(",
"'/tei:teiCorp... | Returns `root` with a witness list added to the TEI header and @wit
values changed to references. | [
"Returns",
"root",
"with",
"a",
"witness",
"list",
"added",
"to",
"the",
"TEI",
"header",
"and"
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L122-L139 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpus._output_work | def _output_work(self, work, root):
"""Saves the TEI XML document `root` at the path `work`."""
output_filename = os.path.join(self._output_dir, work)
tree = etree.ElementTree(root)
tree.write(output_filename, encoding='utf-8', pretty_print=True) | python | def _output_work(self, work, root):
"""Saves the TEI XML document `root` at the path `work`."""
output_filename = os.path.join(self._output_dir, work)
tree = etree.ElementTree(root)
tree.write(output_filename, encoding='utf-8', pretty_print=True) | [
"def",
"_output_work",
"(",
"self",
",",
"work",
",",
"root",
")",
":",
"output_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_output_dir",
",",
"work",
")",
"tree",
"=",
"etree",
".",
"ElementTree",
"(",
"root",
")",
"tree",
"."... | Saves the TEI XML document `root` at the path `work`. | [
"Saves",
"the",
"TEI",
"XML",
"document",
"root",
"at",
"the",
"path",
"work",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L141-L145 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpus._populate_header | def _populate_header(self, root):
"""Populate the teiHeader of the teiCorpus with useful information
from the teiHeader of the first TEI part."""
# If this gets more complicated, it should be handled via an XSLT.
title_stmt = root.xpath(
'tei:teiHeader/tei:fileDesc/tei:titleS... | python | def _populate_header(self, root):
"""Populate the teiHeader of the teiCorpus with useful information
from the teiHeader of the first TEI part."""
# If this gets more complicated, it should be handled via an XSLT.
title_stmt = root.xpath(
'tei:teiHeader/tei:fileDesc/tei:titleS... | [
"def",
"_populate_header",
"(",
"self",
",",
"root",
")",
":",
"# If this gets more complicated, it should be handled via an XSLT.",
"title_stmt",
"=",
"root",
".",
"xpath",
"(",
"'tei:teiHeader/tei:fileDesc/tei:titleStmt'",
",",
"namespaces",
"=",
"constants",
".",
"NAMESP... | Populate the teiHeader of the teiCorpus with useful information
from the teiHeader of the first TEI part. | [
"Populate",
"the",
"teiHeader",
"of",
"the",
"teiCorpus",
"with",
"useful",
"information",
"from",
"the",
"teiHeader",
"of",
"the",
"first",
"TEI",
"part",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L147-L168 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpus._update_refs | def _update_refs(self, root, bearers, attribute, ref_text, xml_id):
"""Change `ref_text` on `bearers` to xml:id references.
:param root: root of TEI document
:type root: `etree._Element`
:param bearers: elements bearing `attribute`
:param attribute: attribute to update
:... | python | def _update_refs(self, root, bearers, attribute, ref_text, xml_id):
"""Change `ref_text` on `bearers` to xml:id references.
:param root: root of TEI document
:type root: `etree._Element`
:param bearers: elements bearing `attribute`
:param attribute: attribute to update
:... | [
"def",
"_update_refs",
"(",
"self",
",",
"root",
",",
"bearers",
",",
"attribute",
",",
"ref_text",
",",
"xml_id",
")",
":",
"ref",
"=",
"' #{} '",
".",
"format",
"(",
"xml_id",
")",
"for",
"bearer",
"in",
"bearers",
":",
"attribute_text",
"=",
"bearer",... | Change `ref_text` on `bearers` to xml:id references.
:param root: root of TEI document
:type root: `etree._Element`
:param bearers: elements bearing `attribute`
:param attribute: attribute to update
:type attribute: `str`
:param ref_text: text to replace
:type re... | [
"Change",
"ref_text",
"on",
"bearers",
"to",
"xml",
":",
"id",
"references",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L189-L207 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpusCBETAGitHub._extract_work | def _extract_work(self, filename):
"""Returns the name of the work in `filename`.
Some works are divided into multiple parts that need to be
joined together.
:param filename: filename of TEI
:type filename: `str`
:rtype: `tuple` of `str`
"""
basename = ... | python | def _extract_work(self, filename):
"""Returns the name of the work in `filename`.
Some works are divided into multiple parts that need to be
joined together.
:param filename: filename of TEI
:type filename: `str`
:rtype: `tuple` of `str`
"""
basename = ... | [
"def",
"_extract_work",
"(",
"self",
",",
"filename",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
")",
"[",
"0",
"]",
"match",
"=",
"self",
".",
"work_pattern",
".",
... | Returns the name of the work in `filename`.
Some works are divided into multiple parts that need to be
joined together.
:param filename: filename of TEI
:type filename: `str`
:rtype: `tuple` of `str` | [
"Returns",
"the",
"name",
"of",
"the",
"work",
"in",
"filename",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L220-L238 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpusCBETAGitHub.get_resps | def get_resps(self, source_tree):
"""Returns a sorted list of all resps in `source_tree`, and the
elements that bear @resp attributes.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `tuple` of `lists`
"""
resps = ... | python | def get_resps(self, source_tree):
"""Returns a sorted list of all resps in `source_tree`, and the
elements that bear @resp attributes.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `tuple` of `lists`
"""
resps = ... | [
"def",
"get_resps",
"(",
"self",
",",
"source_tree",
")",
":",
"resps",
"=",
"set",
"(",
")",
"bearers",
"=",
"source_tree",
".",
"xpath",
"(",
"'//*[@resp]'",
",",
"namespaces",
"=",
"constants",
".",
"NAMESPACES",
")",
"for",
"bearer",
"in",
"bearers",
... | Returns a sorted list of all resps in `source_tree`, and the
elements that bear @resp attributes.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `tuple` of `lists` | [
"Returns",
"a",
"sorted",
"list",
"of",
"all",
"resps",
"in",
"source_tree",
"and",
"the",
"elements",
"that",
"bear",
"@resp",
"attributes",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L240-L256 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpusCBETAGitHub._handle_resps | def _handle_resps(self, root):
"""Returns `root` with a resp list added to the TEI header and @resp
values changed to references."""
resps, bearers = self.get_resps(root)
if not resps:
return root
file_desc = root.xpath(
'/tei:teiCorpus/tei:teiHeader/tei:f... | python | def _handle_resps(self, root):
"""Returns `root` with a resp list added to the TEI header and @resp
values changed to references."""
resps, bearers = self.get_resps(root)
if not resps:
return root
file_desc = root.xpath(
'/tei:teiCorpus/tei:teiHeader/tei:f... | [
"def",
"_handle_resps",
"(",
"self",
",",
"root",
")",
":",
"resps",
",",
"bearers",
"=",
"self",
".",
"get_resps",
"(",
"root",
")",
"if",
"not",
"resps",
":",
"return",
"root",
"file_desc",
"=",
"root",
".",
"xpath",
"(",
"'/tei:teiCorpus/tei:teiHeader/t... | Returns `root` with a resp list added to the TEI header and @resp
values changed to references. | [
"Returns",
"root",
"with",
"a",
"resp",
"list",
"added",
"to",
"the",
"TEI",
"header",
"and"
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L258-L279 |
ajenhl/tacl | tacl/tei_corpus.py | TEICorpusCBETAGitHub._tidy | def _tidy(self, work, file_path):
"""Transforms the file at `file_path` into simpler XML and returns
that.
"""
output_file = os.path.join(self._output_dir, work)
self._logger.info('Tidying file {} into {}'.format(
file_path, output_file))
try:
tei... | python | def _tidy(self, work, file_path):
"""Transforms the file at `file_path` into simpler XML and returns
that.
"""
output_file = os.path.join(self._output_dir, work)
self._logger.info('Tidying file {} into {}'.format(
file_path, output_file))
try:
tei... | [
"def",
"_tidy",
"(",
"self",
",",
"work",
",",
"file_path",
")",
":",
"output_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_output_dir",
",",
"work",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Tidying file {} into {}'",
".",
"fo... | Transforms the file at `file_path` into simpler XML and returns
that. | [
"Transforms",
"the",
"file",
"at",
"file_path",
"into",
"simpler",
"XML",
"and",
"returns",
"that",
"."
] | train | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L281-L295 |
SuperCowPowers/chains | chains/utils/flow_utils.py | flow_tuple | def flow_tuple(data):
"""Tuple for flow (src, dst, sport, dport, proto)"""
src = net_utils.inet_to_str(data['packet'].get('src')) if data['packet'].get('src') else None
dst = net_utils.inet_to_str(data['packet'].get('dst')) if data['packet'].get('dst') else None
sport = data['transport'].get('sport') if... | python | def flow_tuple(data):
"""Tuple for flow (src, dst, sport, dport, proto)"""
src = net_utils.inet_to_str(data['packet'].get('src')) if data['packet'].get('src') else None
dst = net_utils.inet_to_str(data['packet'].get('dst')) if data['packet'].get('dst') else None
sport = data['transport'].get('sport') if... | [
"def",
"flow_tuple",
"(",
"data",
")",
":",
"src",
"=",
"net_utils",
".",
"inet_to_str",
"(",
"data",
"[",
"'packet'",
"]",
".",
"get",
"(",
"'src'",
")",
")",
"if",
"data",
"[",
"'packet'",
"]",
".",
"get",
"(",
"'src'",
")",
"else",
"None",
"dst"... | Tuple for flow (src, dst, sport, dport, proto) | [
"Tuple",
"for",
"flow",
"(",
"src",
"dst",
"sport",
"dport",
"proto",
")"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L11-L18 |
SuperCowPowers/chains | chains/utils/flow_utils.py | Flow.add_packet | def add_packet(self, packet):
"""Add a packet to this flow"""
# First packet?
if not self.meta['flow_id']:
self.meta['flow_id'] = flow_tuple(packet)
self.meta['src'] = self.meta['flow_id'][0]
self.meta['dst'] = self.meta['flow_id'][1]
self.meta['s... | python | def add_packet(self, packet):
"""Add a packet to this flow"""
# First packet?
if not self.meta['flow_id']:
self.meta['flow_id'] = flow_tuple(packet)
self.meta['src'] = self.meta['flow_id'][0]
self.meta['dst'] = self.meta['flow_id'][1]
self.meta['s... | [
"def",
"add_packet",
"(",
"self",
",",
"packet",
")",
":",
"# First packet?",
"if",
"not",
"self",
".",
"meta",
"[",
"'flow_id'",
"]",
":",
"self",
".",
"meta",
"[",
"'flow_id'",
"]",
"=",
"flow_tuple",
"(",
"packet",
")",
"self",
".",
"meta",
"[",
"... | Add a packet to this flow | [
"Add",
"a",
"packet",
"to",
"this",
"flow"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L48-L96 |
SuperCowPowers/chains | chains/utils/flow_utils.py | Flow.get_flow | def get_flow(self):
"""Reassemble the flow and return all the info/data"""
if self.meta['protocol'] == 'TCP':
self.meta['packet_list'].sort(key=lambda packet: packet['transport']['seq'])
for packet in self.meta['packet_list']:
self.meta['payload'] += packet['trans... | python | def get_flow(self):
"""Reassemble the flow and return all the info/data"""
if self.meta['protocol'] == 'TCP':
self.meta['packet_list'].sort(key=lambda packet: packet['transport']['seq'])
for packet in self.meta['packet_list']:
self.meta['payload'] += packet['trans... | [
"def",
"get_flow",
"(",
"self",
")",
":",
"if",
"self",
".",
"meta",
"[",
"'protocol'",
"]",
"==",
"'TCP'",
":",
"self",
".",
"meta",
"[",
"'packet_list'",
"]",
".",
"sort",
"(",
"key",
"=",
"lambda",
"packet",
":",
"packet",
"[",
"'transport'",
"]",... | Reassemble the flow and return all the info/data | [
"Reassemble",
"the",
"flow",
"and",
"return",
"all",
"the",
"info",
"/",
"data"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L98-L105 |
SuperCowPowers/chains | chains/utils/flow_utils.py | Flow._cts_or_stc | def _cts_or_stc(data):
"""Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?"""
# UDP/TCP
if data['transport']:
# TCP flags
if data['transport']['type'] == 'TCP':
flags = data['transport']['flags']
# Syn/... | python | def _cts_or_stc(data):
"""Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?"""
# UDP/TCP
if data['transport']:
# TCP flags
if data['transport']['type'] == 'TCP':
flags = data['transport']['flags']
# Syn/... | [
"def",
"_cts_or_stc",
"(",
"data",
")",
":",
"# UDP/TCP",
"if",
"data",
"[",
"'transport'",
"]",
":",
"# TCP flags",
"if",
"data",
"[",
"'transport'",
"]",
"[",
"'type'",
"]",
"==",
"'TCP'",
":",
"flags",
"=",
"data",
"[",
"'transport'",
"]",
"[",
"'fl... | Does the data look like a Client to Server (cts) or Server to Client (stc) traffic? | [
"Does",
"the",
"data",
"look",
"like",
"a",
"Client",
"to",
"Server",
"(",
"cts",
")",
"or",
"Server",
"to",
"Client",
"(",
"stc",
")",
"traffic?"
] | train | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L112-L160 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens._generate_tokens | def _generate_tokens(self, text):
"""
Generates tokens for the given code.
"""
# This is technically an undocumented API for Python3, but allows us to use the same API as for
# Python2. See http://stackoverflow.com/a/4952291/328565.
for index, tok in enumerate(tokenize.generate_tokens(io.StringI... | python | def _generate_tokens(self, text):
"""
Generates tokens for the given code.
"""
# This is technically an undocumented API for Python3, but allows us to use the same API as for
# Python2. See http://stackoverflow.com/a/4952291/328565.
for index, tok in enumerate(tokenize.generate_tokens(io.StringI... | [
"def",
"_generate_tokens",
"(",
"self",
",",
"text",
")",
":",
"# This is technically an undocumented API for Python3, but allows us to use the same API as for",
"# Python2. See http://stackoverflow.com/a/4952291/328565.",
"for",
"index",
",",
"tok",
"in",
"enumerate",
"(",
"tokeni... | Generates tokens for the given code. | [
"Generates",
"tokens",
"for",
"the",
"given",
"code",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L79-L89 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.get_token_from_offset | def get_token_from_offset(self, offset):
"""
Returns the token containing the given character offset (0-based position in source text),
or the preceeding token if the position is between tokens.
"""
return self._tokens[bisect.bisect(self._token_offsets, offset) - 1] | python | def get_token_from_offset(self, offset):
"""
Returns the token containing the given character offset (0-based position in source text),
or the preceeding token if the position is between tokens.
"""
return self._tokens[bisect.bisect(self._token_offsets, offset) - 1] | [
"def",
"get_token_from_offset",
"(",
"self",
",",
"offset",
")",
":",
"return",
"self",
".",
"_tokens",
"[",
"bisect",
".",
"bisect",
"(",
"self",
".",
"_token_offsets",
",",
"offset",
")",
"-",
"1",
"]"
] | Returns the token containing the given character offset (0-based position in source text),
or the preceeding token if the position is between tokens. | [
"Returns",
"the",
"token",
"containing",
"the",
"given",
"character",
"offset",
"(",
"0",
"-",
"based",
"position",
"in",
"source",
"text",
")",
"or",
"the",
"preceeding",
"token",
"if",
"the",
"position",
"is",
"between",
"tokens",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L111-L116 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.get_token | def get_token(self, lineno, col_offset):
"""
Returns the token containing the given (lineno, col_offset) position, or the preceeding token
if the position is between tokens.
"""
# TODO: add test for multibyte unicode. We need to translate offsets from ast module (which
# are in utf8) to offsets ... | python | def get_token(self, lineno, col_offset):
"""
Returns the token containing the given (lineno, col_offset) position, or the preceeding token
if the position is between tokens.
"""
# TODO: add test for multibyte unicode. We need to translate offsets from ast module (which
# are in utf8) to offsets ... | [
"def",
"get_token",
"(",
"self",
",",
"lineno",
",",
"col_offset",
")",
":",
"# TODO: add test for multibyte unicode. We need to translate offsets from ast module (which",
"# are in utf8) to offsets into the unicode text. tokenize module seems to use unicode offsets",
"# but isn't explicit."... | Returns the token containing the given (lineno, col_offset) position, or the preceeding token
if the position is between tokens. | [
"Returns",
"the",
"token",
"containing",
"the",
"given",
"(",
"lineno",
"col_offset",
")",
"position",
"or",
"the",
"preceeding",
"token",
"if",
"the",
"position",
"is",
"between",
"tokens",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L118-L126 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.get_token_from_utf8 | def get_token_from_utf8(self, lineno, col_offset):
"""
Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses.
"""
return self.get_token(lineno, self._line_numbers.from_utf8_col(lineno, col_offset)) | python | def get_token_from_utf8(self, lineno, col_offset):
"""
Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses.
"""
return self.get_token(lineno, self._line_numbers.from_utf8_col(lineno, col_offset)) | [
"def",
"get_token_from_utf8",
"(",
"self",
",",
"lineno",
",",
"col_offset",
")",
":",
"return",
"self",
".",
"get_token",
"(",
"lineno",
",",
"self",
".",
"_line_numbers",
".",
"from_utf8_col",
"(",
"lineno",
",",
"col_offset",
")",
")"
] | Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses. | [
"Same",
"as",
"get_token",
"()",
"but",
"interprets",
"col_offset",
"as",
"a",
"UTF8",
"offset",
"which",
"is",
"what",
"ast",
"uses",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L128-L132 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.next_token | def next_token(self, tok, include_extra=False):
"""
Returns the next token after the given one. If include_extra is True, includes non-coding
tokens from the tokenize module, such as NL and COMMENT.
"""
i = tok.index + 1
if not include_extra:
while is_non_coding_token(self._tokens[i].type)... | python | def next_token(self, tok, include_extra=False):
"""
Returns the next token after the given one. If include_extra is True, includes non-coding
tokens from the tokenize module, such as NL and COMMENT.
"""
i = tok.index + 1
if not include_extra:
while is_non_coding_token(self._tokens[i].type)... | [
"def",
"next_token",
"(",
"self",
",",
"tok",
",",
"include_extra",
"=",
"False",
")",
":",
"i",
"=",
"tok",
".",
"index",
"+",
"1",
"if",
"not",
"include_extra",
":",
"while",
"is_non_coding_token",
"(",
"self",
".",
"_tokens",
"[",
"i",
"]",
".",
"... | Returns the next token after the given one. If include_extra is True, includes non-coding
tokens from the tokenize module, such as NL and COMMENT. | [
"Returns",
"the",
"next",
"token",
"after",
"the",
"given",
"one",
".",
"If",
"include_extra",
"is",
"True",
"includes",
"non",
"-",
"coding",
"tokens",
"from",
"the",
"tokenize",
"module",
"such",
"as",
"NL",
"and",
"COMMENT",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L134-L143 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.find_token | def find_token(self, start_token, tok_type, tok_str=None, reverse=False):
"""
Looks for the first token, starting at start_token, that matches tok_type and, if given, the
token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you
can check it with `token.ISEOF(t.type)... | python | def find_token(self, start_token, tok_type, tok_str=None, reverse=False):
"""
Looks for the first token, starting at start_token, that matches tok_type and, if given, the
token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you
can check it with `token.ISEOF(t.type)... | [
"def",
"find_token",
"(",
"self",
",",
"start_token",
",",
"tok_type",
",",
"tok_str",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"t",
"=",
"start_token",
"advance",
"=",
"self",
".",
"prev_token",
"if",
"reverse",
"else",
"self",
".",
"next_to... | Looks for the first token, starting at start_token, that matches tok_type and, if given, the
token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you
can check it with `token.ISEOF(t.type)`. | [
"Looks",
"for",
"the",
"first",
"token",
"starting",
"at",
"start_token",
"that",
"matches",
"tok_type",
"and",
"if",
"given",
"the",
"token",
"string",
".",
"Searches",
"backwards",
"if",
"reverse",
"is",
"True",
".",
"Returns",
"ENDMARKER",
"token",
"if",
... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L156-L166 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.token_range | def token_range(self, first_token, last_token, include_extra=False):
"""
Yields all tokens in order from first_token through and including last_token. If
include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT.
"""
for i in xrange(first_token.index, last_token.index + 1):
... | python | def token_range(self, first_token, last_token, include_extra=False):
"""
Yields all tokens in order from first_token through and including last_token. If
include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT.
"""
for i in xrange(first_token.index, last_token.index + 1):
... | [
"def",
"token_range",
"(",
"self",
",",
"first_token",
",",
"last_token",
",",
"include_extra",
"=",
"False",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"first_token",
".",
"index",
",",
"last_token",
".",
"index",
"+",
"1",
")",
":",
"if",
"include_extr... | Yields all tokens in order from first_token through and including last_token. If
include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT. | [
"Yields",
"all",
"tokens",
"in",
"order",
"from",
"first_token",
"through",
"and",
"including",
"last_token",
".",
"If",
"include_extra",
"is",
"True",
"includes",
"non",
"-",
"coding",
"tokens",
"such",
"as",
"tokenize",
".",
"NL",
"and",
".",
"COMMENT",
".... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L168-L175 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.get_tokens | def get_tokens(self, node, include_extra=False):
"""
Yields all tokens making up the given node. If include_extra is True, includes non-coding
tokens such as tokenize.NL and .COMMENT.
"""
return self.token_range(node.first_token, node.last_token, include_extra=include_extra) | python | def get_tokens(self, node, include_extra=False):
"""
Yields all tokens making up the given node. If include_extra is True, includes non-coding
tokens such as tokenize.NL and .COMMENT.
"""
return self.token_range(node.first_token, node.last_token, include_extra=include_extra) | [
"def",
"get_tokens",
"(",
"self",
",",
"node",
",",
"include_extra",
"=",
"False",
")",
":",
"return",
"self",
".",
"token_range",
"(",
"node",
".",
"first_token",
",",
"node",
".",
"last_token",
",",
"include_extra",
"=",
"include_extra",
")"
] | Yields all tokens making up the given node. If include_extra is True, includes non-coding
tokens such as tokenize.NL and .COMMENT. | [
"Yields",
"all",
"tokens",
"making",
"up",
"the",
"given",
"node",
".",
"If",
"include_extra",
"is",
"True",
"includes",
"non",
"-",
"coding",
"tokens",
"such",
"as",
"tokenize",
".",
"NL",
"and",
".",
"COMMENT",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L177-L182 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.get_text_range | def get_text_range(self, node):
"""
After mark_tokens() has been called, returns the (startpos, endpos) positions in source text
corresponding to the given node. Returns (0, 0) for nodes (like `Load`) that don't correspond
to any particular text.
"""
if not hasattr(node, 'first_token'):
re... | python | def get_text_range(self, node):
"""
After mark_tokens() has been called, returns the (startpos, endpos) positions in source text
corresponding to the given node. Returns (0, 0) for nodes (like `Load`) that don't correspond
to any particular text.
"""
if not hasattr(node, 'first_token'):
re... | [
"def",
"get_text_range",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"hasattr",
"(",
"node",
",",
"'first_token'",
")",
":",
"return",
"(",
"0",
",",
"0",
")",
"start",
"=",
"node",
".",
"first_token",
".",
"startpos",
"if",
"any",
"(",
"match_t... | After mark_tokens() has been called, returns the (startpos, endpos) positions in source text
corresponding to the given node. Returns (0, 0) for nodes (like `Load`) that don't correspond
to any particular text. | [
"After",
"mark_tokens",
"()",
"has",
"been",
"called",
"returns",
"the",
"(",
"startpos",
"endpos",
")",
"positions",
"in",
"source",
"text",
"corresponding",
"to",
"the",
"given",
"node",
".",
"Returns",
"(",
"0",
"0",
")",
"for",
"nodes",
"(",
"like",
... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L184-L198 |
gristlabs/asttokens | asttokens/asttokens.py | ASTTokens.get_text | def get_text(self, node):
"""
After mark_tokens() has been called, returns the text corresponding to the given node. Returns
'' for nodes (like `Load`) that don't correspond to any particular text.
"""
start, end = self.get_text_range(node)
return self._text[start : end] | python | def get_text(self, node):
"""
After mark_tokens() has been called, returns the text corresponding to the given node. Returns
'' for nodes (like `Load`) that don't correspond to any particular text.
"""
start, end = self.get_text_range(node)
return self._text[start : end] | [
"def",
"get_text",
"(",
"self",
",",
"node",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"get_text_range",
"(",
"node",
")",
"return",
"self",
".",
"_text",
"[",
"start",
":",
"end",
"]"
] | After mark_tokens() has been called, returns the text corresponding to the given node. Returns
'' for nodes (like `Load`) that don't correspond to any particular text. | [
"After",
"mark_tokens",
"()",
"has",
"been",
"called",
"returns",
"the",
"text",
"corresponding",
"to",
"the",
"given",
"node",
".",
"Returns",
"for",
"nodes",
"(",
"like",
"Load",
")",
"that",
"don",
"t",
"correspond",
"to",
"any",
"particular",
"text",
"... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L200-L206 |
gristlabs/asttokens | asttokens/line_numbers.py | LineNumbers.from_utf8_col | def from_utf8_col(self, line, utf8_column):
"""
Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column.
"""
offsets = self._utf8_offset_cache.get(line)
if offsets is None:
end_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len... | python | def from_utf8_col(self, line, utf8_column):
"""
Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column.
"""
offsets = self._utf8_offset_cache.get(line)
if offsets is None:
end_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len... | [
"def",
"from_utf8_col",
"(",
"self",
",",
"line",
",",
"utf8_column",
")",
":",
"offsets",
"=",
"self",
".",
"_utf8_offset_cache",
".",
"get",
"(",
"line",
")",
"if",
"offsets",
"is",
"None",
":",
"end_offset",
"=",
"self",
".",
"_line_offsets",
"[",
"li... | Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column. | [
"Given",
"a",
"1",
"-",
"based",
"line",
"number",
"and",
"0",
"-",
"based",
"utf8",
"column",
"returns",
"a",
"0",
"-",
"based",
"unicode",
"column",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L35-L48 |
gristlabs/asttokens | asttokens/line_numbers.py | LineNumbers.line_to_offset | def line_to_offset(self, line, column):
"""
Converts 1-based line number and 0-based column to 0-based character offset into text.
"""
line -= 1
if line >= len(self._line_offsets):
return self._text_len
elif line < 0:
return 0
else:
return min(self._line_offsets[line] + max... | python | def line_to_offset(self, line, column):
"""
Converts 1-based line number and 0-based column to 0-based character offset into text.
"""
line -= 1
if line >= len(self._line_offsets):
return self._text_len
elif line < 0:
return 0
else:
return min(self._line_offsets[line] + max... | [
"def",
"line_to_offset",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"line",
"-=",
"1",
"if",
"line",
">=",
"len",
"(",
"self",
".",
"_line_offsets",
")",
":",
"return",
"self",
".",
"_text_len",
"elif",
"line",
"<",
"0",
":",
"return",
"0",
... | Converts 1-based line number and 0-based column to 0-based character offset into text. | [
"Converts",
"1",
"-",
"based",
"line",
"number",
"and",
"0",
"-",
"based",
"column",
"to",
"0",
"-",
"based",
"character",
"offset",
"into",
"text",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L50-L60 |
gristlabs/asttokens | asttokens/line_numbers.py | LineNumbers.offset_to_line | def offset_to_line(self, offset):
"""
Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
numbers.
"""
offset = max(0, min(self._text_len, offset))
line_index = bisect.bisect_right(self._line_offsets, offset) - 1
return (line_index + 1, offset - self._lin... | python | def offset_to_line(self, offset):
"""
Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
numbers.
"""
offset = max(0, min(self._text_len, offset))
line_index = bisect.bisect_right(self._line_offsets, offset) - 1
return (line_index + 1, offset - self._lin... | [
"def",
"offset_to_line",
"(",
"self",
",",
"offset",
")",
":",
"offset",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"self",
".",
"_text_len",
",",
"offset",
")",
")",
"line_index",
"=",
"bisect",
".",
"bisect_right",
"(",
"self",
".",
"_line_offsets",
",",... | Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
numbers. | [
"Converts",
"0",
"-",
"based",
"character",
"offset",
"to",
"pair",
"(",
"line",
"col",
")",
"of",
"1",
"-",
"based",
"line",
"and",
"0",
"-",
"based",
"column",
"numbers",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L62-L69 |
gristlabs/asttokens | asttokens/mark_tokens.py | MarkTokens._iter_non_child_tokens | def _iter_non_child_tokens(self, first_token, last_token, node):
"""
Generates all tokens in [first_token, last_token] range that do not belong to any children of
node. E.g. `foo(bar)` has children `foo` and `bar`, but we would yield the `(`.
"""
tok = first_token
for n in self._iter_children(no... | python | def _iter_non_child_tokens(self, first_token, last_token, node):
"""
Generates all tokens in [first_token, last_token] range that do not belong to any children of
node. E.g. `foo(bar)` has children `foo` and `bar`, but we would yield the `(`.
"""
tok = first_token
for n in self._iter_children(no... | [
"def",
"_iter_non_child_tokens",
"(",
"self",
",",
"first_token",
",",
"last_token",
",",
"node",
")",
":",
"tok",
"=",
"first_token",
"for",
"n",
"in",
"self",
".",
"_iter_children",
"(",
"node",
")",
":",
"for",
"t",
"in",
"self",
".",
"_code",
".",
... | Generates all tokens in [first_token, last_token] range that do not belong to any children of
node. E.g. `foo(bar)` has children `foo` and `bar`, but we would yield the `(`. | [
"Generates",
"all",
"tokens",
"in",
"[",
"first_token",
"last_token",
"]",
"range",
"that",
"do",
"not",
"belong",
"to",
"any",
"children",
"of",
"node",
".",
"E",
".",
"g",
".",
"foo",
"(",
"bar",
")",
"has",
"children",
"foo",
"and",
"bar",
"but",
... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/mark_tokens.py#L106-L120 |
gristlabs/asttokens | asttokens/mark_tokens.py | MarkTokens._expand_to_matching_pairs | def _expand_to_matching_pairs(self, first_token, last_token, node):
"""
Scan tokens in [first_token, last_token] range that are between node's children, and for any
unmatched brackets, adjust first/last tokens to include the closing pair.
"""
# We look for opening parens/braces among non-child token... | python | def _expand_to_matching_pairs(self, first_token, last_token, node):
"""
Scan tokens in [first_token, last_token] range that are between node's children, and for any
unmatched brackets, adjust first/last tokens to include the closing pair.
"""
# We look for opening parens/braces among non-child token... | [
"def",
"_expand_to_matching_pairs",
"(",
"self",
",",
"first_token",
",",
"last_token",
",",
"node",
")",
":",
"# We look for opening parens/braces among non-child tokens (i.e. tokens between our actual",
"# child nodes). If we find any closing ones, we match them to the opens.",
"to_mat... | Scan tokens in [first_token, last_token] range that are between node's children, and for any
unmatched brackets, adjust first/last tokens to include the closing pair. | [
"Scan",
"tokens",
"in",
"[",
"first_token",
"last_token",
"]",
"range",
"that",
"are",
"between",
"node",
"s",
"children",
"and",
"for",
"any",
"unmatched",
"brackets",
"adjust",
"first",
"/",
"last",
"tokens",
"to",
"include",
"the",
"closing",
"pair",
"."
... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/mark_tokens.py#L122-L156 |
gristlabs/asttokens | asttokens/util.py | match_token | def match_token(token, tok_type, tok_str=None):
"""Returns true if token is of the given type and, if a string is given, has that string."""
return token.type == tok_type and (tok_str is None or token.string == tok_str) | python | def match_token(token, tok_type, tok_str=None):
"""Returns true if token is of the given type and, if a string is given, has that string."""
return token.type == tok_type and (tok_str is None or token.string == tok_str) | [
"def",
"match_token",
"(",
"token",
",",
"tok_type",
",",
"tok_str",
"=",
"None",
")",
":",
"return",
"token",
".",
"type",
"==",
"tok_type",
"and",
"(",
"tok_str",
"is",
"None",
"or",
"token",
".",
"string",
"==",
"tok_str",
")"
] | Returns true if token is of the given type and, if a string is given, has that string. | [
"Returns",
"true",
"if",
"token",
"is",
"of",
"the",
"given",
"type",
"and",
"if",
"a",
"string",
"is",
"given",
"has",
"that",
"string",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L45-L47 |
gristlabs/asttokens | asttokens/util.py | expect_token | def expect_token(token, tok_type, tok_str=None):
"""
Verifies that the given token is of the expected type. If tok_str is given, the token string
is verified too. If the token doesn't match, raises an informative ValueError.
"""
if not match_token(token, tok_type, tok_str):
raise ValueError("Expected toke... | python | def expect_token(token, tok_type, tok_str=None):
"""
Verifies that the given token is of the expected type. If tok_str is given, the token string
is verified too. If the token doesn't match, raises an informative ValueError.
"""
if not match_token(token, tok_type, tok_str):
raise ValueError("Expected toke... | [
"def",
"expect_token",
"(",
"token",
",",
"tok_type",
",",
"tok_str",
"=",
"None",
")",
":",
"if",
"not",
"match_token",
"(",
"token",
",",
"tok_type",
",",
"tok_str",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected token %s, got %s on line %s col %s\"",
"%",
... | Verifies that the given token is of the expected type. If tok_str is given, the token string
is verified too. If the token doesn't match, raises an informative ValueError. | [
"Verifies",
"that",
"the",
"given",
"token",
"is",
"of",
"the",
"expected",
"type",
".",
"If",
"tok_str",
"is",
"given",
"the",
"token",
"string",
"is",
"verified",
"too",
".",
"If",
"the",
"token",
"doesn",
"t",
"match",
"raises",
"an",
"informative",
"... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L50-L58 |
gristlabs/asttokens | asttokens/util.py | visit_tree | def visit_tree(node, previsit, postvisit):
"""
Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion
via the function call stack to avoid hitting 'maximum recursion depth exceeded' error.
It calls ``previsit()`` and ``postvisit()`` as follows:
* ``previsit(node, par... | python | def visit_tree(node, previsit, postvisit):
"""
Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion
via the function call stack to avoid hitting 'maximum recursion depth exceeded' error.
It calls ``previsit()`` and ``postvisit()`` as follows:
* ``previsit(node, par... | [
"def",
"visit_tree",
"(",
"node",
",",
"previsit",
",",
"postvisit",
")",
":",
"if",
"not",
"previsit",
":",
"previsit",
"=",
"lambda",
"node",
",",
"pvalue",
":",
"(",
"None",
",",
"None",
")",
"if",
"not",
"postvisit",
":",
"postvisit",
"=",
"lambda"... | Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion
via the function call stack to avoid hitting 'maximum recursion depth exceeded' error.
It calls ``previsit()`` and ``postvisit()`` as follows:
* ``previsit(node, par_value)`` - should return ``(par_value, value)``
... | [
"Scans",
"the",
"tree",
"under",
"the",
"node",
"depth",
"-",
"first",
"using",
"an",
"explicit",
"stack",
".",
"It",
"avoids",
"implicit",
"recursion",
"via",
"the",
"function",
"call",
"stack",
"to",
"avoid",
"hitting",
"maximum",
"recursion",
"depth",
"ex... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L144-L185 |
gristlabs/asttokens | asttokens/util.py | walk | def walk(node):
"""
Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node``
itself), using depth-first pre-order traversal (yieling parents before their children).
This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and
``astroid`` ... | python | def walk(node):
"""
Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node``
itself), using depth-first pre-order traversal (yieling parents before their children).
This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and
``astroid`` ... | [
"def",
"walk",
"(",
"node",
")",
":",
"iter_children",
"=",
"iter_children_func",
"(",
"node",
")",
"done",
"=",
"set",
"(",
")",
"stack",
"=",
"[",
"node",
"]",
"while",
"stack",
":",
"current",
"=",
"stack",
".",
"pop",
"(",
")",
"assert",
"current... | Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node``
itself), using depth-first pre-order traversal (yieling parents before their children).
This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and
``astroid`` trees. Also, as ``iter_c... | [
"Recursively",
"yield",
"all",
"descendant",
"nodes",
"in",
"the",
"tree",
"starting",
"at",
"node",
"(",
"including",
"node",
"itself",
")",
"using",
"depth",
"-",
"first",
"pre",
"-",
"order",
"traversal",
"(",
"yieling",
"parents",
"before",
"their",
"chi... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L189-L211 |
gristlabs/asttokens | asttokens/util.py | replace | def replace(text, replacements):
"""
Replaces multiple slices of text with new values. This is a convenience method for making code
modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is
an iterable of ``(start, end, new_text)`` tuples.
For example, ``replace("this ... | python | def replace(text, replacements):
"""
Replaces multiple slices of text with new values. This is a convenience method for making code
modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is
an iterable of ``(start, end, new_text)`` tuples.
For example, ``replace("this ... | [
"def",
"replace",
"(",
"text",
",",
"replacements",
")",
":",
"p",
"=",
"0",
"parts",
"=",
"[",
"]",
"for",
"(",
"start",
",",
"end",
",",
"new_text",
")",
"in",
"sorted",
"(",
"replacements",
")",
":",
"parts",
".",
"append",
"(",
"text",
"[",
"... | Replaces multiple slices of text with new values. This is a convenience method for making code
modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is
an iterable of ``(start, end, new_text)`` tuples.
For example, ``replace("this is a test", [(0, 4, "X"), (8, 1, "THE")])... | [
"Replaces",
"multiple",
"slices",
"of",
"text",
"with",
"new",
"values",
".",
"This",
"is",
"a",
"convenience",
"method",
"for",
"making",
"code",
"modifications",
"of",
"ranges",
"e",
".",
"g",
".",
"as",
"identified",
"by",
"ASTTokens",
".",
"get_text_rang... | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L214-L230 |
gristlabs/asttokens | asttokens/util.py | NodeMethods.get | def get(self, obj, cls):
"""
Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,
or `obj.visit_default` if the type-specific method is not found.
"""
method = self._cache.get(cls)
if not method:
name = "visit_" + cls.__name__.lower()
method = getattr(... | python | def get(self, obj, cls):
"""
Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,
or `obj.visit_default` if the type-specific method is not found.
"""
method = self._cache.get(cls)
if not method:
name = "visit_" + cls.__name__.lower()
method = getattr(... | [
"def",
"get",
"(",
"self",
",",
"obj",
",",
"cls",
")",
":",
"method",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"cls",
")",
"if",
"not",
"method",
":",
"name",
"=",
"\"visit_\"",
"+",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"method",
... | Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,
or `obj.visit_default` if the type-specific method is not found. | [
"Using",
"the",
"lowercase",
"name",
"of",
"the",
"class",
"as",
"node_type",
"returns",
"obj",
".",
"visit_",
"{",
"node_type",
"}",
"or",
"obj",
".",
"visit_default",
"if",
"the",
"type",
"-",
"specific",
"method",
"is",
"not",
"found",
"."
] | train | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L240-L250 |
robin900/gspread-dataframe | gspread_dataframe.py | _cellrepr | def _cellrepr(value, allow_formulas):
"""
Get a string representation of dataframe value.
:param :value: the value to represent
:param :allow_formulas: if True, allow values starting with '='
to be interpreted as formulas; otherwise, escape
them with an apostrophe to avoid formu... | python | def _cellrepr(value, allow_formulas):
"""
Get a string representation of dataframe value.
:param :value: the value to represent
:param :allow_formulas: if True, allow values starting with '='
to be interpreted as formulas; otherwise, escape
them with an apostrophe to avoid formu... | [
"def",
"_cellrepr",
"(",
"value",
",",
"allow_formulas",
")",
":",
"if",
"pd",
".",
"isnull",
"(",
"value",
")",
"is",
"True",
":",
"return",
"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"value",
"=",
"repr",
"(",
"value",
")",
... | Get a string representation of dataframe value.
:param :value: the value to represent
:param :allow_formulas: if True, allow values starting with '='
to be interpreted as formulas; otherwise, escape
them with an apostrophe to avoid formula interpretation. | [
"Get",
"a",
"string",
"representation",
"of",
"dataframe",
"value",
"."
] | train | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L40-L57 |
robin900/gspread-dataframe | gspread_dataframe.py | _resize_to_minimum | def _resize_to_minimum(worksheet, rows=None, cols=None):
"""
Resize the worksheet to guarantee a minimum size, either in rows,
or columns, or both.
Both rows and cols are optional.
"""
# get the current size
current_cols, current_rows = (
worksheet.col_count,
worksheet.row_c... | python | def _resize_to_minimum(worksheet, rows=None, cols=None):
"""
Resize the worksheet to guarantee a minimum size, either in rows,
or columns, or both.
Both rows and cols are optional.
"""
# get the current size
current_cols, current_rows = (
worksheet.col_count,
worksheet.row_c... | [
"def",
"_resize_to_minimum",
"(",
"worksheet",
",",
"rows",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"# get the current size",
"current_cols",
",",
"current_rows",
"=",
"(",
"worksheet",
".",
"col_count",
",",
"worksheet",
".",
"row_count",
")",
"if",
... | Resize the worksheet to guarantee a minimum size, either in rows,
or columns, or both.
Both rows and cols are optional. | [
"Resize",
"the",
"worksheet",
"to",
"guarantee",
"a",
"minimum",
"size",
"either",
"in",
"rows",
"or",
"columns",
"or",
"both",
"."
] | train | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L59-L77 |
robin900/gspread-dataframe | gspread_dataframe.py | get_as_dataframe | def get_as_dataframe(worksheet,
evaluate_formulas=False,
**options):
"""
Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise g... | python | def get_as_dataframe(worksheet,
evaluate_formulas=False,
**options):
"""
Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise g... | [
"def",
"get_as_dataframe",
"(",
"worksheet",
",",
"evaluate_formulas",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"all_values",
"=",
"_get_all_values",
"(",
"worksheet",
",",
"evaluate_formulas",
")",
"return",
"TextParser",
"(",
"all_values",
",",
"*",
... | Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise get the formula itself if present.
Defaults to False.
:param \*\*options: all the options for pandas.io.pars... | [
"Returns",
"the",
"worksheet",
"contents",
"as",
"a",
"DataFrame",
"."
] | train | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L118-L135 |
robin900/gspread-dataframe | gspread_dataframe.py | set_with_dataframe | def set_with_dataframe(worksheet,
dataframe,
row=1,
col=1,
include_index=False,
include_column_header=True,
resize=False,
allow_formulas=True):
"""
Set... | python | def set_with_dataframe(worksheet,
dataframe,
row=1,
col=1,
include_index=False,
include_column_header=True,
resize=False,
allow_formulas=True):
"""
Set... | [
"def",
"set_with_dataframe",
"(",
"worksheet",
",",
"dataframe",
",",
"row",
"=",
"1",
",",
"col",
"=",
"1",
",",
"include_index",
"=",
"False",
",",
"include_column_header",
"=",
"True",
",",
"resize",
"=",
"False",
",",
"allow_formulas",
"=",
"True",
")"... | Sets the values of a given DataFrame, anchoring its upper-left corner
at (row, col). (Default is row 1, column 1.)
:param worksheet: the gspread worksheet to set with content of DataFrame.
:param dataframe: the DataFrame.
:param include_index: if True, include the DataFrame's index as an
ad... | [
"Sets",
"the",
"values",
"of",
"a",
"given",
"DataFrame",
"anchoring",
"its",
"upper",
"-",
"left",
"corner",
"at",
"(",
"row",
"col",
")",
".",
"(",
"Default",
"is",
"row",
"1",
"column",
"1",
".",
")"
] | train | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L137-L213 |
openregister/openregister-python | openregister/entry.py | Entry.timestamp | def timestamp(self, timestamp):
"""Entry timestamp as datetime."""
if timestamp is None:
self._timestamp = datetime.utcnow()
elif isinstance(timestamp, datetime):
self._timestamp = timestamp
else:
self._timestamp = datetime.strptime(timestamp, fmt) | python | def timestamp(self, timestamp):
"""Entry timestamp as datetime."""
if timestamp is None:
self._timestamp = datetime.utcnow()
elif isinstance(timestamp, datetime):
self._timestamp = timestamp
else:
self._timestamp = datetime.strptime(timestamp, fmt) | [
"def",
"timestamp",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"self",
".",
"_timestamp",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"elif",
"isinstance",
"(",
"timestamp",
",",
"datetime",
")",
":",
"self",
".",
"_ti... | Entry timestamp as datetime. | [
"Entry",
"timestamp",
"as",
"datetime",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L27-L34 |
openregister/openregister-python | openregister/entry.py | Entry.primitive | def primitive(self):
"""Entry as Python primitive."""
primitive = {}
if self.entry_number is not None:
primitive['entry-number'] = self.entry_number
if self.item_hash is not None:
primitive['item-hash'] = self.item_hash
primitive['timestamp'] = self.time... | python | def primitive(self):
"""Entry as Python primitive."""
primitive = {}
if self.entry_number is not None:
primitive['entry-number'] = self.entry_number
if self.item_hash is not None:
primitive['item-hash'] = self.item_hash
primitive['timestamp'] = self.time... | [
"def",
"primitive",
"(",
"self",
")",
":",
"primitive",
"=",
"{",
"}",
"if",
"self",
".",
"entry_number",
"is",
"not",
"None",
":",
"primitive",
"[",
"'entry-number'",
"]",
"=",
"self",
".",
"entry_number",
"if",
"self",
".",
"item_hash",
"is",
"not",
... | Entry as Python primitive. | [
"Entry",
"as",
"Python",
"primitive",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L37-L47 |
openregister/openregister-python | openregister/entry.py | Entry.primitive | def primitive(self, primitive):
"""Entry from Python primitive."""
self.entry_number = primitive['entry-number']
self.item_hash = primitive['item-hash']
self.timestamp = primitive['timestamp'] | python | def primitive(self, primitive):
"""Entry from Python primitive."""
self.entry_number = primitive['entry-number']
self.item_hash = primitive['item-hash']
self.timestamp = primitive['timestamp'] | [
"def",
"primitive",
"(",
"self",
",",
"primitive",
")",
":",
"self",
".",
"entry_number",
"=",
"primitive",
"[",
"'entry-number'",
"]",
"self",
".",
"item_hash",
"=",
"primitive",
"[",
"'item-hash'",
"]",
"self",
".",
"timestamp",
"=",
"primitive",
"[",
"'... | Entry from Python primitive. | [
"Entry",
"from",
"Python",
"primitive",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L50-L54 |
openregister/openregister-python | openregister/client.py | Client.config | def config(self, name, suffix):
"Return config variable value, defaulting to environment"
var = '%s_%s' % (name, suffix)
var = var.upper().replace('-', '_')
if var in self._config:
return self._config[var]
return os.environ[var] | python | def config(self, name, suffix):
"Return config variable value, defaulting to environment"
var = '%s_%s' % (name, suffix)
var = var.upper().replace('-', '_')
if var in self._config:
return self._config[var]
return os.environ[var] | [
"def",
"config",
"(",
"self",
",",
"name",
",",
"suffix",
")",
":",
"var",
"=",
"'%s_%s'",
"%",
"(",
"name",
",",
"suffix",
")",
"var",
"=",
"var",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"var",
"in",
"self",
... | Return config variable value, defaulting to environment | [
"Return",
"config",
"variable",
"value",
"defaulting",
"to",
"environment"
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L16-L22 |
openregister/openregister-python | openregister/client.py | Client.index | def index(self, index, field, value):
"Search for records matching a value in an index service"
params = {
"q": value,
# search index has '_' instead of '-' in field names ..
"q.options": "{fields:['%s']}" % (field.replace('-', '_'))
}
response = self... | python | def index(self, index, field, value):
"Search for records matching a value in an index service"
params = {
"q": value,
# search index has '_' instead of '-' in field names ..
"q.options": "{fields:['%s']}" % (field.replace('-', '_'))
}
response = self... | [
"def",
"index",
"(",
"self",
",",
"index",
",",
"field",
",",
"value",
")",
":",
"params",
"=",
"{",
"\"q\"",
":",
"value",
",",
"# search index has '_' instead of '-' in field names ..",
"\"q.options\"",
":",
"\"{fields:['%s']}\"",
"%",
"(",
"field",
".",
"repl... | Search for records matching a value in an index service | [
"Search",
"for",
"records",
"matching",
"a",
"value",
"in",
"an",
"index",
"service"
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L41-L56 |
openregister/openregister-python | openregister/item.py | Item.primitive | def primitive(self):
"""Python primitive representation."""
dict = {}
for key, value in self.__dict__.items():
if not key.startswith('_'):
dict[key] = copy(value)
for key in dict:
if isinstance(dict[key], (set)):
dict[key] = sorted... | python | def primitive(self):
"""Python primitive representation."""
dict = {}
for key, value in self.__dict__.items():
if not key.startswith('_'):
dict[key] = copy(value)
for key in dict:
if isinstance(dict[key], (set)):
dict[key] = sorted... | [
"def",
"primitive",
"(",
"self",
")",
":",
"dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"key",
".",
"startswith",
"(",
"'_'",
")",
":",
"dict",
"[",
"key",
"]",
"=",... | Python primitive representation. | [
"Python",
"primitive",
"representation",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L49-L60 |
openregister/openregister-python | openregister/item.py | Item.primitive | def primitive(self, dictionary):
"""Item from Python primitive."""
self.__dict__ = {k: v for k, v in dictionary.items() if v} | python | def primitive(self, dictionary):
"""Item from Python primitive."""
self.__dict__ = {k: v for k, v in dictionary.items() if v} | [
"def",
"primitive",
"(",
"self",
",",
"dictionary",
")",
":",
"self",
".",
"__dict__",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"dictionary",
".",
"items",
"(",
")",
"if",
"v",
"}"
] | Item from Python primitive. | [
"Item",
"from",
"Python",
"primitive",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L63-L65 |
openregister/openregister-python | openregister/record.py | Record.primitive | def primitive(self):
"""Record as Python primitive."""
primitive = copy(self.item.primitive)
primitive.update(self.entry.primitive)
return primitive | python | def primitive(self):
"""Record as Python primitive."""
primitive = copy(self.item.primitive)
primitive.update(self.entry.primitive)
return primitive | [
"def",
"primitive",
"(",
"self",
")",
":",
"primitive",
"=",
"copy",
"(",
"self",
".",
"item",
".",
"primitive",
")",
"primitive",
".",
"update",
"(",
"self",
".",
"entry",
".",
"primitive",
")",
"return",
"primitive"
] | Record as Python primitive. | [
"Record",
"as",
"Python",
"primitive",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L19-L23 |
openregister/openregister-python | openregister/record.py | Record.primitive | def primitive(self, primitive):
"""Record from Python primitive."""
self.entry = Entry()
self.entry.primitive = primitive
primitive = copy(primitive)
for field in self.entry.fields:
del primitive[field]
self.item = Item()
self.item.primitive = primit... | python | def primitive(self, primitive):
"""Record from Python primitive."""
self.entry = Entry()
self.entry.primitive = primitive
primitive = copy(primitive)
for field in self.entry.fields:
del primitive[field]
self.item = Item()
self.item.primitive = primit... | [
"def",
"primitive",
"(",
"self",
",",
"primitive",
")",
":",
"self",
".",
"entry",
"=",
"Entry",
"(",
")",
"self",
".",
"entry",
".",
"primitive",
"=",
"primitive",
"primitive",
"=",
"copy",
"(",
"primitive",
")",
"for",
"field",
"in",
"self",
".",
"... | Record from Python primitive. | [
"Record",
"from",
"Python",
"primitive",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L26-L36 |
openregister/openregister-python | openregister/representations/tsv.py | load | def load(self, text, fieldnames=None):
"""Item from TSV representation."""
lines = text.split('\n')
fieldnames = load_line(lines[0])
values = load_line(lines[1])
self.__dict__ = dict(zip(fieldnames, values)) | python | def load(self, text, fieldnames=None):
"""Item from TSV representation."""
lines = text.split('\n')
fieldnames = load_line(lines[0])
values = load_line(lines[1])
self.__dict__ = dict(zip(fieldnames, values)) | [
"def",
"load",
"(",
"self",
",",
"text",
",",
"fieldnames",
"=",
"None",
")",
":",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"fieldnames",
"=",
"load_line",
"(",
"lines",
"[",
"0",
"]",
")",
"values",
"=",
"load_line",
"(",
"lines",
"[... | Item from TSV representation. | [
"Item",
"from",
"TSV",
"representation",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L43-L48 |
openregister/openregister-python | openregister/representations/tsv.py | reader | def reader(stream, fieldnames=None):
"""Read Items from a stream containing TSV."""
if not fieldnames:
fieldnames = load_line(stream.readline())
for line in stream:
values = load_line(line)
item = Item()
item.__dict__ = dict(zip(fieldnames, values))
yield item | python | def reader(stream, fieldnames=None):
"""Read Items from a stream containing TSV."""
if not fieldnames:
fieldnames = load_line(stream.readline())
for line in stream:
values = load_line(line)
item = Item()
item.__dict__ = dict(zip(fieldnames, values))
yield item | [
"def",
"reader",
"(",
"stream",
",",
"fieldnames",
"=",
"None",
")",
":",
"if",
"not",
"fieldnames",
":",
"fieldnames",
"=",
"load_line",
"(",
"stream",
".",
"readline",
"(",
")",
")",
"for",
"line",
"in",
"stream",
":",
"values",
"=",
"load_line",
"("... | Read Items from a stream containing TSV. | [
"Read",
"Items",
"from",
"a",
"stream",
"containing",
"TSV",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L51-L59 |
openregister/openregister-python | openregister/representations/tsv.py | dump | def dump(self):
"""TSV representation."""
dict = self.primitive
if not dict:
return ''
return dump_line(self.keys) + dump_line(self.values) | python | def dump(self):
"""TSV representation."""
dict = self.primitive
if not dict:
return ''
return dump_line(self.keys) + dump_line(self.values) | [
"def",
"dump",
"(",
"self",
")",
":",
"dict",
"=",
"self",
".",
"primitive",
"if",
"not",
"dict",
":",
"return",
"''",
"return",
"dump_line",
"(",
"self",
".",
"keys",
")",
"+",
"dump_line",
"(",
"self",
".",
"values",
")"
] | TSV representation. | [
"TSV",
"representation",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L66-L71 |
openregister/openregister-python | openregister/representations/csv.py | load | def load(self, text,
lineterminator='\r\n',
quotechar='"',
delimiter=",",
escapechar=escapechar,
quoting=csv.QUOTE_MINIMAL):
"""Item from CSV representation."""
f = io.StringIO(text)
if not quotechar:
quoting = csv.QUOTE_NONE
reader = csv.DictReade... | python | def load(self, text,
lineterminator='\r\n',
quotechar='"',
delimiter=",",
escapechar=escapechar,
quoting=csv.QUOTE_MINIMAL):
"""Item from CSV representation."""
f = io.StringIO(text)
if not quotechar:
quoting = csv.QUOTE_NONE
reader = csv.DictReade... | [
"def",
"load",
"(",
"self",
",",
"text",
",",
"lineterminator",
"=",
"'\\r\\n'",
",",
"quotechar",
"=",
"'\"'",
",",
"delimiter",
"=",
"\",\"",
",",
"escapechar",
"=",
"escapechar",
",",
"quoting",
"=",
"csv",
".",
"QUOTE_MINIMAL",
")",
":",
"f",
"=",
... | Item from CSV representation. | [
"Item",
"from",
"CSV",
"representation",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L14-L40 |
openregister/openregister-python | openregister/representations/csv.py | dump | def dump(self, **kwargs):
"""CSV representation of a item."""
f = io.StringIO()
w = Writer(f, self.keys, **kwargs)
w.write(self)
text = f.getvalue().lstrip()
f.close()
return text | python | def dump(self, **kwargs):
"""CSV representation of a item."""
f = io.StringIO()
w = Writer(f, self.keys, **kwargs)
w.write(self)
text = f.getvalue().lstrip()
f.close()
return text | [
"def",
"dump",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"io",
".",
"StringIO",
"(",
")",
"w",
"=",
"Writer",
"(",
"f",
",",
"self",
".",
"keys",
",",
"*",
"*",
"kwargs",
")",
"w",
".",
"write",
"(",
"self",
")",
"text",
"="... | CSV representation of a item. | [
"CSV",
"representation",
"of",
"a",
"item",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L70-L79 |
openregister/openregister-python | openregister/datatypes/digest.py | git_hash | def git_hash(blob):
"""Return git-hash compatible SHA-1 hexdigits for a blob of data."""
head = str("blob " + str(len(blob)) + "\0").encode("utf-8")
return sha1(head + blob).hexdigest() | python | def git_hash(blob):
"""Return git-hash compatible SHA-1 hexdigits for a blob of data."""
head = str("blob " + str(len(blob)) + "\0").encode("utf-8")
return sha1(head + blob).hexdigest() | [
"def",
"git_hash",
"(",
"blob",
")",
":",
"head",
"=",
"str",
"(",
"\"blob \"",
"+",
"str",
"(",
"len",
"(",
"blob",
")",
")",
"+",
"\"\\0\"",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
"return",
"sha1",
"(",
"head",
"+",
"blob",
")",
".",
"hexdi... | Return git-hash compatible SHA-1 hexdigits for a blob of data. | [
"Return",
"git",
"-",
"hash",
"compatible",
"SHA",
"-",
"1",
"hexdigits",
"for",
"a",
"blob",
"of",
"data",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/datatypes/digest.py#L5-L8 |
openregister/openregister-python | openregister/representations/json.py | dump | def dump(self):
"""Item as a JSON representation."""
return json.dumps(
self.primitive,
sort_keys=True,
ensure_ascii=False,
separators=(',', ':')) | python | def dump(self):
"""Item as a JSON representation."""
return json.dumps(
self.primitive,
sort_keys=True,
ensure_ascii=False,
separators=(',', ':')) | [
"def",
"dump",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"primitive",
",",
"sort_keys",
"=",
"True",
",",
"ensure_ascii",
"=",
"False",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")"
] | Item as a JSON representation. | [
"Item",
"as",
"a",
"JSON",
"representation",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L17-L23 |
openregister/openregister-python | openregister/representations/json.py | reader | def reader(stream):
"""Read Items from a stream containing a JSON array."""
string = stream.read()
decoder = json.JSONDecoder().raw_decode
index = START.match(string, 0).end()
while index < len(string):
obj, end = decoder(string, index)
item = Item()
item.primitive = obj
... | python | def reader(stream):
"""Read Items from a stream containing a JSON array."""
string = stream.read()
decoder = json.JSONDecoder().raw_decode
index = START.match(string, 0).end()
while index < len(string):
obj, end = decoder(string, index)
item = Item()
item.primitive = obj
... | [
"def",
"reader",
"(",
"stream",
")",
":",
"string",
"=",
"stream",
".",
"read",
"(",
")",
"decoder",
"=",
"json",
".",
"JSONDecoder",
"(",
")",
".",
"raw_decode",
"index",
"=",
"START",
".",
"match",
"(",
"string",
",",
"0",
")",
".",
"end",
"(",
... | Read Items from a stream containing a JSON array. | [
"Read",
"Items",
"from",
"a",
"stream",
"containing",
"a",
"JSON",
"array",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L26-L37 |
openregister/openregister-python | openregister/representations/jsonl.py | reader | def reader(stream):
"""Read Items from a stream containing lines of JSON."""
for line in stream:
item = Item()
item.json = line
yield item | python | def reader(stream):
"""Read Items from a stream containing lines of JSON."""
for line in stream:
item = Item()
item.json = line
yield item | [
"def",
"reader",
"(",
"stream",
")",
":",
"for",
"line",
"in",
"stream",
":",
"item",
"=",
"Item",
"(",
")",
"item",
".",
"json",
"=",
"line",
"yield",
"item"
] | Read Items from a stream containing lines of JSON. | [
"Read",
"Items",
"from",
"a",
"stream",
"containing",
"lines",
"of",
"JSON",
"."
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/jsonl.py#L8-L13 |
openregister/openregister-python | openregister/store.py | Store.meta | def meta(self, total, page=1, page_size=None):
"""
Calculate statistics for a collection
return: meta
"""
if page_size is None or page_size < 0:
page_size = self.page_size
meta = {}
meta['total'] = total
meta['page_size'] = page_size
m... | python | def meta(self, total, page=1, page_size=None):
"""
Calculate statistics for a collection
return: meta
"""
if page_size is None or page_size < 0:
page_size = self.page_size
meta = {}
meta['total'] = total
meta['page_size'] = page_size
m... | [
"def",
"meta",
"(",
"self",
",",
"total",
",",
"page",
"=",
"1",
",",
"page_size",
"=",
"None",
")",
":",
"if",
"page_size",
"is",
"None",
"or",
"page_size",
"<",
"0",
":",
"page_size",
"=",
"self",
".",
"page_size",
"meta",
"=",
"{",
"}",
"meta",
... | Calculate statistics for a collection
return: meta | [
"Calculate",
"statistics",
"for",
"a",
"collection",
"return",
":",
"meta"
] | train | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/store.py#L12-L26 |
sdispater/cachy | cachy/tag_set.py | TagSet.tag_id | def tag_id(self, name):
"""
Get the unique tag identifier for a given tag.
:param name: The tag
:type name: str
:rtype: str
"""
return self._store.get(self.tag_key(name)) or self.reset_tag(name) | python | def tag_id(self, name):
"""
Get the unique tag identifier for a given tag.
:param name: The tag
:type name: str
:rtype: str
"""
return self._store.get(self.tag_key(name)) or self.reset_tag(name) | [
"def",
"tag_id",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_store",
".",
"get",
"(",
"self",
".",
"tag_key",
"(",
"name",
")",
")",
"or",
"self",
".",
"reset_tag",
"(",
"name",
")"
] | Get the unique tag identifier for a given tag.
:param name: The tag
:type name: str
:rtype: str | [
"Get",
"the",
"unique",
"tag",
"identifier",
"for",
"a",
"given",
"tag",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tag_set.py#L25-L34 |
sdispater/cachy | cachy/tag_set.py | TagSet.reset_tag | def reset_tag(self, name):
"""
Reset the tag and return the new tag identifier.
:param name: The tag
:type name: str
:rtype: str
"""
id_ = str(uuid.uuid4()).replace('-', '')
self._store.forever(self.tag_key(name), id_)
return id_ | python | def reset_tag(self, name):
"""
Reset the tag and return the new tag identifier.
:param name: The tag
:type name: str
:rtype: str
"""
id_ = str(uuid.uuid4()).replace('-', '')
self._store.forever(self.tag_key(name), id_)
return id_ | [
"def",
"reset_tag",
"(",
"self",
",",
"name",
")",
":",
"id_",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"self",
".",
"_store",
".",
"forever",
"(",
"self",
".",
"tag_key",
"(",
"name",
")... | Reset the tag and return the new tag identifier.
:param name: The tag
:type name: str
:rtype: str | [
"Reset",
"the",
"tag",
"and",
"return",
"the",
"new",
"tag",
"identifier",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tag_set.py#L52-L65 |
inveniosoftware/invenio-logging | invenio_logging/fs.py | InvenioLoggingFS.init_app | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
if app.config['LOGGING_FS_LOGFILE'] is None:
return
self.install_handler(app)
app.extensions['invenio-logging-fs'] = self | python | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
if app.config['LOGGING_FS_LOGFILE'] is None:
return
self.install_handler(app)
app.extensions['invenio-logging-fs'] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"if",
"app",
".",
"config",
"[",
"'LOGGING_FS_LOGFILE'",
"]",
"is",
"None",
":",
"return",
"self",
".",
"install_handler",
"(",
"app",
")",
"app",
".",
... | Flask application initialization. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L30-L36 |
inveniosoftware/invenio-logging | invenio_logging/fs.py | InvenioLoggingFS.init_config | def init_config(self, app):
"""Initialize config."""
app.config.setdefault(
'LOGGING_FS_LEVEL',
'DEBUG' if app.debug else 'WARNING'
)
for k in dir(config):
if k.startswith('LOGGING_FS'):
app.config.setdefault(k, getattr(config, k))
... | python | def init_config(self, app):
"""Initialize config."""
app.config.setdefault(
'LOGGING_FS_LEVEL',
'DEBUG' if app.debug else 'WARNING'
)
for k in dir(config):
if k.startswith('LOGGING_FS'):
app.config.setdefault(k, getattr(config, k))
... | [
"def",
"init_config",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'LOGGING_FS_LEVEL'",
",",
"'DEBUG'",
"if",
"app",
".",
"debug",
"else",
"'WARNING'",
")",
"for",
"k",
"in",
"dir",
"(",
"config",
")",
":",
"if",
... | Initialize config. | [
"Initialize",
"config",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L38-L54 |
inveniosoftware/invenio-logging | invenio_logging/fs.py | InvenioLoggingFS.install_handler | def install_handler(self, app):
"""Install log handler on Flask application."""
# Check if directory exists.
basedir = dirname(app.config['LOGGING_FS_LOGFILE'])
if not exists(basedir):
raise ValueError(
'Log directory {0} does not exists.'.format(basedir))
... | python | def install_handler(self, app):
"""Install log handler on Flask application."""
# Check if directory exists.
basedir = dirname(app.config['LOGGING_FS_LOGFILE'])
if not exists(basedir):
raise ValueError(
'Log directory {0} does not exists.'.format(basedir))
... | [
"def",
"install_handler",
"(",
"self",
",",
"app",
")",
":",
"# Check if directory exists.",
"basedir",
"=",
"dirname",
"(",
"app",
".",
"config",
"[",
"'LOGGING_FS_LOGFILE'",
"]",
")",
"if",
"not",
"exists",
"(",
"basedir",
")",
":",
"raise",
"ValueError",
... | Install log handler on Flask application. | [
"Install",
"log",
"handler",
"on",
"Flask",
"application",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L56-L83 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.put | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | python | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"minutes",
")",
":",
"minutes",
"=",
"self",
".",
"_get_minutes",
"(",
"minutes",
")",
"if",
"minutes",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_store",
".",
"put",
"(",
"self",
".... | Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"for",
"a",
"given",
"number",
"of",
"minutes",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L56-L72 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.add | def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|d... | python | def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|d... | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"val",
",",
"minutes",
")",
":",
"if",
"not",
"self",
".",
"has",
"(",
"key",
")",
":",
"self",
".",
"put",
"(",
"key",
",",
"val",
",",
"minutes",
")",
"return",
"True",
"return",
"False"
] | Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int|datetime
:rtype: bool | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L74-L94 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.increment | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
self._store.increment(self.tagged_item_key(ke... | python | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
self._store.increment(self.tagged_item_key(ke... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"self",
".",
"_store",
".",
"increment",
"(",
"self",
".",
"tagged_item_key",
"(",
"key",
")",
",",
"value",
")"
] | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool | [
"Increment",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L96-L108 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.decrement | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
self._store.decrement(self.tagged_item_key(ke... | python | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
self._store.decrement(self.tagged_item_key(ke... | [
"def",
"decrement",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"self",
".",
"_store",
".",
"decrement",
"(",
"self",
".",
"tagged_item_key",
"(",
"key",
")",
",",
"value",
")"
] | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool | [
"Decrement",
"the",
"value",
"of",
"an",
"item",
"in",
"the",
"cache",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L110-L122 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.forever | def forever(self, key, value):
"""
Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed
"""
self._store.forever(self.tagged_item_key(key), value) | python | def forever(self, key, value):
"""
Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed
"""
self._store.forever(self.tagged_item_key(key), value) | [
"def",
"forever",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_store",
".",
"forever",
"(",
"self",
".",
"tagged_item_key",
"(",
"key",
")",
",",
"value",
")"
] | Store an item in the cache indefinitely.
:param key: The cache key
:type key: str
:param value: The value
:type value: mixed | [
"Store",
"an",
"item",
"in",
"the",
"cache",
"indefinitely",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L124-L134 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.remember | def remember(self, key, minutes, callback):
"""
Get an item from the cache, or store the default value.
:param key: The cache key
:type key: str
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime
:param callback: The defa... | python | def remember(self, key, minutes, callback):
"""
Get an item from the cache, or store the default value.
:param key: The cache key
:type key: str
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime
:param callback: The defa... | [
"def",
"remember",
"(",
"self",
",",
"key",
",",
"minutes",
",",
"callback",
")",
":",
"# If the item exists in the cache we will just return this immediately",
"# otherwise we will execute the given callback and cache the result",
"# of that execution for the given number of minutes in ... | Get an item from the cache, or store the default value.
:param key: The cache key
:type key: str
:param minutes: The lifetime in minutes of the cached value
:type minutes: int or datetime
:param callback: The default function
:type callback: mixed
:rtype: mixe... | [
"Get",
"an",
"item",
"from",
"the",
"cache",
"or",
"store",
"the",
"default",
"value",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L153-L179 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.remember_forever | def remember_forever(self, key, callback):
"""
Get an item from the cache, or store the default value forever.
:param key: The cache key
:type key: str
:param callback: The default function
:type callback: mixed
:rtype: mixed
"""
# If the item e... | python | def remember_forever(self, key, callback):
"""
Get an item from the cache, or store the default value forever.
:param key: The cache key
:type key: str
:param callback: The default function
:type callback: mixed
:rtype: mixed
"""
# If the item e... | [
"def",
"remember_forever",
"(",
"self",
",",
"key",
",",
"callback",
")",
":",
"# If the item exists in the cache we will just return this immediately",
"# otherwise we will execute the given callback and cache the result",
"# of that execution forever.",
"val",
"=",
"self",
".",
"... | Get an item from the cache, or store the default value forever.
:param key: The cache key
:type key: str
:param callback: The default function
:type callback: mixed
:rtype: mixed | [
"Get",
"an",
"item",
"from",
"the",
"cache",
"or",
"store",
"the",
"default",
"value",
"forever",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L181-L204 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache.tagged_item_key | def tagged_item_key(self, key):
"""
Get a fully qualified key for a tagged item.
:param key: The cache key
:type key: str
:rtype: str
"""
return '%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key) | python | def tagged_item_key(self, key):
"""
Get a fully qualified key for a tagged item.
:param key: The cache key
:type key: str
:rtype: str
"""
return '%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key) | [
"def",
"tagged_item_key",
"(",
"self",
",",
"key",
")",
":",
"return",
"'%s:%s'",
"%",
"(",
"hashlib",
".",
"sha1",
"(",
"encode",
"(",
"self",
".",
"_tags",
".",
"get_namespace",
"(",
")",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"key",
")"
] | Get a fully qualified key for a tagged item.
:param key: The cache key
:type key: str
:rtype: str | [
"Get",
"a",
"fully",
"qualified",
"key",
"for",
"a",
"tagged",
"item",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L206-L215 |
sdispater/cachy | cachy/tagged_cache.py | TaggedCache._get_minutes | def _get_minutes(self, duration):
"""
Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None
"""
if isinstance(duration, datetime.datetime):
from_now = (duration - da... | python | def _get_minutes(self, duration):
"""
Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None
"""
if isinstance(duration, datetime.datetime):
from_now = (duration - da... | [
"def",
"_get_minutes",
"(",
"self",
",",
"duration",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"datetime",
".",
"datetime",
")",
":",
"from_now",
"=",
"(",
"duration",
"-",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
".",
"total_s... | Calculate the number of minutes with the given duration.
:param duration: The duration
:type duration: int or datetime
:rtype: int or None | [
"Calculate",
"the",
"number",
"of",
"minutes",
"with",
"the",
"given",
"duration",
"."
] | train | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L225-L243 |
fabaff/python-netdata | example.py | main | async def main():
"""Get the data from a Netdata instance."""
with aiohttp.ClientSession() as session:
data = Netdata('localhost', loop, session, data='data')
await data.get_data('system.cpu')
print(json.dumps(data.values, indent=4, sort_keys=True))
# Print the current value of... | python | async def main():
"""Get the data from a Netdata instance."""
with aiohttp.ClientSession() as session:
data = Netdata('localhost', loop, session, data='data')
await data.get_data('system.cpu')
print(json.dumps(data.values, indent=4, sort_keys=True))
# Print the current value of... | [
"async",
"def",
"main",
"(",
")",
":",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"data",
"=",
"Netdata",
"(",
"'localhost'",
",",
"loop",
",",
"session",
",",
"data",
"=",
"'data'",
")",
"await",
"data",
".",
"get_data",
... | Get the data from a Netdata instance. | [
"Get",
"the",
"data",
"from",
"a",
"Netdata",
"instance",
"."
] | train | https://github.com/fabaff/python-netdata/blob/bca5d58f84a0fc849b9bb16a00959a0b33d13a67/example.py#L9-L34 |
inveniosoftware/invenio-logging | invenio_logging/console.py | InvenioLoggingConsole.install_handler | def install_handler(self, app):
"""Install logging handler."""
# Configure python logging
if app.config['LOGGING_CONSOLE_PYWARNINGS']:
self.capture_pywarnings(logging.StreamHandler())
if app.config['LOGGING_CONSOLE_LEVEL'] is not None:
for h in app.logger.handler... | python | def install_handler(self, app):
"""Install logging handler."""
# Configure python logging
if app.config['LOGGING_CONSOLE_PYWARNINGS']:
self.capture_pywarnings(logging.StreamHandler())
if app.config['LOGGING_CONSOLE_LEVEL'] is not None:
for h in app.logger.handler... | [
"def",
"install_handler",
"(",
"self",
",",
"app",
")",
":",
"# Configure python logging",
"if",
"app",
".",
"config",
"[",
"'LOGGING_CONSOLE_PYWARNINGS'",
"]",
":",
"self",
".",
"capture_pywarnings",
"(",
"logging",
".",
"StreamHandler",
"(",
")",
")",
"if",
... | Install logging handler. | [
"Install",
"logging",
"handler",
"."
] | train | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/console.py#L46-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.