repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
inspirehep/refextract | refextract/references/text.py | strip_footer | def strip_footer(ref_lines, section_title):
"""Remove footer title from references lines"""
pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re.escape(section_title)
re_footer = re.compile(pattern, re.UNICODE)
return [l for l in ref_lines if not re_footer.match(l)] | python | def strip_footer(ref_lines, section_title):
"""Remove footer title from references lines"""
pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re.escape(section_title)
re_footer = re.compile(pattern, re.UNICODE)
return [l for l in ref_lines if not re_footer.match(l)] | [
"def",
"strip_footer",
"(",
"ref_lines",
",",
"section_title",
")",
":",
"pattern",
"=",
"ur'\\(?\\[?\\d{0,4}\\]?\\)?\\.?\\s*%s\\s*$'",
"%",
"re",
".",
"escape",
"(",
"section_title",
")",
"re_footer",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"re",
".",
"UNICODE",
")",
"return",
"[",
"l",
"for",
"l",
"in",
"ref_lines",
"if",
"not",
"re_footer",
".",
"match",
"(",
"l",
")",
"]"
] | Remove footer title from references lines | [
"Remove",
"footer",
"title",
"from",
"references",
"lines"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L155-L159 | train | 236,600 |
inspirehep/refextract | refextract/references/api.py | extract_references_from_url | def extract_references_from_url(url, headers=None, chunk_size=1024, **kwargs):
"""Extract references from the pdf specified in the url.
The first parameter is the URL of the file.
It returns a list of parsed references.
It raises FullTextNotAvailableError if the URL gives a 404,
UnknownDocumentTypeError if it is not a PDF or plain text.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_url(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_url(path, override_kbs_files={'journals': 'my/path/to.kb'})
"""
# Get temporary filepath to download to
filename, filepath = mkstemp(
suffix=u"_{0}".format(os.path.basename(url)),
)
os.close(filename)
try:
req = requests.get(
url=url,
headers=headers,
stream=True
)
req.raise_for_status()
with open(filepath, 'wb') as f:
for chunk in req.iter_content(chunk_size):
f.write(chunk)
references = extract_references_from_file(filepath, **kwargs)
except requests.exceptions.HTTPError:
raise FullTextNotAvailableError(u"URL not found: '{0}'".format(url)), None, sys.exc_info()[2]
finally:
os.remove(filepath)
return references | python | def extract_references_from_url(url, headers=None, chunk_size=1024, **kwargs):
"""Extract references from the pdf specified in the url.
The first parameter is the URL of the file.
It returns a list of parsed references.
It raises FullTextNotAvailableError if the URL gives a 404,
UnknownDocumentTypeError if it is not a PDF or plain text.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_url(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_url(path, override_kbs_files={'journals': 'my/path/to.kb'})
"""
# Get temporary filepath to download to
filename, filepath = mkstemp(
suffix=u"_{0}".format(os.path.basename(url)),
)
os.close(filename)
try:
req = requests.get(
url=url,
headers=headers,
stream=True
)
req.raise_for_status()
with open(filepath, 'wb') as f:
for chunk in req.iter_content(chunk_size):
f.write(chunk)
references = extract_references_from_file(filepath, **kwargs)
except requests.exceptions.HTTPError:
raise FullTextNotAvailableError(u"URL not found: '{0}'".format(url)), None, sys.exc_info()[2]
finally:
os.remove(filepath)
return references | [
"def",
"extract_references_from_url",
"(",
"url",
",",
"headers",
"=",
"None",
",",
"chunk_size",
"=",
"1024",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get temporary filepath to download to",
"filename",
",",
"filepath",
"=",
"mkstemp",
"(",
"suffix",
"=",
"u\"_{0}\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"url",
")",
")",
",",
")",
"os",
".",
"close",
"(",
"filename",
")",
"try",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"url",
",",
"headers",
"=",
"headers",
",",
"stream",
"=",
"True",
")",
"req",
".",
"raise_for_status",
"(",
")",
"with",
"open",
"(",
"filepath",
",",
"'wb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"req",
".",
"iter_content",
"(",
"chunk_size",
")",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"references",
"=",
"extract_references_from_file",
"(",
"filepath",
",",
"*",
"*",
"kwargs",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
":",
"raise",
"FullTextNotAvailableError",
"(",
"u\"URL not found: '{0}'\"",
".",
"format",
"(",
"url",
")",
")",
",",
"None",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"finally",
":",
"os",
".",
"remove",
"(",
"filepath",
")",
"return",
"references"
] | Extract references from the pdf specified in the url.
The first parameter is the URL of the file.
It returns a list of parsed references.
It raises FullTextNotAvailableError if the URL gives a 404,
UnknownDocumentTypeError if it is not a PDF or plain text.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_url(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_url(path, override_kbs_files={'journals': 'my/path/to.kb'}) | [
"Extract",
"references",
"from",
"the",
"pdf",
"specified",
"in",
"the",
"url",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L54-L99 | train | 236,601 |
inspirehep/refextract | refextract/references/api.py | extract_references_from_file | def extract_references_from_file(path,
recid=None,
reference_format=u"{title} {volume} ({year}) {page}",
linker_callback=None,
override_kbs_files=None):
"""Extract references from a local pdf file.
The first parameter is the path to the file.
It returns a list of parsed references.
It raises FullTextNotAvailableError if the file does not exist,
UnknownDocumentTypeError if it is not a PDF or plain text.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_file(path, reference_format=u"{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_file(path, override_kbs_files={'journals': 'my/path/to.kb'})
"""
if not os.path.isfile(path):
raise FullTextNotAvailableError(u"File not found: '{0}'".format(path))
docbody = get_plaintext_document_body(path)
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
if not reflines:
docbody = get_plaintext_document_body(path, keep_layout=True)
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
parsed_refs, stats = parse_references(
reflines,
recid=recid,
reference_format=reference_format,
linker_callback=linker_callback,
override_kbs_files=override_kbs_files,
)
if magic.from_file(path, mime=True) == "application/pdf":
texkeys = extract_texkeys_from_pdf(path)
if len(texkeys) == len(parsed_refs):
parsed_refs = [dict(ref, texkey=[key]) for ref, key in izip(parsed_refs, texkeys)]
return parsed_refs | python | def extract_references_from_file(path,
recid=None,
reference_format=u"{title} {volume} ({year}) {page}",
linker_callback=None,
override_kbs_files=None):
"""Extract references from a local pdf file.
The first parameter is the path to the file.
It returns a list of parsed references.
It raises FullTextNotAvailableError if the file does not exist,
UnknownDocumentTypeError if it is not a PDF or plain text.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_file(path, reference_format=u"{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_file(path, override_kbs_files={'journals': 'my/path/to.kb'})
"""
if not os.path.isfile(path):
raise FullTextNotAvailableError(u"File not found: '{0}'".format(path))
docbody = get_plaintext_document_body(path)
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
if not reflines:
docbody = get_plaintext_document_body(path, keep_layout=True)
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
parsed_refs, stats = parse_references(
reflines,
recid=recid,
reference_format=reference_format,
linker_callback=linker_callback,
override_kbs_files=override_kbs_files,
)
if magic.from_file(path, mime=True) == "application/pdf":
texkeys = extract_texkeys_from_pdf(path)
if len(texkeys) == len(parsed_refs):
parsed_refs = [dict(ref, texkey=[key]) for ref, key in izip(parsed_refs, texkeys)]
return parsed_refs | [
"def",
"extract_references_from_file",
"(",
"path",
",",
"recid",
"=",
"None",
",",
"reference_format",
"=",
"u\"{title} {volume} ({year}) {page}\"",
",",
"linker_callback",
"=",
"None",
",",
"override_kbs_files",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"raise",
"FullTextNotAvailableError",
"(",
"u\"File not found: '{0}'\"",
".",
"format",
"(",
"path",
")",
")",
"docbody",
"=",
"get_plaintext_document_body",
"(",
"path",
")",
"reflines",
",",
"dummy",
",",
"dummy",
"=",
"extract_references_from_fulltext",
"(",
"docbody",
")",
"if",
"not",
"reflines",
":",
"docbody",
"=",
"get_plaintext_document_body",
"(",
"path",
",",
"keep_layout",
"=",
"True",
")",
"reflines",
",",
"dummy",
",",
"dummy",
"=",
"extract_references_from_fulltext",
"(",
"docbody",
")",
"parsed_refs",
",",
"stats",
"=",
"parse_references",
"(",
"reflines",
",",
"recid",
"=",
"recid",
",",
"reference_format",
"=",
"reference_format",
",",
"linker_callback",
"=",
"linker_callback",
",",
"override_kbs_files",
"=",
"override_kbs_files",
",",
")",
"if",
"magic",
".",
"from_file",
"(",
"path",
",",
"mime",
"=",
"True",
")",
"==",
"\"application/pdf\"",
":",
"texkeys",
"=",
"extract_texkeys_from_pdf",
"(",
"path",
")",
"if",
"len",
"(",
"texkeys",
")",
"==",
"len",
"(",
"parsed_refs",
")",
":",
"parsed_refs",
"=",
"[",
"dict",
"(",
"ref",
",",
"texkey",
"=",
"[",
"key",
"]",
")",
"for",
"ref",
",",
"key",
"in",
"izip",
"(",
"parsed_refs",
",",
"texkeys",
")",
"]",
"return",
"parsed_refs"
] | Extract references from a local pdf file.
The first parameter is the path to the file.
It returns a list of parsed references.
It raises FullTextNotAvailableError if the file does not exist,
UnknownDocumentTypeError if it is not a PDF or plain text.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_file(path, reference_format=u"{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_file(path, override_kbs_files={'journals': 'my/path/to.kb'}) | [
"Extract",
"references",
"from",
"a",
"local",
"pdf",
"file",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L102-L151 | train | 236,602 |
inspirehep/refextract | refextract/references/api.py | extract_references_from_string | def extract_references_from_string(source,
is_only_references=True,
recid=None,
reference_format="{title} {volume} ({year}) {page}",
linker_callback=None,
override_kbs_files=None):
"""Extract references from a raw string.
The first parameter is the path to the file.
It returns a tuple (references, stats).
If the string does not only contain references, improve accuracy by
specifing ``is_only_references=False``.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_string(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_string(path, override_kbs_files={'journals': 'my/path/to.kb'})
"""
docbody = source.split('\n')
if not is_only_references:
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
else:
refs_info = get_reference_section_beginning(docbody)
if not refs_info:
refs_info, dummy = find_numeration_in_body(docbody)
refs_info['start_line'] = 0
refs_info['end_line'] = len(docbody) - 1,
reflines = rebuild_reference_lines(
docbody, refs_info['marker_pattern'])
parsed_refs, stats = parse_references(
reflines,
recid=recid,
reference_format=reference_format,
linker_callback=linker_callback,
override_kbs_files=override_kbs_files,
)
return parsed_refs | python | def extract_references_from_string(source,
is_only_references=True,
recid=None,
reference_format="{title} {volume} ({year}) {page}",
linker_callback=None,
override_kbs_files=None):
"""Extract references from a raw string.
The first parameter is the path to the file.
It returns a tuple (references, stats).
If the string does not only contain references, improve accuracy by
specifing ``is_only_references=False``.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_string(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_string(path, override_kbs_files={'journals': 'my/path/to.kb'})
"""
docbody = source.split('\n')
if not is_only_references:
reflines, dummy, dummy = extract_references_from_fulltext(docbody)
else:
refs_info = get_reference_section_beginning(docbody)
if not refs_info:
refs_info, dummy = find_numeration_in_body(docbody)
refs_info['start_line'] = 0
refs_info['end_line'] = len(docbody) - 1,
reflines = rebuild_reference_lines(
docbody, refs_info['marker_pattern'])
parsed_refs, stats = parse_references(
reflines,
recid=recid,
reference_format=reference_format,
linker_callback=linker_callback,
override_kbs_files=override_kbs_files,
)
return parsed_refs | [
"def",
"extract_references_from_string",
"(",
"source",
",",
"is_only_references",
"=",
"True",
",",
"recid",
"=",
"None",
",",
"reference_format",
"=",
"\"{title} {volume} ({year}) {page}\"",
",",
"linker_callback",
"=",
"None",
",",
"override_kbs_files",
"=",
"None",
")",
":",
"docbody",
"=",
"source",
".",
"split",
"(",
"'\\n'",
")",
"if",
"not",
"is_only_references",
":",
"reflines",
",",
"dummy",
",",
"dummy",
"=",
"extract_references_from_fulltext",
"(",
"docbody",
")",
"else",
":",
"refs_info",
"=",
"get_reference_section_beginning",
"(",
"docbody",
")",
"if",
"not",
"refs_info",
":",
"refs_info",
",",
"dummy",
"=",
"find_numeration_in_body",
"(",
"docbody",
")",
"refs_info",
"[",
"'start_line'",
"]",
"=",
"0",
"refs_info",
"[",
"'end_line'",
"]",
"=",
"len",
"(",
"docbody",
")",
"-",
"1",
",",
"reflines",
"=",
"rebuild_reference_lines",
"(",
"docbody",
",",
"refs_info",
"[",
"'marker_pattern'",
"]",
")",
"parsed_refs",
",",
"stats",
"=",
"parse_references",
"(",
"reflines",
",",
"recid",
"=",
"recid",
",",
"reference_format",
"=",
"reference_format",
",",
"linker_callback",
"=",
"linker_callback",
",",
"override_kbs_files",
"=",
"override_kbs_files",
",",
")",
"return",
"parsed_refs"
] | Extract references from a raw string.
The first parameter is the path to the file.
It returns a tuple (references, stats).
If the string does not only contain references, improve accuracy by
specifing ``is_only_references=False``.
The standard reference format is: {title} {volume} ({year}) {page}.
E.g. you can change that by passing the reference_format:
>>> extract_references_from_string(path, reference_format="{title},{volume},{page}")
If you want to also link each reference to some other resource (like a record),
you can provide a linker_callback function to be executed for every reference
element found.
To override KBs for journal names etc., use ``override_kbs_files``:
>>> extract_references_from_string(path, override_kbs_files={'journals': 'my/path/to.kb'}) | [
"Extract",
"references",
"from",
"a",
"raw",
"string",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L154-L201 | train | 236,603 |
inspirehep/refextract | refextract/references/api.py | extract_journal_reference | def extract_journal_reference(line, override_kbs_files=None):
"""Extract the journal reference from string.
Extracts the journal reference from string and parses for specific
journal information.
"""
kbs = get_kbs(custom_kbs_files=override_kbs_files)
references, dummy_m, dummy_c, dummy_co = parse_reference_line(line, kbs)
for elements in references:
for el in elements:
if el['type'] == 'JOURNAL':
return el | python | def extract_journal_reference(line, override_kbs_files=None):
"""Extract the journal reference from string.
Extracts the journal reference from string and parses for specific
journal information.
"""
kbs = get_kbs(custom_kbs_files=override_kbs_files)
references, dummy_m, dummy_c, dummy_co = parse_reference_line(line, kbs)
for elements in references:
for el in elements:
if el['type'] == 'JOURNAL':
return el | [
"def",
"extract_journal_reference",
"(",
"line",
",",
"override_kbs_files",
"=",
"None",
")",
":",
"kbs",
"=",
"get_kbs",
"(",
"custom_kbs_files",
"=",
"override_kbs_files",
")",
"references",
",",
"dummy_m",
",",
"dummy_c",
",",
"dummy_co",
"=",
"parse_reference_line",
"(",
"line",
",",
"kbs",
")",
"for",
"elements",
"in",
"references",
":",
"for",
"el",
"in",
"elements",
":",
"if",
"el",
"[",
"'type'",
"]",
"==",
"'JOURNAL'",
":",
"return",
"el"
] | Extract the journal reference from string.
Extracts the journal reference from string and parses for specific
journal information. | [
"Extract",
"the",
"journal",
"reference",
"from",
"string",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L204-L216 | train | 236,604 |
inspirehep/refextract | refextract/references/record.py | build_references | def build_references(citations, reference_format=False):
"""Build list of reference dictionaries from a references list
"""
# Now, run the method which will take as input:
# 1. A list of lists of dictionaries, where each dictionary is a piece
# of citation information corresponding to a tag in the citation.
# 2. The line marker for this entire citation line (mulitple citation
# 'finds' inside a single citation will use the same marker value)
# The resulting xml line will be a properly marked up form of the
# citation. It will take into account authors to try and split up
# references which should be read as two SEPARATE ones.
return [c for citation_elements in citations
for elements in citation_elements['elements']
for c in build_reference_fields(elements,
citation_elements['line_marker'],
citation_elements['raw_ref'],
reference_format)] | python | def build_references(citations, reference_format=False):
"""Build list of reference dictionaries from a references list
"""
# Now, run the method which will take as input:
# 1. A list of lists of dictionaries, where each dictionary is a piece
# of citation information corresponding to a tag in the citation.
# 2. The line marker for this entire citation line (mulitple citation
# 'finds' inside a single citation will use the same marker value)
# The resulting xml line will be a properly marked up form of the
# citation. It will take into account authors to try and split up
# references which should be read as two SEPARATE ones.
return [c for citation_elements in citations
for elements in citation_elements['elements']
for c in build_reference_fields(elements,
citation_elements['line_marker'],
citation_elements['raw_ref'],
reference_format)] | [
"def",
"build_references",
"(",
"citations",
",",
"reference_format",
"=",
"False",
")",
":",
"# Now, run the method which will take as input:",
"# 1. A list of lists of dictionaries, where each dictionary is a piece",
"# of citation information corresponding to a tag in the citation.",
"# 2. The line marker for this entire citation line (mulitple citation",
"# 'finds' inside a single citation will use the same marker value)",
"# The resulting xml line will be a properly marked up form of the",
"# citation. It will take into account authors to try and split up",
"# references which should be read as two SEPARATE ones.",
"return",
"[",
"c",
"for",
"citation_elements",
"in",
"citations",
"for",
"elements",
"in",
"citation_elements",
"[",
"'elements'",
"]",
"for",
"c",
"in",
"build_reference_fields",
"(",
"elements",
",",
"citation_elements",
"[",
"'line_marker'",
"]",
",",
"citation_elements",
"[",
"'raw_ref'",
"]",
",",
"reference_format",
")",
"]"
] | Build list of reference dictionaries from a references list | [
"Build",
"list",
"of",
"reference",
"dictionaries",
"from",
"a",
"references",
"list"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L31-L47 | train | 236,605 |
inspirehep/refextract | refextract/references/record.py | build_reference_fields | def build_reference_fields(citation_elements, line_marker, raw_ref,
reference_format):
"""Create the final representation of the reference information.
@param citation_elements: (list) an ordered list of dictionary elements,
with each element corresponding to a found
piece of information from a reference line.
@param line_marker: (string) The line marker for this single reference
line (e.g. [19])
@param raw_ref: (string) The raw string of this line
@return reference_fields: (list) A list of one dictionary containing the
reference elements
"""
# Begin the datafield element
current_field = create_reference_field(line_marker)
current_field['raw_ref'] = [raw_ref]
reference_fields = [current_field]
for element in citation_elements:
# Before going onto checking 'what' the next element is,
# handle misc text and semi-colons
# Multiple misc text subfields will be compressed later
# This will also be the only part of the code that deals with MISC
# tag_typed elements
misc_txt = element['misc_txt']
if misc_txt.strip("., [](){}"):
misc_txt = misc_txt.lstrip('])} ,.').rstrip('[({ ,.')
add_subfield(current_field, 'misc', misc_txt)
# Now handle the type dependent actions
# JOURNAL
if element['type'] == "JOURNAL":
add_journal_subfield(current_field, element, reference_format)
# REPORT NUMBER
elif element['type'] == "REPORTNUMBER":
add_subfield(current_field, 'reportnumber', element['report_num'])
# URL
elif element['type'] == "URL":
if element['url_string'] == element['url_desc']:
# Build the datafield for the URL segment of the reference
# line:
add_subfield(current_field, 'url', element['url_string'])
# Else, in the case that the url string and the description differ
# in some way, include them both
else:
add_subfield(current_field, 'url', element['url_string'])
add_subfield(current_field, 'urldesc', element['url_desc'])
# DOI
elif element['type'] == "DOI":
add_subfield(current_field, 'doi', 'doi:' + element['doi_string'])
# HDL
elif element['type'] == "HDL":
add_subfield(current_field, 'hdl', 'hdl:' + element['hdl_id'])
# AUTHOR
elif element['type'] == "AUTH":
value = element['auth_txt']
if element['auth_type'] == 'incl':
value = "(%s)" % value
add_subfield(current_field, 'author', value)
elif element['type'] == "QUOTED":
add_subfield(current_field, 'title', element['title'])
elif element['type'] == "ISBN":
add_subfield(current_field, 'isbn', element['ISBN'])
elif element['type'] == "BOOK":
add_subfield(current_field, 'title', element['title'])
elif element['type'] == "PUBLISHER":
add_subfield(current_field, 'publisher', element['publisher'])
elif element['type'] == "YEAR":
add_subfield(current_field, 'year', element['year'])
elif element['type'] == "COLLABORATION":
add_subfield(current_field,
'collaboration',
element['collaboration'])
elif element['type'] == "RECID":
add_subfield(current_field, 'recid', str(element['recid']))
return reference_fields | python | def build_reference_fields(citation_elements, line_marker, raw_ref,
reference_format):
"""Create the final representation of the reference information.
@param citation_elements: (list) an ordered list of dictionary elements,
with each element corresponding to a found
piece of information from a reference line.
@param line_marker: (string) The line marker for this single reference
line (e.g. [19])
@param raw_ref: (string) The raw string of this line
@return reference_fields: (list) A list of one dictionary containing the
reference elements
"""
# Begin the datafield element
current_field = create_reference_field(line_marker)
current_field['raw_ref'] = [raw_ref]
reference_fields = [current_field]
for element in citation_elements:
# Before going onto checking 'what' the next element is,
# handle misc text and semi-colons
# Multiple misc text subfields will be compressed later
# This will also be the only part of the code that deals with MISC
# tag_typed elements
misc_txt = element['misc_txt']
if misc_txt.strip("., [](){}"):
misc_txt = misc_txt.lstrip('])} ,.').rstrip('[({ ,.')
add_subfield(current_field, 'misc', misc_txt)
# Now handle the type dependent actions
# JOURNAL
if element['type'] == "JOURNAL":
add_journal_subfield(current_field, element, reference_format)
# REPORT NUMBER
elif element['type'] == "REPORTNUMBER":
add_subfield(current_field, 'reportnumber', element['report_num'])
# URL
elif element['type'] == "URL":
if element['url_string'] == element['url_desc']:
# Build the datafield for the URL segment of the reference
# line:
add_subfield(current_field, 'url', element['url_string'])
# Else, in the case that the url string and the description differ
# in some way, include them both
else:
add_subfield(current_field, 'url', element['url_string'])
add_subfield(current_field, 'urldesc', element['url_desc'])
# DOI
elif element['type'] == "DOI":
add_subfield(current_field, 'doi', 'doi:' + element['doi_string'])
# HDL
elif element['type'] == "HDL":
add_subfield(current_field, 'hdl', 'hdl:' + element['hdl_id'])
# AUTHOR
elif element['type'] == "AUTH":
value = element['auth_txt']
if element['auth_type'] == 'incl':
value = "(%s)" % value
add_subfield(current_field, 'author', value)
elif element['type'] == "QUOTED":
add_subfield(current_field, 'title', element['title'])
elif element['type'] == "ISBN":
add_subfield(current_field, 'isbn', element['ISBN'])
elif element['type'] == "BOOK":
add_subfield(current_field, 'title', element['title'])
elif element['type'] == "PUBLISHER":
add_subfield(current_field, 'publisher', element['publisher'])
elif element['type'] == "YEAR":
add_subfield(current_field, 'year', element['year'])
elif element['type'] == "COLLABORATION":
add_subfield(current_field,
'collaboration',
element['collaboration'])
elif element['type'] == "RECID":
add_subfield(current_field, 'recid', str(element['recid']))
return reference_fields | [
"def",
"build_reference_fields",
"(",
"citation_elements",
",",
"line_marker",
",",
"raw_ref",
",",
"reference_format",
")",
":",
"# Begin the datafield element",
"current_field",
"=",
"create_reference_field",
"(",
"line_marker",
")",
"current_field",
"[",
"'raw_ref'",
"]",
"=",
"[",
"raw_ref",
"]",
"reference_fields",
"=",
"[",
"current_field",
"]",
"for",
"element",
"in",
"citation_elements",
":",
"# Before going onto checking 'what' the next element is,",
"# handle misc text and semi-colons",
"# Multiple misc text subfields will be compressed later",
"# This will also be the only part of the code that deals with MISC",
"# tag_typed elements",
"misc_txt",
"=",
"element",
"[",
"'misc_txt'",
"]",
"if",
"misc_txt",
".",
"strip",
"(",
"\"., [](){}\"",
")",
":",
"misc_txt",
"=",
"misc_txt",
".",
"lstrip",
"(",
"'])} ,.'",
")",
".",
"rstrip",
"(",
"'[({ ,.'",
")",
"add_subfield",
"(",
"current_field",
",",
"'misc'",
",",
"misc_txt",
")",
"# Now handle the type dependent actions",
"# JOURNAL",
"if",
"element",
"[",
"'type'",
"]",
"==",
"\"JOURNAL\"",
":",
"add_journal_subfield",
"(",
"current_field",
",",
"element",
",",
"reference_format",
")",
"# REPORT NUMBER",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"REPORTNUMBER\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'reportnumber'",
",",
"element",
"[",
"'report_num'",
"]",
")",
"# URL",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"URL\"",
":",
"if",
"element",
"[",
"'url_string'",
"]",
"==",
"element",
"[",
"'url_desc'",
"]",
":",
"# Build the datafield for the URL segment of the reference",
"# line:",
"add_subfield",
"(",
"current_field",
",",
"'url'",
",",
"element",
"[",
"'url_string'",
"]",
")",
"# Else, in the case that the url string and the description differ",
"# in some way, include them both",
"else",
":",
"add_subfield",
"(",
"current_field",
",",
"'url'",
",",
"element",
"[",
"'url_string'",
"]",
")",
"add_subfield",
"(",
"current_field",
",",
"'urldesc'",
",",
"element",
"[",
"'url_desc'",
"]",
")",
"# DOI",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"DOI\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'doi'",
",",
"'doi:'",
"+",
"element",
"[",
"'doi_string'",
"]",
")",
"# HDL",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"HDL\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'hdl'",
",",
"'hdl:'",
"+",
"element",
"[",
"'hdl_id'",
"]",
")",
"# AUTHOR",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"AUTH\"",
":",
"value",
"=",
"element",
"[",
"'auth_txt'",
"]",
"if",
"element",
"[",
"'auth_type'",
"]",
"==",
"'incl'",
":",
"value",
"=",
"\"(%s)\"",
"%",
"value",
"add_subfield",
"(",
"current_field",
",",
"'author'",
",",
"value",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"QUOTED\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'title'",
",",
"element",
"[",
"'title'",
"]",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"ISBN\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'isbn'",
",",
"element",
"[",
"'ISBN'",
"]",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"BOOK\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'title'",
",",
"element",
"[",
"'title'",
"]",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"PUBLISHER\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'publisher'",
",",
"element",
"[",
"'publisher'",
"]",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"YEAR\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'year'",
",",
"element",
"[",
"'year'",
"]",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"COLLABORATION\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'collaboration'",
",",
"element",
"[",
"'collaboration'",
"]",
")",
"elif",
"element",
"[",
"'type'",
"]",
"==",
"\"RECID\"",
":",
"add_subfield",
"(",
"current_field",
",",
"'recid'",
",",
"str",
"(",
"element",
"[",
"'recid'",
"]",
")",
")",
"return",
"reference_fields"
] | Create the final representation of the reference information.
@param citation_elements: (list) an ordered list of dictionary elements,
with each element corresponding to a found
piece of information from a reference line.
@param line_marker: (string) The line marker for this single reference
line (e.g. [19])
@param raw_ref: (string) The raw string of this line
@return reference_fields: (list) A list of one dictionary containing the
reference elements | [
"Create",
"the",
"final",
"representation",
"of",
"the",
"reference",
"information",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L71-L161 | train | 236,606 |
inspirehep/refextract | refextract/references/pdf.py | extract_texkeys_from_pdf | def extract_texkeys_from_pdf(pdf_file):
"""
Extract the texkeys from the given PDF file
This is done by looking up the named destinations in the PDF
@param pdf_file: path to a PDF
@return: list of all texkeys found in the PDF
"""
with open(pdf_file, 'rb') as pdf_stream:
try:
pdf = PdfFileReader(pdf_stream, strict=False)
destinations = pdf.getNamedDestinations()
except Exception:
LOGGER.debug(u"PDF: Internal PyPDF2 error, no TeXkeys returned.")
return []
# not all named destinations point to references
refs = [dest for dest in destinations.iteritems()
if re_reference_in_dest.match(dest[0])]
try:
if _destinations_in_two_columns(pdf, refs):
LOGGER.debug(u"PDF: Using two-column layout")
def sortfunc(dest_couple):
return _destination_position(pdf, dest_couple[1])
else:
LOGGER.debug(u"PDF: Using single-column layout")
def sortfunc(dest_couple):
(page, _, ypos, xpos) = _destination_position(
pdf, dest_couple[1])
return (page, ypos, xpos)
refs.sort(key=sortfunc)
# extract the TeXkey from the named destination name
return [re_reference_in_dest.match(destname).group(1)
for (destname, _) in refs]
except Exception:
LOGGER.debug(u"PDF: Impossible to determine layout, no TeXkeys returned")
return [] | python | def extract_texkeys_from_pdf(pdf_file):
"""
Extract the texkeys from the given PDF file
This is done by looking up the named destinations in the PDF
@param pdf_file: path to a PDF
@return: list of all texkeys found in the PDF
"""
with open(pdf_file, 'rb') as pdf_stream:
try:
pdf = PdfFileReader(pdf_stream, strict=False)
destinations = pdf.getNamedDestinations()
except Exception:
LOGGER.debug(u"PDF: Internal PyPDF2 error, no TeXkeys returned.")
return []
# not all named destinations point to references
refs = [dest for dest in destinations.iteritems()
if re_reference_in_dest.match(dest[0])]
try:
if _destinations_in_two_columns(pdf, refs):
LOGGER.debug(u"PDF: Using two-column layout")
def sortfunc(dest_couple):
return _destination_position(pdf, dest_couple[1])
else:
LOGGER.debug(u"PDF: Using single-column layout")
def sortfunc(dest_couple):
(page, _, ypos, xpos) = _destination_position(
pdf, dest_couple[1])
return (page, ypos, xpos)
refs.sort(key=sortfunc)
# extract the TeXkey from the named destination name
return [re_reference_in_dest.match(destname).group(1)
for (destname, _) in refs]
except Exception:
LOGGER.debug(u"PDF: Impossible to determine layout, no TeXkeys returned")
return [] | [
"def",
"extract_texkeys_from_pdf",
"(",
"pdf_file",
")",
":",
"with",
"open",
"(",
"pdf_file",
",",
"'rb'",
")",
"as",
"pdf_stream",
":",
"try",
":",
"pdf",
"=",
"PdfFileReader",
"(",
"pdf_stream",
",",
"strict",
"=",
"False",
")",
"destinations",
"=",
"pdf",
".",
"getNamedDestinations",
"(",
")",
"except",
"Exception",
":",
"LOGGER",
".",
"debug",
"(",
"u\"PDF: Internal PyPDF2 error, no TeXkeys returned.\"",
")",
"return",
"[",
"]",
"# not all named destinations point to references",
"refs",
"=",
"[",
"dest",
"for",
"dest",
"in",
"destinations",
".",
"iteritems",
"(",
")",
"if",
"re_reference_in_dest",
".",
"match",
"(",
"dest",
"[",
"0",
"]",
")",
"]",
"try",
":",
"if",
"_destinations_in_two_columns",
"(",
"pdf",
",",
"refs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"u\"PDF: Using two-column layout\"",
")",
"def",
"sortfunc",
"(",
"dest_couple",
")",
":",
"return",
"_destination_position",
"(",
"pdf",
",",
"dest_couple",
"[",
"1",
"]",
")",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"u\"PDF: Using single-column layout\"",
")",
"def",
"sortfunc",
"(",
"dest_couple",
")",
":",
"(",
"page",
",",
"_",
",",
"ypos",
",",
"xpos",
")",
"=",
"_destination_position",
"(",
"pdf",
",",
"dest_couple",
"[",
"1",
"]",
")",
"return",
"(",
"page",
",",
"ypos",
",",
"xpos",
")",
"refs",
".",
"sort",
"(",
"key",
"=",
"sortfunc",
")",
"# extract the TeXkey from the named destination name",
"return",
"[",
"re_reference_in_dest",
".",
"match",
"(",
"destname",
")",
".",
"group",
"(",
"1",
")",
"for",
"(",
"destname",
",",
"_",
")",
"in",
"refs",
"]",
"except",
"Exception",
":",
"LOGGER",
".",
"debug",
"(",
"u\"PDF: Impossible to determine layout, no TeXkeys returned\"",
")",
"return",
"[",
"]"
] | Extract the texkeys from the given PDF file
This is done by looking up the named destinations in the PDF
@param pdf_file: path to a PDF
@return: list of all texkeys found in the PDF | [
"Extract",
"the",
"texkeys",
"from",
"the",
"given",
"PDF",
"file"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/pdf.py#L43-L84 | train | 236,607 |
inspirehep/refextract | refextract/references/regexs.py | get_reference_line_numeration_marker_patterns | def get_reference_line_numeration_marker_patterns(prefix=u''):
"""Return a list of compiled regex patterns used to search for the marker
of a reference line in a full-text document.
@param prefix: (string) the possible prefix to a reference line
@return: (list) of compiled regex patterns.
"""
title = u""
if type(prefix) in (str, unicode):
title = prefix
g_name = u'(?P<mark>'
g_close = u')'
space = ur'\s*'
patterns = [
# [1]
space + title + g_name + ur'\[\s*(?P<marknum>\d+)\s*\]' + g_close,
# [<letters and numbers]
space + title + g_name +
ur'\[\s*[a-zA-Z:-]+\+?\s?(\d{1,4}[A-Za-z:-]?)?\s*\]' + g_close,
# {1}
space + title + g_name + ur'\{\s*(?P<marknum>\d+)\s*\}' + g_close,
# (1)
space + title + g_name + ur'\<\s*(?P<marknum>\d+)\s*\>' + g_close,
space + title + g_name + ur'\(\s*(?P<marknum>\d+)\s*\)' + g_close,
space + title + g_name + ur'(?P<marknum>\d+)\s*\.(?!\d)' + g_close,
space + title + g_name + ur'(?P<marknum>\d+)\s+' + g_close,
space + title + g_name + ur'(?P<marknum>\d+)\s*\]' + g_close,
# 1]
space + title + g_name + ur'(?P<marknum>\d+)\s*\}' + g_close,
# 1}
space + title + g_name + ur'(?P<marknum>\d+)\s*\)' + g_close,
# 1)
space + title + g_name + ur'(?P<marknum>\d+)\s*\>' + g_close,
# [1.1]
space + title + g_name + ur'\[\s*\d+\.\d+\s*\]' + g_close,
# [ ]
space + title + g_name + ur'\[\s*\]' + g_close,
# *
space + title + g_name + ur'\*' + g_close,
]
return [re.compile(p, re.I | re.UNICODE) for p in patterns] | python | def get_reference_line_numeration_marker_patterns(prefix=u''):
"""Return a list of compiled regex patterns used to search for the marker
of a reference line in a full-text document.
@param prefix: (string) the possible prefix to a reference line
@return: (list) of compiled regex patterns.
"""
title = u""
if type(prefix) in (str, unicode):
title = prefix
g_name = u'(?P<mark>'
g_close = u')'
space = ur'\s*'
patterns = [
# [1]
space + title + g_name + ur'\[\s*(?P<marknum>\d+)\s*\]' + g_close,
# [<letters and numbers]
space + title + g_name +
ur'\[\s*[a-zA-Z:-]+\+?\s?(\d{1,4}[A-Za-z:-]?)?\s*\]' + g_close,
# {1}
space + title + g_name + ur'\{\s*(?P<marknum>\d+)\s*\}' + g_close,
# (1)
space + title + g_name + ur'\<\s*(?P<marknum>\d+)\s*\>' + g_close,
space + title + g_name + ur'\(\s*(?P<marknum>\d+)\s*\)' + g_close,
space + title + g_name + ur'(?P<marknum>\d+)\s*\.(?!\d)' + g_close,
space + title + g_name + ur'(?P<marknum>\d+)\s+' + g_close,
space + title + g_name + ur'(?P<marknum>\d+)\s*\]' + g_close,
# 1]
space + title + g_name + ur'(?P<marknum>\d+)\s*\}' + g_close,
# 1}
space + title + g_name + ur'(?P<marknum>\d+)\s*\)' + g_close,
# 1)
space + title + g_name + ur'(?P<marknum>\d+)\s*\>' + g_close,
# [1.1]
space + title + g_name + ur'\[\s*\d+\.\d+\s*\]' + g_close,
# [ ]
space + title + g_name + ur'\[\s*\]' + g_close,
# *
space + title + g_name + ur'\*' + g_close,
]
return [re.compile(p, re.I | re.UNICODE) for p in patterns] | [
"def",
"get_reference_line_numeration_marker_patterns",
"(",
"prefix",
"=",
"u''",
")",
":",
"title",
"=",
"u\"\"",
"if",
"type",
"(",
"prefix",
")",
"in",
"(",
"str",
",",
"unicode",
")",
":",
"title",
"=",
"prefix",
"g_name",
"=",
"u'(?P<mark>'",
"g_close",
"=",
"u')'",
"space",
"=",
"ur'\\s*'",
"patterns",
"=",
"[",
"# [1]",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\[\\s*(?P<marknum>\\d+)\\s*\\]'",
"+",
"g_close",
",",
"# [<letters and numbers]",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\[\\s*[a-zA-Z:-]+\\+?\\s?(\\d{1,4}[A-Za-z:-]?)?\\s*\\]'",
"+",
"g_close",
",",
"# {1}",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\{\\s*(?P<marknum>\\d+)\\s*\\}'",
"+",
"g_close",
",",
"# (1)",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\<\\s*(?P<marknum>\\d+)\\s*\\>'",
"+",
"g_close",
",",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\(\\s*(?P<marknum>\\d+)\\s*\\)'",
"+",
"g_close",
",",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'(?P<marknum>\\d+)\\s*\\.(?!\\d)'",
"+",
"g_close",
",",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'(?P<marknum>\\d+)\\s+'",
"+",
"g_close",
",",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'(?P<marknum>\\d+)\\s*\\]'",
"+",
"g_close",
",",
"# 1]",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'(?P<marknum>\\d+)\\s*\\}'",
"+",
"g_close",
",",
"# 1}",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'(?P<marknum>\\d+)\\s*\\)'",
"+",
"g_close",
",",
"# 1)",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'(?P<marknum>\\d+)\\s*\\>'",
"+",
"g_close",
",",
"# [1.1]",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\[\\s*\\d+\\.\\d+\\s*\\]'",
"+",
"g_close",
",",
"# [ ]",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\[\\s*\\]'",
"+",
"g_close",
",",
"# *",
"space",
"+",
"title",
"+",
"g_name",
"+",
"ur'\\*'",
"+",
"g_close",
",",
"]",
"return",
"[",
"re",
".",
"compile",
"(",
"p",
",",
"re",
".",
"I",
"|",
"re",
".",
"UNICODE",
")",
"for",
"p",
"in",
"patterns",
"]"
] | Return a list of compiled regex patterns used to search for the marker
of a reference line in a full-text document.
@param prefix: (string) the possible prefix to a reference line
@return: (list) of compiled regex patterns. | [
"Return",
"a",
"list",
"of",
"compiled",
"regex",
"patterns",
"used",
"to",
"search",
"for",
"the",
"marker",
"of",
"a",
"reference",
"line",
"in",
"a",
"full",
"-",
"text",
"document",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L733-L772 | train | 236,608 |
inspirehep/refextract | refextract/references/regexs.py | get_post_reference_section_title_patterns | def get_post_reference_section_title_patterns():
"""Return a list of compiled regex patterns used to search for the title
of the section after the reference section in a full-text document.
@return: (list) of compiled regex patterns.
"""
compiled_patterns = []
thead = ur'^\s*([\{\(\<\[]?\s*(\w|\d)\s*[\)\}\>\.\-\]]?\s*)?'
ttail = ur'(\s*\:\s*)?'
numatn = ur'(\d+|\w\b|i{1,3}v?|vi{0,3})[\.\,]{0,2}\b'
roman_numbers = ur'[LVIX]'
patterns = [
# Section titles
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'appendix') + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'appendices') + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'acknowledgement') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'acknowledgment') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'table') + ur'\w?s?\d?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'figure') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'list of figure') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'annex') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'discussion') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'remercie') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'index') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'summary') + ur's?' + ttail,
# Figure nums
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'figure') + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'fig') + ur'\.\s*' + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'fig') + ur'\.?\s*\d\w?\b',
# Tables
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'table') + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'tab') + ur'\.\s*' + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'tab') + ur'\.?\s*\d\w?\b',
# Other titles formats
ur'^\s*' + roman_numbers + ur'\.?\s*[Cc]onclusion[\w\s]*$',
ur'^\s*Appendix\s[A-Z]\s*\:\s*[a-zA-Z]+\s*',
]
for p in patterns:
compiled_patterns.append(re.compile(p, re.I | re.UNICODE))
return compiled_patterns | python | def get_post_reference_section_title_patterns():
"""Return a list of compiled regex patterns used to search for the title
of the section after the reference section in a full-text document.
@return: (list) of compiled regex patterns.
"""
compiled_patterns = []
thead = ur'^\s*([\{\(\<\[]?\s*(\w|\d)\s*[\)\}\>\.\-\]]?\s*)?'
ttail = ur'(\s*\:\s*)?'
numatn = ur'(\d+|\w\b|i{1,3}v?|vi{0,3})[\.\,]{0,2}\b'
roman_numbers = ur'[LVIX]'
patterns = [
# Section titles
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'appendix') + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'appendices') + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'acknowledgement') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'acknowledgment') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'table') + ur'\w?s?\d?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'figure') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'list of figure') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'annex') + ur's?' + ttail,
thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'discussion') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'remercie') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'index') + ur's?' + ttail,
thead +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'summary') + ur's?' + ttail,
# Figure nums
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'figure') + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'fig') + ur'\.\s*' + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'fig') + ur'\.?\s*\d\w?\b',
# Tables
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'table') + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'tab') + ur'\.\s*' + numatn,
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'tab') + ur'\.?\s*\d\w?\b',
# Other titles formats
ur'^\s*' + roman_numbers + ur'\.?\s*[Cc]onclusion[\w\s]*$',
ur'^\s*Appendix\s[A-Z]\s*\:\s*[a-zA-Z]+\s*',
]
for p in patterns:
compiled_patterns.append(re.compile(p, re.I | re.UNICODE))
return compiled_patterns | [
"def",
"get_post_reference_section_title_patterns",
"(",
")",
":",
"compiled_patterns",
"=",
"[",
"]",
"thead",
"=",
"ur'^\\s*([\\{\\(\\<\\[]?\\s*(\\w|\\d)\\s*[\\)\\}\\>\\.\\-\\]]?\\s*)?'",
"ttail",
"=",
"ur'(\\s*\\:\\s*)?'",
"numatn",
"=",
"ur'(\\d+|\\w\\b|i{1,3}v?|vi{0,3})[\\.\\,]{0,2}\\b'",
"roman_numbers",
"=",
"ur'[LVIX]'",
"patterns",
"=",
"[",
"# Section titles",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'appendix'",
")",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'appendices'",
")",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'acknowledgement'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'acknowledgment'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'table'",
")",
"+",
"ur'\\w?s?\\d?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'figure'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'list of figure'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'annex'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'discussion'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'remercie'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'index'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"thead",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'summary'",
")",
"+",
"ur's?'",
"+",
"ttail",
",",
"# Figure nums",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'figure'",
")",
"+",
"numatn",
",",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'fig'",
")",
"+",
"ur'\\.\\s*'",
"+",
"numatn",
",",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'fig'",
")",
"+",
"ur'\\.?\\s*\\d\\w?\\b'",
",",
"# Tables",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'table'",
")",
"+",
"numatn",
",",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'tab'",
")",
"+",
"ur'\\.\\s*'",
"+",
"numatn",
",",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'tab'",
")",
"+",
"ur'\\.?\\s*\\d\\w?\\b'",
",",
"# Other titles formats",
"ur'^\\s*'",
"+",
"roman_numbers",
"+",
"ur'\\.?\\s*[Cc]onclusion[\\w\\s]*$'",
",",
"ur'^\\s*Appendix\\s[A-Z]\\s*\\:\\s*[a-zA-Z]+\\s*'",
",",
"]",
"for",
"p",
"in",
"patterns",
":",
"compiled_patterns",
".",
"append",
"(",
"re",
".",
"compile",
"(",
"p",
",",
"re",
".",
"I",
"|",
"re",
".",
"UNICODE",
")",
")",
"return",
"compiled_patterns"
] | Return a list of compiled regex patterns used to search for the title
of the section after the reference section in a full-text document.
@return: (list) of compiled regex patterns. | [
"Return",
"a",
"list",
"of",
"compiled",
"regex",
"patterns",
"used",
"to",
"search",
"for",
"the",
"title",
"of",
"the",
"section",
"after",
"the",
"reference",
"section",
"in",
"a",
"full",
"-",
"text",
"document",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L800-L871 | train | 236,609 |
inspirehep/refextract | refextract/references/regexs.py | get_post_reference_section_keyword_patterns | def get_post_reference_section_keyword_patterns():
"""Return a list of compiled regex patterns used to search for various
keywords that can often be found after, and therefore suggest the end of,
a reference section in a full-text document.
@return: (list) of compiled regex patterns.
"""
compiled_patterns = []
patterns = [u'(' + _create_regex_pattern_add_optional_spaces_to_word_characters(u'prepared') +
ur'|' + _create_regex_pattern_add_optional_spaces_to_word_characters(u'created') +
ur').*(AAS\s*)?\sLATEX',
ur'AAS\s+?LATEX\s+?' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'macros') + u'v',
ur'^\s*' + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'This paper has been produced using'),
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(u'This article was processed by the author using Springer-Verlag') +
u' LATEX']
for p in patterns:
compiled_patterns.append(re.compile(p, re.I | re.UNICODE))
return compiled_patterns | python | def get_post_reference_section_keyword_patterns():
"""Return a list of compiled regex patterns used to search for various
keywords that can often be found after, and therefore suggest the end of,
a reference section in a full-text document.
@return: (list) of compiled regex patterns.
"""
compiled_patterns = []
patterns = [u'(' + _create_regex_pattern_add_optional_spaces_to_word_characters(u'prepared') +
ur'|' + _create_regex_pattern_add_optional_spaces_to_word_characters(u'created') +
ur').*(AAS\s*)?\sLATEX',
ur'AAS\s+?LATEX\s+?' +
_create_regex_pattern_add_optional_spaces_to_word_characters(
u'macros') + u'v',
ur'^\s*' + _create_regex_pattern_add_optional_spaces_to_word_characters(
u'This paper has been produced using'),
ur'^\s*' +
_create_regex_pattern_add_optional_spaces_to_word_characters(u'This article was processed by the author using Springer-Verlag') +
u' LATEX']
for p in patterns:
compiled_patterns.append(re.compile(p, re.I | re.UNICODE))
return compiled_patterns | [
"def",
"get_post_reference_section_keyword_patterns",
"(",
")",
":",
"compiled_patterns",
"=",
"[",
"]",
"patterns",
"=",
"[",
"u'('",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'prepared'",
")",
"+",
"ur'|'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'created'",
")",
"+",
"ur').*(AAS\\s*)?\\sLATEX'",
",",
"ur'AAS\\s+?LATEX\\s+?'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'macros'",
")",
"+",
"u'v'",
",",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'This paper has been produced using'",
")",
",",
"ur'^\\s*'",
"+",
"_create_regex_pattern_add_optional_spaces_to_word_characters",
"(",
"u'This article was processed by the author using Springer-Verlag'",
")",
"+",
"u' LATEX'",
"]",
"for",
"p",
"in",
"patterns",
":",
"compiled_patterns",
".",
"append",
"(",
"re",
".",
"compile",
"(",
"p",
",",
"re",
".",
"I",
"|",
"re",
".",
"UNICODE",
")",
")",
"return",
"compiled_patterns"
] | Return a list of compiled regex patterns used to search for various
keywords that can often be found after, and therefore suggest the end of,
a reference section in a full-text document.
@return: (list) of compiled regex patterns. | [
"Return",
"a",
"list",
"of",
"compiled",
"regex",
"patterns",
"used",
"to",
"search",
"for",
"various",
"keywords",
"that",
"can",
"often",
"be",
"found",
"after",
"and",
"therefore",
"suggest",
"the",
"end",
"of",
"a",
"reference",
"section",
"in",
"a",
"full",
"-",
"text",
"document",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L874-L894 | train | 236,610 |
inspirehep/refextract | refextract/references/regexs.py | regex_match_list | def regex_match_list(line, patterns):
"""Given a list of COMPILED regex patters, perform the "re.match" operation
on the line for every pattern.
Break from searching at the first match, returning the match object.
In the case that no patterns match, the None type will be returned.
@param line: (unicode string) to be searched in.
@param patterns: (list) of compiled regex patterns to search "line"
with.
@return: (None or an re.match object), depending upon whether one of
the patterns matched within line or not.
"""
m = None
for ptn in patterns:
m = ptn.match(line)
if m is not None:
break
return m | python | def regex_match_list(line, patterns):
"""Given a list of COMPILED regex patters, perform the "re.match" operation
on the line for every pattern.
Break from searching at the first match, returning the match object.
In the case that no patterns match, the None type will be returned.
@param line: (unicode string) to be searched in.
@param patterns: (list) of compiled regex patterns to search "line"
with.
@return: (None or an re.match object), depending upon whether one of
the patterns matched within line or not.
"""
m = None
for ptn in patterns:
m = ptn.match(line)
if m is not None:
break
return m | [
"def",
"regex_match_list",
"(",
"line",
",",
"patterns",
")",
":",
"m",
"=",
"None",
"for",
"ptn",
"in",
"patterns",
":",
"m",
"=",
"ptn",
".",
"match",
"(",
"line",
")",
"if",
"m",
"is",
"not",
"None",
":",
"break",
"return",
"m"
] | Given a list of COMPILED regex patters, perform the "re.match" operation
on the line for every pattern.
Break from searching at the first match, returning the match object.
In the case that no patterns match, the None type will be returned.
@param line: (unicode string) to be searched in.
@param patterns: (list) of compiled regex patterns to search "line"
with.
@return: (None or an re.match object), depending upon whether one of
the patterns matched within line or not. | [
"Given",
"a",
"list",
"of",
"COMPILED",
"regex",
"patters",
"perform",
"the",
"re",
".",
"match",
"operation",
"on",
"the",
"line",
"for",
"every",
"pattern",
".",
"Break",
"from",
"searching",
"at",
"the",
"first",
"match",
"returning",
"the",
"match",
"object",
".",
"In",
"the",
"case",
"that",
"no",
"patterns",
"match",
"the",
"None",
"type",
"will",
"be",
"returned",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L897-L913 | train | 236,611 |
inspirehep/refextract | refextract/documents/text.py | get_url_repair_patterns | def get_url_repair_patterns():
"""Initialise and return a list of precompiled regexp patterns that
are used to try to re-assemble URLs that have been broken during
a document's conversion to plain-text.
@return: (list) of compiled re regexp patterns used for finding
various broken URLs.
"""
file_types_list = [
ur'h\s*t\s*m', # htm
ur'h\s*t\s*m\s*l', # html
ur't\s*x\s*t' # txt
ur'p\s*h\s*p' # php
ur'a\s*s\s*p\s*' # asp
ur'j\s*s\s*p', # jsp
ur'p\s*y', # py (python)
ur'p\s*l', # pl (perl)
ur'x\s*m\s*l', # xml
ur'j\s*p\s*g', # jpg
ur'g\s*i\s*f' # gif
ur'm\s*o\s*v' # mov
ur's\s*w\s*f' # swf
ur'p\s*d\s*f' # pdf
ur'p\s*s' # ps
ur'd\s*o\s*c', # doc
ur't\s*e\s*x', # tex
ur's\s*h\s*t\s*m\s*l', # shtml
]
pattern_list = [
ur'(h\s*t\s*t\s*p\s*\:\s*\/\s*\/)',
ur'(f\s*t\s*p\s*\:\s*\/\s*\/\s*)',
ur'((http|ftp):\/\/\s*[\w\d])',
ur'((http|ftp):\/\/([\w\d\s\._\-])+?\s*\/)',
ur'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\s\.\-])+?\/)+)',
ur'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\s\.\-])+?\/)*([\w\d\_\s\-]+\.\s?[\w\d]+))',
]
pattern_list = [re.compile(p, re.I | re.UNICODE) for p in pattern_list]
# some possible endings for URLs:
p = ur'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\.\-])+?\/)*([\w\d\_\-]+\.%s))'
for extension in file_types_list:
p_url = re.compile(p % extension, re.I | re.UNICODE)
pattern_list.append(p_url)
# if url last thing in line, and only 10 letters max, concat them
p_url = re.compile(
r'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\.\-])+?\/)*\s*?([\w\d\_\.\-]\s?){1,10}\s*)$',
re.I | re.UNICODE)
pattern_list.append(p_url)
return pattern_list | python | def get_url_repair_patterns():
"""Initialise and return a list of precompiled regexp patterns that
are used to try to re-assemble URLs that have been broken during
a document's conversion to plain-text.
@return: (list) of compiled re regexp patterns used for finding
various broken URLs.
"""
file_types_list = [
ur'h\s*t\s*m', # htm
ur'h\s*t\s*m\s*l', # html
ur't\s*x\s*t' # txt
ur'p\s*h\s*p' # php
ur'a\s*s\s*p\s*' # asp
ur'j\s*s\s*p', # jsp
ur'p\s*y', # py (python)
ur'p\s*l', # pl (perl)
ur'x\s*m\s*l', # xml
ur'j\s*p\s*g', # jpg
ur'g\s*i\s*f' # gif
ur'm\s*o\s*v' # mov
ur's\s*w\s*f' # swf
ur'p\s*d\s*f' # pdf
ur'p\s*s' # ps
ur'd\s*o\s*c', # doc
ur't\s*e\s*x', # tex
ur's\s*h\s*t\s*m\s*l', # shtml
]
pattern_list = [
ur'(h\s*t\s*t\s*p\s*\:\s*\/\s*\/)',
ur'(f\s*t\s*p\s*\:\s*\/\s*\/\s*)',
ur'((http|ftp):\/\/\s*[\w\d])',
ur'((http|ftp):\/\/([\w\d\s\._\-])+?\s*\/)',
ur'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\s\.\-])+?\/)+)',
ur'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\s\.\-])+?\/)*([\w\d\_\s\-]+\.\s?[\w\d]+))',
]
pattern_list = [re.compile(p, re.I | re.UNICODE) for p in pattern_list]
# some possible endings for URLs:
p = ur'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\.\-])+?\/)*([\w\d\_\-]+\.%s))'
for extension in file_types_list:
p_url = re.compile(p % extension, re.I | re.UNICODE)
pattern_list.append(p_url)
# if url last thing in line, and only 10 letters max, concat them
p_url = re.compile(
r'((http|ftp):\/\/([\w\d\_\.\-])+\/(([\w\d\_\.\-])+?\/)*\s*?([\w\d\_\.\-]\s?){1,10}\s*)$',
re.I | re.UNICODE)
pattern_list.append(p_url)
return pattern_list | [
"def",
"get_url_repair_patterns",
"(",
")",
":",
"file_types_list",
"=",
"[",
"ur'h\\s*t\\s*m'",
",",
"# htm",
"ur'h\\s*t\\s*m\\s*l'",
",",
"# html",
"ur't\\s*x\\s*t'",
"# txt",
"ur'p\\s*h\\s*p'",
"# php",
"ur'a\\s*s\\s*p\\s*'",
"# asp",
"ur'j\\s*s\\s*p'",
",",
"# jsp",
"ur'p\\s*y'",
",",
"# py (python)",
"ur'p\\s*l'",
",",
"# pl (perl)",
"ur'x\\s*m\\s*l'",
",",
"# xml",
"ur'j\\s*p\\s*g'",
",",
"# jpg",
"ur'g\\s*i\\s*f'",
"# gif",
"ur'm\\s*o\\s*v'",
"# mov",
"ur's\\s*w\\s*f'",
"# swf",
"ur'p\\s*d\\s*f'",
"# pdf",
"ur'p\\s*s'",
"# ps",
"ur'd\\s*o\\s*c'",
",",
"# doc",
"ur't\\s*e\\s*x'",
",",
"# tex",
"ur's\\s*h\\s*t\\s*m\\s*l'",
",",
"# shtml",
"]",
"pattern_list",
"=",
"[",
"ur'(h\\s*t\\s*t\\s*p\\s*\\:\\s*\\/\\s*\\/)'",
",",
"ur'(f\\s*t\\s*p\\s*\\:\\s*\\/\\s*\\/\\s*)'",
",",
"ur'((http|ftp):\\/\\/\\s*[\\w\\d])'",
",",
"ur'((http|ftp):\\/\\/([\\w\\d\\s\\._\\-])+?\\s*\\/)'",
",",
"ur'((http|ftp):\\/\\/([\\w\\d\\_\\.\\-])+\\/(([\\w\\d\\_\\s\\.\\-])+?\\/)+)'",
",",
"ur'((http|ftp):\\/\\/([\\w\\d\\_\\.\\-])+\\/(([\\w\\d\\_\\s\\.\\-])+?\\/)*([\\w\\d\\_\\s\\-]+\\.\\s?[\\w\\d]+))'",
",",
"]",
"pattern_list",
"=",
"[",
"re",
".",
"compile",
"(",
"p",
",",
"re",
".",
"I",
"|",
"re",
".",
"UNICODE",
")",
"for",
"p",
"in",
"pattern_list",
"]",
"# some possible endings for URLs:",
"p",
"=",
"ur'((http|ftp):\\/\\/([\\w\\d\\_\\.\\-])+\\/(([\\w\\d\\_\\.\\-])+?\\/)*([\\w\\d\\_\\-]+\\.%s))'",
"for",
"extension",
"in",
"file_types_list",
":",
"p_url",
"=",
"re",
".",
"compile",
"(",
"p",
"%",
"extension",
",",
"re",
".",
"I",
"|",
"re",
".",
"UNICODE",
")",
"pattern_list",
".",
"append",
"(",
"p_url",
")",
"# if url last thing in line, and only 10 letters max, concat them",
"p_url",
"=",
"re",
".",
"compile",
"(",
"r'((http|ftp):\\/\\/([\\w\\d\\_\\.\\-])+\\/(([\\w\\d\\_\\.\\-])+?\\/)*\\s*?([\\w\\d\\_\\.\\-]\\s?){1,10}\\s*)$'",
",",
"re",
".",
"I",
"|",
"re",
".",
"UNICODE",
")",
"pattern_list",
".",
"append",
"(",
"p_url",
")",
"return",
"pattern_list"
] | Initialise and return a list of precompiled regexp patterns that
are used to try to re-assemble URLs that have been broken during
a document's conversion to plain-text.
@return: (list) of compiled re regexp patterns used for finding
various broken URLs. | [
"Initialise",
"and",
"return",
"a",
"list",
"of",
"precompiled",
"regexp",
"patterns",
"that",
"are",
"used",
"to",
"try",
"to",
"re",
"-",
"assemble",
"URLs",
"that",
"have",
"been",
"broken",
"during",
"a",
"document",
"s",
"conversion",
"to",
"plain",
"-",
"text",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L45-L95 | train | 236,612 |
inspirehep/refextract | refextract/documents/text.py | join_lines | def join_lines(line1, line2):
"""Join 2 lines of text
>>> join_lines('abc', 'de')
'abcde'
>>> join_lines('a-', 'b')
'ab'
"""
if line1 == u"":
pass
elif line1[-1] == u'-':
# hyphenated word at the end of the
# line - don't add in a space and remove hyphen
line1 = line1[:-1]
elif line1[-1] != u' ':
# no space at the end of this
# line, add in a space
line1 = line1 + u' '
return line1 + line2 | python | def join_lines(line1, line2):
"""Join 2 lines of text
>>> join_lines('abc', 'de')
'abcde'
>>> join_lines('a-', 'b')
'ab'
"""
if line1 == u"":
pass
elif line1[-1] == u'-':
# hyphenated word at the end of the
# line - don't add in a space and remove hyphen
line1 = line1[:-1]
elif line1[-1] != u' ':
# no space at the end of this
# line, add in a space
line1 = line1 + u' '
return line1 + line2 | [
"def",
"join_lines",
"(",
"line1",
",",
"line2",
")",
":",
"if",
"line1",
"==",
"u\"\"",
":",
"pass",
"elif",
"line1",
"[",
"-",
"1",
"]",
"==",
"u'-'",
":",
"# hyphenated word at the end of the",
"# line - don't add in a space and remove hyphen",
"line1",
"=",
"line1",
"[",
":",
"-",
"1",
"]",
"elif",
"line1",
"[",
"-",
"1",
"]",
"!=",
"u' '",
":",
"# no space at the end of this",
"# line, add in a space",
"line1",
"=",
"line1",
"+",
"u' '",
"return",
"line1",
"+",
"line2"
] | Join 2 lines of text
>>> join_lines('abc', 'de')
'abcde'
>>> join_lines('a-', 'b')
'ab' | [
"Join",
"2",
"lines",
"of",
"text"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L102-L120 | train | 236,613 |
inspirehep/refextract | refextract/documents/text.py | repair_broken_urls | def repair_broken_urls(line):
"""Attempt to repair broken URLs in a line of text.
E.g.: remove spaces from the middle of a URL; something like that.
@param line: (string) the line in which to check for broken URLs.
@return: (string) the line after any broken URLs have been repaired.
"""
def _chop_spaces_in_url_match(m):
"""Suppresses spaces in a matched URL."""
return m.group(1).replace(" ", "")
for ptn in re_list_url_repair_patterns:
line = ptn.sub(_chop_spaces_in_url_match, line)
return line | python | def repair_broken_urls(line):
"""Attempt to repair broken URLs in a line of text.
E.g.: remove spaces from the middle of a URL; something like that.
@param line: (string) the line in which to check for broken URLs.
@return: (string) the line after any broken URLs have been repaired.
"""
def _chop_spaces_in_url_match(m):
"""Suppresses spaces in a matched URL."""
return m.group(1).replace(" ", "")
for ptn in re_list_url_repair_patterns:
line = ptn.sub(_chop_spaces_in_url_match, line)
return line | [
"def",
"repair_broken_urls",
"(",
"line",
")",
":",
"def",
"_chop_spaces_in_url_match",
"(",
"m",
")",
":",
"\"\"\"Suppresses spaces in a matched URL.\"\"\"",
"return",
"m",
".",
"group",
"(",
"1",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
"for",
"ptn",
"in",
"re_list_url_repair_patterns",
":",
"line",
"=",
"ptn",
".",
"sub",
"(",
"_chop_spaces_in_url_match",
",",
"line",
")",
"return",
"line"
] | Attempt to repair broken URLs in a line of text.
E.g.: remove spaces from the middle of a URL; something like that.
@param line: (string) the line in which to check for broken URLs.
@return: (string) the line after any broken URLs have been repaired. | [
"Attempt",
"to",
"repair",
"broken",
"URLs",
"in",
"a",
"line",
"of",
"text",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L123-L136 | train | 236,614 |
inspirehep/refextract | refextract/documents/text.py | remove_and_record_multiple_spaces_in_line | def remove_and_record_multiple_spaces_in_line(line):
"""For a given string, locate all ocurrences of multiple spaces
together in the line, record the number of spaces found at each
position, and replace them with a single space.
@param line: (string) the text line to be processed for multiple
spaces.
@return: (tuple) countaining a dictionary and a string. The
dictionary contains information about the number of spaces removed
at given positions in the line. For example, if 3 spaces were
removed from the line at index '22', the dictionary would be set
as follows: { 22 : 3 }
The string that is also returned in this tuple is the line after
multiple-space ocurrences have replaced with single spaces.
"""
removed_spaces = {}
# get a collection of match objects for all instances of
# multiple-spaces found in the line:
multispace_matches = re_group_captured_multiple_space.finditer(line)
# record the number of spaces found at each match position:
for multispace in multispace_matches:
removed_spaces[multispace.start()] = \
(multispace.end() - multispace.start() - 1)
# now remove the multiple-spaces from the line, replacing with a
# single space at each position:
line = re_group_captured_multiple_space.sub(u' ', line)
return (removed_spaces, line) | python | def remove_and_record_multiple_spaces_in_line(line):
"""For a given string, locate all ocurrences of multiple spaces
together in the line, record the number of spaces found at each
position, and replace them with a single space.
@param line: (string) the text line to be processed for multiple
spaces.
@return: (tuple) countaining a dictionary and a string. The
dictionary contains information about the number of spaces removed
at given positions in the line. For example, if 3 spaces were
removed from the line at index '22', the dictionary would be set
as follows: { 22 : 3 }
The string that is also returned in this tuple is the line after
multiple-space ocurrences have replaced with single spaces.
"""
removed_spaces = {}
# get a collection of match objects for all instances of
# multiple-spaces found in the line:
multispace_matches = re_group_captured_multiple_space.finditer(line)
# record the number of spaces found at each match position:
for multispace in multispace_matches:
removed_spaces[multispace.start()] = \
(multispace.end() - multispace.start() - 1)
# now remove the multiple-spaces from the line, replacing with a
# single space at each position:
line = re_group_captured_multiple_space.sub(u' ', line)
return (removed_spaces, line) | [
"def",
"remove_and_record_multiple_spaces_in_line",
"(",
"line",
")",
":",
"removed_spaces",
"=",
"{",
"}",
"# get a collection of match objects for all instances of",
"# multiple-spaces found in the line:",
"multispace_matches",
"=",
"re_group_captured_multiple_space",
".",
"finditer",
"(",
"line",
")",
"# record the number of spaces found at each match position:",
"for",
"multispace",
"in",
"multispace_matches",
":",
"removed_spaces",
"[",
"multispace",
".",
"start",
"(",
")",
"]",
"=",
"(",
"multispace",
".",
"end",
"(",
")",
"-",
"multispace",
".",
"start",
"(",
")",
"-",
"1",
")",
"# now remove the multiple-spaces from the line, replacing with a",
"# single space at each position:",
"line",
"=",
"re_group_captured_multiple_space",
".",
"sub",
"(",
"u' '",
",",
"line",
")",
"return",
"(",
"removed_spaces",
",",
"line",
")"
] | For a given string, locate all ocurrences of multiple spaces
together in the line, record the number of spaces found at each
position, and replace them with a single space.
@param line: (string) the text line to be processed for multiple
spaces.
@return: (tuple) countaining a dictionary and a string. The
dictionary contains information about the number of spaces removed
at given positions in the line. For example, if 3 spaces were
removed from the line at index '22', the dictionary would be set
as follows: { 22 : 3 }
The string that is also returned in this tuple is the line after
multiple-space ocurrences have replaced with single spaces. | [
"For",
"a",
"given",
"string",
"locate",
"all",
"ocurrences",
"of",
"multiple",
"spaces",
"together",
"in",
"the",
"line",
"record",
"the",
"number",
"of",
"spaces",
"found",
"at",
"each",
"position",
"and",
"replace",
"them",
"with",
"a",
"single",
"space",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L139-L164 | train | 236,615 |
inspirehep/refextract | refextract/documents/text.py | remove_page_boundary_lines | def remove_page_boundary_lines(docbody):
"""Try to locate page breaks, headers and footers within a document body,
and remove the array cells at which they are found.
@param docbody: (list) of strings, each string being a line in the
document's body.
@return: (list) of strings. The document body, hopefully with page-
breaks, headers and footers removed. Each string in the list once more
represents a line in the document.
"""
number_head_lines = number_foot_lines = 0
# Make sure document not just full of whitespace:
if not document_contains_text(docbody):
# document contains only whitespace - cannot safely
# strip headers/footers
return docbody
# Get list of index posns of pagebreaks in document:
page_break_posns = get_page_break_positions(docbody)
# Get num lines making up each header if poss:
number_head_lines = get_number_header_lines(docbody, page_break_posns)
# Get num lines making up each footer if poss:
number_foot_lines = get_number_footer_lines(docbody, page_break_posns)
# Remove pagebreaks,headers,footers:
docbody = strip_headers_footers_pagebreaks(docbody,
page_break_posns,
number_head_lines,
number_foot_lines)
return docbody | python | def remove_page_boundary_lines(docbody):
"""Try to locate page breaks, headers and footers within a document body,
and remove the array cells at which they are found.
@param docbody: (list) of strings, each string being a line in the
document's body.
@return: (list) of strings. The document body, hopefully with page-
breaks, headers and footers removed. Each string in the list once more
represents a line in the document.
"""
number_head_lines = number_foot_lines = 0
# Make sure document not just full of whitespace:
if not document_contains_text(docbody):
# document contains only whitespace - cannot safely
# strip headers/footers
return docbody
# Get list of index posns of pagebreaks in document:
page_break_posns = get_page_break_positions(docbody)
# Get num lines making up each header if poss:
number_head_lines = get_number_header_lines(docbody, page_break_posns)
# Get num lines making up each footer if poss:
number_foot_lines = get_number_footer_lines(docbody, page_break_posns)
# Remove pagebreaks,headers,footers:
docbody = strip_headers_footers_pagebreaks(docbody,
page_break_posns,
number_head_lines,
number_foot_lines)
return docbody | [
"def",
"remove_page_boundary_lines",
"(",
"docbody",
")",
":",
"number_head_lines",
"=",
"number_foot_lines",
"=",
"0",
"# Make sure document not just full of whitespace:",
"if",
"not",
"document_contains_text",
"(",
"docbody",
")",
":",
"# document contains only whitespace - cannot safely",
"# strip headers/footers",
"return",
"docbody",
"# Get list of index posns of pagebreaks in document:",
"page_break_posns",
"=",
"get_page_break_positions",
"(",
"docbody",
")",
"# Get num lines making up each header if poss:",
"number_head_lines",
"=",
"get_number_header_lines",
"(",
"docbody",
",",
"page_break_posns",
")",
"# Get num lines making up each footer if poss:",
"number_foot_lines",
"=",
"get_number_footer_lines",
"(",
"docbody",
",",
"page_break_posns",
")",
"# Remove pagebreaks,headers,footers:",
"docbody",
"=",
"strip_headers_footers_pagebreaks",
"(",
"docbody",
",",
"page_break_posns",
",",
"number_head_lines",
",",
"number_foot_lines",
")",
"return",
"docbody"
] | Try to locate page breaks, headers and footers within a document body,
and remove the array cells at which they are found.
@param docbody: (list) of strings, each string being a line in the
document's body.
@return: (list) of strings. The document body, hopefully with page-
breaks, headers and footers removed. Each string in the list once more
represents a line in the document. | [
"Try",
"to",
"locate",
"page",
"breaks",
"headers",
"and",
"footers",
"within",
"a",
"document",
"body",
"and",
"remove",
"the",
"array",
"cells",
"at",
"which",
"they",
"are",
"found",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L186-L217 | train | 236,616 |
inspirehep/refextract | refextract/documents/text.py | get_page_break_positions | def get_page_break_positions(docbody):
"""Locate page breaks in the list of document lines and create a list
positions in the document body list.
@param docbody: (list) of strings - each string is a line in the
document.
@return: (list) of integer positions, whereby each integer represents the
position (in the document body) of a page-break.
"""
page_break_posns = []
p_break = re.compile(ur'^\s*\f\s*$', re.UNICODE)
num_document_lines = len(docbody)
for i in xrange(num_document_lines):
if p_break.match(docbody[i]) is not None:
page_break_posns.append(i)
return page_break_posns | python | def get_page_break_positions(docbody):
"""Locate page breaks in the list of document lines and create a list
positions in the document body list.
@param docbody: (list) of strings - each string is a line in the
document.
@return: (list) of integer positions, whereby each integer represents the
position (in the document body) of a page-break.
"""
page_break_posns = []
p_break = re.compile(ur'^\s*\f\s*$', re.UNICODE)
num_document_lines = len(docbody)
for i in xrange(num_document_lines):
if p_break.match(docbody[i]) is not None:
page_break_posns.append(i)
return page_break_posns | [
"def",
"get_page_break_positions",
"(",
"docbody",
")",
":",
"page_break_posns",
"=",
"[",
"]",
"p_break",
"=",
"re",
".",
"compile",
"(",
"ur'^\\s*\\f\\s*$'",
",",
"re",
".",
"UNICODE",
")",
"num_document_lines",
"=",
"len",
"(",
"docbody",
")",
"for",
"i",
"in",
"xrange",
"(",
"num_document_lines",
")",
":",
"if",
"p_break",
".",
"match",
"(",
"docbody",
"[",
"i",
"]",
")",
"is",
"not",
"None",
":",
"page_break_posns",
".",
"append",
"(",
"i",
")",
"return",
"page_break_posns"
] | Locate page breaks in the list of document lines and create a list
positions in the document body list.
@param docbody: (list) of strings - each string is a line in the
document.
@return: (list) of integer positions, whereby each integer represents the
position (in the document body) of a page-break. | [
"Locate",
"page",
"breaks",
"in",
"the",
"list",
"of",
"document",
"lines",
"and",
"create",
"a",
"list",
"positions",
"in",
"the",
"document",
"body",
"list",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L237-L251 | train | 236,617 |
inspirehep/refextract | refextract/documents/text.py | get_number_header_lines | def get_number_header_lines(docbody, page_break_posns):
"""Try to guess the number of header lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of header lines.
@param docbody: (list) of strings - each string being a line in the
document
@param page_break_posns: (list) of integers - each integer is the
position of a page break in the document.
@return: (int) the number of lines that make up the header of each page.
"""
remaining_breaks = len(page_break_posns) - 1
num_header_lines = empty_line = 0
# pattern to search for a word in a line:
p_wordSearch = re.compile(ur'([A-Za-z0-9-]+)', re.UNICODE)
if remaining_breaks > 2:
if remaining_breaks > 3:
# Only check odd page headers
next_head = 2
else:
# Check headers on each page
next_head = 1
keep_checking = 1
while keep_checking:
cur_break = 1
if docbody[(page_break_posns[cur_break] +
num_header_lines + 1)].isspace():
# this is a blank line
empty_line = 1
if (page_break_posns[cur_break] + num_header_lines + 1) \
== (page_break_posns[(cur_break + 1)]):
# Have reached next page-break: document has no
# body - only head/footers!
keep_checking = 0
grps_headLineWords = \
p_wordSearch.findall(docbody[(page_break_posns[cur_break] +
num_header_lines + 1)])
cur_break = cur_break + next_head
while (cur_break < remaining_breaks) and keep_checking:
lineno = page_break_posns[cur_break] + num_header_lines + 1
if lineno >= len(docbody):
keep_checking = 0
break
grps_thisLineWords = \
p_wordSearch.findall(docbody[lineno])
if empty_line:
if len(grps_thisLineWords) != 0:
# This line should be empty, but isn't
keep_checking = 0
else:
if (len(grps_thisLineWords) == 0) or \
(len(grps_headLineWords) != len(grps_thisLineWords)):
# Not same num 'words' as equivilent line
# in 1st header:
keep_checking = 0
else:
keep_checking = \
check_boundary_lines_similar(grps_headLineWords,
grps_thisLineWords)
# Update cur_break for nxt line to check
cur_break = cur_break + next_head
if keep_checking:
# Line is a header line: check next
num_header_lines = num_header_lines + 1
empty_line = 0
return num_header_lines | python | def get_number_header_lines(docbody, page_break_posns):
"""Try to guess the number of header lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of header lines.
@param docbody: (list) of strings - each string being a line in the
document
@param page_break_posns: (list) of integers - each integer is the
position of a page break in the document.
@return: (int) the number of lines that make up the header of each page.
"""
remaining_breaks = len(page_break_posns) - 1
num_header_lines = empty_line = 0
# pattern to search for a word in a line:
p_wordSearch = re.compile(ur'([A-Za-z0-9-]+)', re.UNICODE)
if remaining_breaks > 2:
if remaining_breaks > 3:
# Only check odd page headers
next_head = 2
else:
# Check headers on each page
next_head = 1
keep_checking = 1
while keep_checking:
cur_break = 1
if docbody[(page_break_posns[cur_break] +
num_header_lines + 1)].isspace():
# this is a blank line
empty_line = 1
if (page_break_posns[cur_break] + num_header_lines + 1) \
== (page_break_posns[(cur_break + 1)]):
# Have reached next page-break: document has no
# body - only head/footers!
keep_checking = 0
grps_headLineWords = \
p_wordSearch.findall(docbody[(page_break_posns[cur_break] +
num_header_lines + 1)])
cur_break = cur_break + next_head
while (cur_break < remaining_breaks) and keep_checking:
lineno = page_break_posns[cur_break] + num_header_lines + 1
if lineno >= len(docbody):
keep_checking = 0
break
grps_thisLineWords = \
p_wordSearch.findall(docbody[lineno])
if empty_line:
if len(grps_thisLineWords) != 0:
# This line should be empty, but isn't
keep_checking = 0
else:
if (len(grps_thisLineWords) == 0) or \
(len(grps_headLineWords) != len(grps_thisLineWords)):
# Not same num 'words' as equivilent line
# in 1st header:
keep_checking = 0
else:
keep_checking = \
check_boundary_lines_similar(grps_headLineWords,
grps_thisLineWords)
# Update cur_break for nxt line to check
cur_break = cur_break + next_head
if keep_checking:
# Line is a header line: check next
num_header_lines = num_header_lines + 1
empty_line = 0
return num_header_lines | [
"def",
"get_number_header_lines",
"(",
"docbody",
",",
"page_break_posns",
")",
":",
"remaining_breaks",
"=",
"len",
"(",
"page_break_posns",
")",
"-",
"1",
"num_header_lines",
"=",
"empty_line",
"=",
"0",
"# pattern to search for a word in a line:",
"p_wordSearch",
"=",
"re",
".",
"compile",
"(",
"ur'([A-Za-z0-9-]+)'",
",",
"re",
".",
"UNICODE",
")",
"if",
"remaining_breaks",
">",
"2",
":",
"if",
"remaining_breaks",
">",
"3",
":",
"# Only check odd page headers",
"next_head",
"=",
"2",
"else",
":",
"# Check headers on each page",
"next_head",
"=",
"1",
"keep_checking",
"=",
"1",
"while",
"keep_checking",
":",
"cur_break",
"=",
"1",
"if",
"docbody",
"[",
"(",
"page_break_posns",
"[",
"cur_break",
"]",
"+",
"num_header_lines",
"+",
"1",
")",
"]",
".",
"isspace",
"(",
")",
":",
"# this is a blank line",
"empty_line",
"=",
"1",
"if",
"(",
"page_break_posns",
"[",
"cur_break",
"]",
"+",
"num_header_lines",
"+",
"1",
")",
"==",
"(",
"page_break_posns",
"[",
"(",
"cur_break",
"+",
"1",
")",
"]",
")",
":",
"# Have reached next page-break: document has no",
"# body - only head/footers!",
"keep_checking",
"=",
"0",
"grps_headLineWords",
"=",
"p_wordSearch",
".",
"findall",
"(",
"docbody",
"[",
"(",
"page_break_posns",
"[",
"cur_break",
"]",
"+",
"num_header_lines",
"+",
"1",
")",
"]",
")",
"cur_break",
"=",
"cur_break",
"+",
"next_head",
"while",
"(",
"cur_break",
"<",
"remaining_breaks",
")",
"and",
"keep_checking",
":",
"lineno",
"=",
"page_break_posns",
"[",
"cur_break",
"]",
"+",
"num_header_lines",
"+",
"1",
"if",
"lineno",
">=",
"len",
"(",
"docbody",
")",
":",
"keep_checking",
"=",
"0",
"break",
"grps_thisLineWords",
"=",
"p_wordSearch",
".",
"findall",
"(",
"docbody",
"[",
"lineno",
"]",
")",
"if",
"empty_line",
":",
"if",
"len",
"(",
"grps_thisLineWords",
")",
"!=",
"0",
":",
"# This line should be empty, but isn't",
"keep_checking",
"=",
"0",
"else",
":",
"if",
"(",
"len",
"(",
"grps_thisLineWords",
")",
"==",
"0",
")",
"or",
"(",
"len",
"(",
"grps_headLineWords",
")",
"!=",
"len",
"(",
"grps_thisLineWords",
")",
")",
":",
"# Not same num 'words' as equivilent line",
"# in 1st header:",
"keep_checking",
"=",
"0",
"else",
":",
"keep_checking",
"=",
"check_boundary_lines_similar",
"(",
"grps_headLineWords",
",",
"grps_thisLineWords",
")",
"# Update cur_break for nxt line to check",
"cur_break",
"=",
"cur_break",
"+",
"next_head",
"if",
"keep_checking",
":",
"# Line is a header line: check next",
"num_header_lines",
"=",
"num_header_lines",
"+",
"1",
"empty_line",
"=",
"0",
"return",
"num_header_lines"
] | Try to guess the number of header lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of header lines.
@param docbody: (list) of strings - each string being a line in the
document
@param page_break_posns: (list) of integers - each integer is the
position of a page break in the document.
@return: (int) the number of lines that make up the header of each page. | [
"Try",
"to",
"guess",
"the",
"number",
"of",
"header",
"lines",
"each",
"page",
"of",
"a",
"document",
"has",
".",
"The",
"positions",
"of",
"the",
"page",
"breaks",
"in",
"the",
"document",
"are",
"used",
"to",
"try",
"to",
"guess",
"the",
"number",
"of",
"header",
"lines",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L254-L320 | train | 236,618 |
inspirehep/refextract | refextract/documents/text.py | get_number_footer_lines | def get_number_footer_lines(docbody, page_break_posns):
"""Try to guess the number of footer lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of footer lines.
@param docbody: (list) of strings - each string being a line in the
document
@param page_break_posns: (list) of integers - each integer is the
position of a page break in the document.
@return: (int) the number of lines that make up the footer of each page.
"""
num_breaks = len(page_break_posns)
num_footer_lines = 0
empty_line = 0
keep_checking = 1
p_wordSearch = re.compile(unicode(r'([A-Za-z0-9-]+)'), re.UNICODE)
if num_breaks > 2:
while keep_checking:
cur_break = 1
if page_break_posns[cur_break] - num_footer_lines - 1 < 0 or \
page_break_posns[cur_break] - num_footer_lines - 1 > \
len(docbody) - 1:
# Be sure that the docbody list boundary wasn't overstepped:
break
if docbody[(page_break_posns[cur_break] -
num_footer_lines - 1)].isspace():
empty_line = 1
grps_headLineWords = \
p_wordSearch.findall(docbody[(page_break_posns[cur_break] -
num_footer_lines - 1)])
cur_break = cur_break + 1
while (cur_break < num_breaks) and keep_checking:
grps_thisLineWords = \
p_wordSearch.findall(docbody[(page_break_posns[cur_break] -
num_footer_lines - 1)])
if empty_line:
if len(grps_thisLineWords) != 0:
# this line should be empty, but isn't
keep_checking = 0
else:
if (len(grps_thisLineWords) == 0) or \
(len(grps_headLineWords) != len(grps_thisLineWords)):
# Not same num 'words' as equivilent line
# in 1st footer:
keep_checking = 0
else:
keep_checking = \
check_boundary_lines_similar(grps_headLineWords,
grps_thisLineWords)
# Update cur_break for nxt line to check
cur_break = cur_break + 1
if keep_checking:
# Line is a footer line: check next
num_footer_lines = num_footer_lines + 1
empty_line = 0
return num_footer_lines | python | def get_number_footer_lines(docbody, page_break_posns):
"""Try to guess the number of footer lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of footer lines.
@param docbody: (list) of strings - each string being a line in the
document
@param page_break_posns: (list) of integers - each integer is the
position of a page break in the document.
@return: (int) the number of lines that make up the footer of each page.
"""
num_breaks = len(page_break_posns)
num_footer_lines = 0
empty_line = 0
keep_checking = 1
p_wordSearch = re.compile(unicode(r'([A-Za-z0-9-]+)'), re.UNICODE)
if num_breaks > 2:
while keep_checking:
cur_break = 1
if page_break_posns[cur_break] - num_footer_lines - 1 < 0 or \
page_break_posns[cur_break] - num_footer_lines - 1 > \
len(docbody) - 1:
# Be sure that the docbody list boundary wasn't overstepped:
break
if docbody[(page_break_posns[cur_break] -
num_footer_lines - 1)].isspace():
empty_line = 1
grps_headLineWords = \
p_wordSearch.findall(docbody[(page_break_posns[cur_break] -
num_footer_lines - 1)])
cur_break = cur_break + 1
while (cur_break < num_breaks) and keep_checking:
grps_thisLineWords = \
p_wordSearch.findall(docbody[(page_break_posns[cur_break] -
num_footer_lines - 1)])
if empty_line:
if len(grps_thisLineWords) != 0:
# this line should be empty, but isn't
keep_checking = 0
else:
if (len(grps_thisLineWords) == 0) or \
(len(grps_headLineWords) != len(grps_thisLineWords)):
# Not same num 'words' as equivilent line
# in 1st footer:
keep_checking = 0
else:
keep_checking = \
check_boundary_lines_similar(grps_headLineWords,
grps_thisLineWords)
# Update cur_break for nxt line to check
cur_break = cur_break + 1
if keep_checking:
# Line is a footer line: check next
num_footer_lines = num_footer_lines + 1
empty_line = 0
return num_footer_lines | [
"def",
"get_number_footer_lines",
"(",
"docbody",
",",
"page_break_posns",
")",
":",
"num_breaks",
"=",
"len",
"(",
"page_break_posns",
")",
"num_footer_lines",
"=",
"0",
"empty_line",
"=",
"0",
"keep_checking",
"=",
"1",
"p_wordSearch",
"=",
"re",
".",
"compile",
"(",
"unicode",
"(",
"r'([A-Za-z0-9-]+)'",
")",
",",
"re",
".",
"UNICODE",
")",
"if",
"num_breaks",
">",
"2",
":",
"while",
"keep_checking",
":",
"cur_break",
"=",
"1",
"if",
"page_break_posns",
"[",
"cur_break",
"]",
"-",
"num_footer_lines",
"-",
"1",
"<",
"0",
"or",
"page_break_posns",
"[",
"cur_break",
"]",
"-",
"num_footer_lines",
"-",
"1",
">",
"len",
"(",
"docbody",
")",
"-",
"1",
":",
"# Be sure that the docbody list boundary wasn't overstepped:",
"break",
"if",
"docbody",
"[",
"(",
"page_break_posns",
"[",
"cur_break",
"]",
"-",
"num_footer_lines",
"-",
"1",
")",
"]",
".",
"isspace",
"(",
")",
":",
"empty_line",
"=",
"1",
"grps_headLineWords",
"=",
"p_wordSearch",
".",
"findall",
"(",
"docbody",
"[",
"(",
"page_break_posns",
"[",
"cur_break",
"]",
"-",
"num_footer_lines",
"-",
"1",
")",
"]",
")",
"cur_break",
"=",
"cur_break",
"+",
"1",
"while",
"(",
"cur_break",
"<",
"num_breaks",
")",
"and",
"keep_checking",
":",
"grps_thisLineWords",
"=",
"p_wordSearch",
".",
"findall",
"(",
"docbody",
"[",
"(",
"page_break_posns",
"[",
"cur_break",
"]",
"-",
"num_footer_lines",
"-",
"1",
")",
"]",
")",
"if",
"empty_line",
":",
"if",
"len",
"(",
"grps_thisLineWords",
")",
"!=",
"0",
":",
"# this line should be empty, but isn't",
"keep_checking",
"=",
"0",
"else",
":",
"if",
"(",
"len",
"(",
"grps_thisLineWords",
")",
"==",
"0",
")",
"or",
"(",
"len",
"(",
"grps_headLineWords",
")",
"!=",
"len",
"(",
"grps_thisLineWords",
")",
")",
":",
"# Not same num 'words' as equivilent line",
"# in 1st footer:",
"keep_checking",
"=",
"0",
"else",
":",
"keep_checking",
"=",
"check_boundary_lines_similar",
"(",
"grps_headLineWords",
",",
"grps_thisLineWords",
")",
"# Update cur_break for nxt line to check",
"cur_break",
"=",
"cur_break",
"+",
"1",
"if",
"keep_checking",
":",
"# Line is a footer line: check next",
"num_footer_lines",
"=",
"num_footer_lines",
"+",
"1",
"empty_line",
"=",
"0",
"return",
"num_footer_lines"
] | Try to guess the number of footer lines each page of a document has.
The positions of the page breaks in the document are used to try to guess
the number of footer lines.
@param docbody: (list) of strings - each string being a line in the
document
@param page_break_posns: (list) of integers - each integer is the
position of a page break in the document.
@return: (int) the number of lines that make up the footer of each page. | [
"Try",
"to",
"guess",
"the",
"number",
"of",
"footer",
"lines",
"each",
"page",
"of",
"a",
"document",
"has",
".",
"The",
"positions",
"of",
"the",
"page",
"breaks",
"in",
"the",
"document",
"are",
"used",
"to",
"try",
"to",
"guess",
"the",
"number",
"of",
"footer",
"lines",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L323-L377 | train | 236,619 |
inspirehep/refextract | refextract/documents/text.py | strip_headers_footers_pagebreaks | def strip_headers_footers_pagebreaks(docbody,
page_break_posns,
num_head_lines,
num_foot_lines):
"""Remove page-break lines, header lines, and footer lines from the
document.
@param docbody: (list) of strings, whereby each string in the list is a
line in the document.
@param page_break_posns: (list) of integers, whereby each integer
represents the index in docbody at which a page-break is found.
@param num_head_lines: (int) the number of header lines each page in the
document has.
@param num_foot_lines: (int) the number of footer lines each page in the
document has.
@return: (list) of strings - the document body after the headers,
footers, and page-break lines have been stripped from the list.
"""
num_breaks = len(page_break_posns)
page_lens = []
for x in xrange(0, num_breaks):
if x < num_breaks - 1:
page_lens.append(page_break_posns[x + 1] - page_break_posns[x])
page_lens.sort()
if (len(page_lens) > 0) and \
(num_head_lines + num_foot_lines + 1 < page_lens[0]):
# Safe to chop hdrs & ftrs
page_break_posns.reverse()
first = 1
for i in xrange(0, len(page_break_posns)):
# Unless this is the last page break, chop headers
if not first:
for dummy in xrange(1, num_head_lines + 1):
docbody[page_break_posns[i] +
1:page_break_posns[i] + 2] = []
else:
first = 0
# Chop page break itself
docbody[page_break_posns[i]:page_break_posns[i] + 1] = []
# Chop footers (unless this is the first page break)
if i != len(page_break_posns) - 1:
for dummy in xrange(1, num_foot_lines + 1):
docbody[page_break_posns[i] -
num_foot_lines:page_break_posns[i] -
num_foot_lines + 1] = []
return docbody | python | def strip_headers_footers_pagebreaks(docbody,
page_break_posns,
num_head_lines,
num_foot_lines):
"""Remove page-break lines, header lines, and footer lines from the
document.
@param docbody: (list) of strings, whereby each string in the list is a
line in the document.
@param page_break_posns: (list) of integers, whereby each integer
represents the index in docbody at which a page-break is found.
@param num_head_lines: (int) the number of header lines each page in the
document has.
@param num_foot_lines: (int) the number of footer lines each page in the
document has.
@return: (list) of strings - the document body after the headers,
footers, and page-break lines have been stripped from the list.
"""
num_breaks = len(page_break_posns)
page_lens = []
for x in xrange(0, num_breaks):
if x < num_breaks - 1:
page_lens.append(page_break_posns[x + 1] - page_break_posns[x])
page_lens.sort()
if (len(page_lens) > 0) and \
(num_head_lines + num_foot_lines + 1 < page_lens[0]):
# Safe to chop hdrs & ftrs
page_break_posns.reverse()
first = 1
for i in xrange(0, len(page_break_posns)):
# Unless this is the last page break, chop headers
if not first:
for dummy in xrange(1, num_head_lines + 1):
docbody[page_break_posns[i] +
1:page_break_posns[i] + 2] = []
else:
first = 0
# Chop page break itself
docbody[page_break_posns[i]:page_break_posns[i] + 1] = []
# Chop footers (unless this is the first page break)
if i != len(page_break_posns) - 1:
for dummy in xrange(1, num_foot_lines + 1):
docbody[page_break_posns[i] -
num_foot_lines:page_break_posns[i] -
num_foot_lines + 1] = []
return docbody | [
"def",
"strip_headers_footers_pagebreaks",
"(",
"docbody",
",",
"page_break_posns",
",",
"num_head_lines",
",",
"num_foot_lines",
")",
":",
"num_breaks",
"=",
"len",
"(",
"page_break_posns",
")",
"page_lens",
"=",
"[",
"]",
"for",
"x",
"in",
"xrange",
"(",
"0",
",",
"num_breaks",
")",
":",
"if",
"x",
"<",
"num_breaks",
"-",
"1",
":",
"page_lens",
".",
"append",
"(",
"page_break_posns",
"[",
"x",
"+",
"1",
"]",
"-",
"page_break_posns",
"[",
"x",
"]",
")",
"page_lens",
".",
"sort",
"(",
")",
"if",
"(",
"len",
"(",
"page_lens",
")",
">",
"0",
")",
"and",
"(",
"num_head_lines",
"+",
"num_foot_lines",
"+",
"1",
"<",
"page_lens",
"[",
"0",
"]",
")",
":",
"# Safe to chop hdrs & ftrs",
"page_break_posns",
".",
"reverse",
"(",
")",
"first",
"=",
"1",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"page_break_posns",
")",
")",
":",
"# Unless this is the last page break, chop headers",
"if",
"not",
"first",
":",
"for",
"dummy",
"in",
"xrange",
"(",
"1",
",",
"num_head_lines",
"+",
"1",
")",
":",
"docbody",
"[",
"page_break_posns",
"[",
"i",
"]",
"+",
"1",
":",
"page_break_posns",
"[",
"i",
"]",
"+",
"2",
"]",
"=",
"[",
"]",
"else",
":",
"first",
"=",
"0",
"# Chop page break itself",
"docbody",
"[",
"page_break_posns",
"[",
"i",
"]",
":",
"page_break_posns",
"[",
"i",
"]",
"+",
"1",
"]",
"=",
"[",
"]",
"# Chop footers (unless this is the first page break)",
"if",
"i",
"!=",
"len",
"(",
"page_break_posns",
")",
"-",
"1",
":",
"for",
"dummy",
"in",
"xrange",
"(",
"1",
",",
"num_foot_lines",
"+",
"1",
")",
":",
"docbody",
"[",
"page_break_posns",
"[",
"i",
"]",
"-",
"num_foot_lines",
":",
"page_break_posns",
"[",
"i",
"]",
"-",
"num_foot_lines",
"+",
"1",
"]",
"=",
"[",
"]",
"return",
"docbody"
] | Remove page-break lines, header lines, and footer lines from the
document.
@param docbody: (list) of strings, whereby each string in the list is a
line in the document.
@param page_break_posns: (list) of integers, whereby each integer
represents the index in docbody at which a page-break is found.
@param num_head_lines: (int) the number of header lines each page in the
document has.
@param num_foot_lines: (int) the number of footer lines each page in the
document has.
@return: (list) of strings - the document body after the headers,
footers, and page-break lines have been stripped from the list. | [
"Remove",
"page",
"-",
"break",
"lines",
"header",
"lines",
"and",
"footer",
"lines",
"from",
"the",
"document",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L380-L424 | train | 236,620 |
inspirehep/refextract | refextract/documents/text.py | check_boundary_lines_similar | def check_boundary_lines_similar(l_1, l_2):
"""Compare two lists to see if their elements are roughly the same.
@param l_1: (list) of strings.
@param l_2: (list) of strings.
@return: (int) 1/0.
"""
num_matches = 0
if (type(l_1) != list) or (type(l_2) != list) or (len(l_1) != len(l_2)):
# these 'boundaries' are not similar
return 0
num_elements = len(l_1)
for i in xrange(0, num_elements):
if l_1[i].isdigit() and l_2[i].isdigit():
# both lines are integers
num_matches += 1
else:
l1_str = l_1[i].lower()
l2_str = l_2[i].lower()
if (l1_str[0] == l2_str[0]) and \
(l1_str[len(l1_str) - 1] == l2_str[len(l2_str) - 1]):
num_matches = num_matches + 1
if (len(l_1) == 0) or (float(num_matches) / float(len(l_1)) < 0.9):
return 0
else:
return 1 | python | def check_boundary_lines_similar(l_1, l_2):
"""Compare two lists to see if their elements are roughly the same.
@param l_1: (list) of strings.
@param l_2: (list) of strings.
@return: (int) 1/0.
"""
num_matches = 0
if (type(l_1) != list) or (type(l_2) != list) or (len(l_1) != len(l_2)):
# these 'boundaries' are not similar
return 0
num_elements = len(l_1)
for i in xrange(0, num_elements):
if l_1[i].isdigit() and l_2[i].isdigit():
# both lines are integers
num_matches += 1
else:
l1_str = l_1[i].lower()
l2_str = l_2[i].lower()
if (l1_str[0] == l2_str[0]) and \
(l1_str[len(l1_str) - 1] == l2_str[len(l2_str) - 1]):
num_matches = num_matches + 1
if (len(l_1) == 0) or (float(num_matches) / float(len(l_1)) < 0.9):
return 0
else:
return 1 | [
"def",
"check_boundary_lines_similar",
"(",
"l_1",
",",
"l_2",
")",
":",
"num_matches",
"=",
"0",
"if",
"(",
"type",
"(",
"l_1",
")",
"!=",
"list",
")",
"or",
"(",
"type",
"(",
"l_2",
")",
"!=",
"list",
")",
"or",
"(",
"len",
"(",
"l_1",
")",
"!=",
"len",
"(",
"l_2",
")",
")",
":",
"# these 'boundaries' are not similar",
"return",
"0",
"num_elements",
"=",
"len",
"(",
"l_1",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"num_elements",
")",
":",
"if",
"l_1",
"[",
"i",
"]",
".",
"isdigit",
"(",
")",
"and",
"l_2",
"[",
"i",
"]",
".",
"isdigit",
"(",
")",
":",
"# both lines are integers",
"num_matches",
"+=",
"1",
"else",
":",
"l1_str",
"=",
"l_1",
"[",
"i",
"]",
".",
"lower",
"(",
")",
"l2_str",
"=",
"l_2",
"[",
"i",
"]",
".",
"lower",
"(",
")",
"if",
"(",
"l1_str",
"[",
"0",
"]",
"==",
"l2_str",
"[",
"0",
"]",
")",
"and",
"(",
"l1_str",
"[",
"len",
"(",
"l1_str",
")",
"-",
"1",
"]",
"==",
"l2_str",
"[",
"len",
"(",
"l2_str",
")",
"-",
"1",
"]",
")",
":",
"num_matches",
"=",
"num_matches",
"+",
"1",
"if",
"(",
"len",
"(",
"l_1",
")",
"==",
"0",
")",
"or",
"(",
"float",
"(",
"num_matches",
")",
"/",
"float",
"(",
"len",
"(",
"l_1",
")",
")",
"<",
"0.9",
")",
":",
"return",
"0",
"else",
":",
"return",
"1"
] | Compare two lists to see if their elements are roughly the same.
@param l_1: (list) of strings.
@param l_2: (list) of strings.
@return: (int) 1/0. | [
"Compare",
"two",
"lists",
"to",
"see",
"if",
"their",
"elements",
"are",
"roughly",
"the",
"same",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L427-L452 | train | 236,621 |
inspirehep/refextract | refextract/references/kbs.py | make_cache_key | def make_cache_key(custom_kbs_files=None):
"""Create cache key for kbs caches instances
This function generates a unique key for a given set of arguments.
The files dictionary is transformed like this:
{'journal': '/var/journal.kb', 'books': '/var/books.kb'}
to
"journal=/var/journal.kb;books=/var/books.kb"
Then _inspire is appended if we are an INSPIRE site.
"""
if custom_kbs_files:
serialized_args = ('%s=%s' % v for v in iteritems(custom_kbs_files))
serialized_args = ';'.join(serialized_args)
else:
serialized_args = "default"
cache_key = md5(serialized_args).digest()
return cache_key | python | def make_cache_key(custom_kbs_files=None):
"""Create cache key for kbs caches instances
This function generates a unique key for a given set of arguments.
The files dictionary is transformed like this:
{'journal': '/var/journal.kb', 'books': '/var/books.kb'}
to
"journal=/var/journal.kb;books=/var/books.kb"
Then _inspire is appended if we are an INSPIRE site.
"""
if custom_kbs_files:
serialized_args = ('%s=%s' % v for v in iteritems(custom_kbs_files))
serialized_args = ';'.join(serialized_args)
else:
serialized_args = "default"
cache_key = md5(serialized_args).digest()
return cache_key | [
"def",
"make_cache_key",
"(",
"custom_kbs_files",
"=",
"None",
")",
":",
"if",
"custom_kbs_files",
":",
"serialized_args",
"=",
"(",
"'%s=%s'",
"%",
"v",
"for",
"v",
"in",
"iteritems",
"(",
"custom_kbs_files",
")",
")",
"serialized_args",
"=",
"';'",
".",
"join",
"(",
"serialized_args",
")",
"else",
":",
"serialized_args",
"=",
"\"default\"",
"cache_key",
"=",
"md5",
"(",
"serialized_args",
")",
".",
"digest",
"(",
")",
"return",
"cache_key"
] | Create cache key for kbs caches instances
This function generates a unique key for a given set of arguments.
The files dictionary is transformed like this:
{'journal': '/var/journal.kb', 'books': '/var/books.kb'}
to
"journal=/var/journal.kb;books=/var/books.kb"
Then _inspire is appended if we are an INSPIRE site. | [
"Create",
"cache",
"key",
"for",
"kbs",
"caches",
"instances"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L112-L130 | train | 236,622 |
inspirehep/refextract | refextract/references/kbs.py | create_institute_numeration_group_regexp_pattern | def create_institute_numeration_group_regexp_pattern(patterns):
"""Using a list of regexp patterns for recognising numeration patterns
for institute preprint references, ordered by length - longest to
shortest - create a grouped 'OR' or of these patterns, ready to be
used in a bigger regexp.
@param patterns: (list) of strings. All of the numeration regexp
patterns for recognising an institute's preprint reference styles.
@return: (string) a grouped 'OR' regexp pattern of the numeration
patterns. E.g.:
(?P<num>[12]\d{3} \d\d\d|\d\d \d\d\d|[A-Za-z] \d\d\d)
"""
patterns_list = [institute_num_pattern_to_regex(p[1]) for p in patterns]
grouped_numeration_pattern = u"(?P<numn>%s)" % u'|'.join(patterns_list)
return grouped_numeration_pattern | python | def create_institute_numeration_group_regexp_pattern(patterns):
"""Using a list of regexp patterns for recognising numeration patterns
for institute preprint references, ordered by length - longest to
shortest - create a grouped 'OR' or of these patterns, ready to be
used in a bigger regexp.
@param patterns: (list) of strings. All of the numeration regexp
patterns for recognising an institute's preprint reference styles.
@return: (string) a grouped 'OR' regexp pattern of the numeration
patterns. E.g.:
(?P<num>[12]\d{3} \d\d\d|\d\d \d\d\d|[A-Za-z] \d\d\d)
"""
patterns_list = [institute_num_pattern_to_regex(p[1]) for p in patterns]
grouped_numeration_pattern = u"(?P<numn>%s)" % u'|'.join(patterns_list)
return grouped_numeration_pattern | [
"def",
"create_institute_numeration_group_regexp_pattern",
"(",
"patterns",
")",
":",
"patterns_list",
"=",
"[",
"institute_num_pattern_to_regex",
"(",
"p",
"[",
"1",
"]",
")",
"for",
"p",
"in",
"patterns",
"]",
"grouped_numeration_pattern",
"=",
"u\"(?P<numn>%s)\"",
"%",
"u'|'",
".",
"join",
"(",
"patterns_list",
")",
"return",
"grouped_numeration_pattern"
] | Using a list of regexp patterns for recognising numeration patterns
for institute preprint references, ordered by length - longest to
shortest - create a grouped 'OR' or of these patterns, ready to be
used in a bigger regexp.
@param patterns: (list) of strings. All of the numeration regexp
patterns for recognising an institute's preprint reference styles.
@return: (string) a grouped 'OR' regexp pattern of the numeration
patterns. E.g.:
(?P<num>[12]\d{3} \d\d\d|\d\d \d\d\d|[A-Za-z] \d\d\d) | [
"Using",
"a",
"list",
"of",
"regexp",
"patterns",
"for",
"recognising",
"numeration",
"patterns",
"for",
"institute",
"preprint",
"references",
"ordered",
"by",
"length",
"-",
"longest",
"to",
"shortest",
"-",
"create",
"a",
"grouped",
"OR",
"or",
"of",
"these",
"patterns",
"ready",
"to",
"be",
"used",
"in",
"a",
"bigger",
"regexp",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L161-L174 | train | 236,623 |
inspirehep/refextract | refextract/references/kbs.py | build_reportnum_kb | def build_reportnum_kb(fpath):
"""Given the path to a knowledge base file containing the details
of institutes and the patterns that their preprint report
numbering schemes take, create a dictionary of regexp search
patterns to recognise these preprint references in reference
lines, and a dictionary of replacements for non-standard preprint
categories in these references.
The knowledge base file should consist only of lines that take one
of the following 3 formats:
#####Institute Name####
(the name of the institute to which the preprint reference patterns
belong, e.g. '#####LANL#####', surrounded by 5 # on either side.)
<pattern>
(numeration patterns for an institute's preprints, surrounded by
< and >.)
seek-term --- replace-term
(i.e. a seek phrase on the left hand side, a replace phrase on the
right hand side, with the two phrases being separated by 3 hyphens.)
E.g.:
ASTRO PH ---astro-ph
The left-hand side term is a non-standard version of the preprint
reference category; the right-hand side term is the standard version.
If the KB file cannot be read from, or an unexpected line is
encountered in the KB, an error message is output to standard error
and execution is halted with an error-code 0.
@param fpath: (string) the path to the knowledge base file.
@return: (tuple) containing 2 dictionaries. The first contains regexp
search patterns used to identify preprint references in a line. This
dictionary is keyed by a tuple containing the line number of the
pattern in the KB and the non-standard category string.
E.g.: (3, 'ASTRO PH').
The second dictionary contains the standardised category string,
and is keyed by the non-standard category string. E.g.: 'astro-ph'.
"""
def _add_institute_preprint_patterns(preprint_classifications,
preprint_numeration_ptns,
preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories,
kb_line_num):
"""For a list of preprint category strings and preprint numeration
patterns for a given institute, create the regexp patterns for
each of the preprint types. Add the regexp patterns to the
dictionary of search patterns
(preprint_reference_search_regexp_patterns), keyed by the line
number of the institute in the KB, and the preprint category
search string. Also add the standardised preprint category string
to another dictionary, keyed by the line number of its position
in the KB and its non-standardised version.
@param preprint_classifications: (list) of tuples whereby each tuple
contains a preprint category search string and the line number of
the name of institute to which it belongs in the KB.
E.g.: (45, 'ASTRO PH').
@param preprint_numeration_ptns: (list) of preprint reference
numeration search patterns (strings)
@param preprint_reference_search_regexp_patterns: (dictionary) of
regexp patterns used to search in document lines.
@param standardised_preprint_reference_categories: (dictionary)
containing the standardised strings for preprint reference
categories. (E.g. 'astro-ph'.)
@param kb_line_num: (integer) - the line number int the KB at
which a given institute name was found.
@return: None
"""
if preprint_classifications and preprint_numeration_ptns:
# the previous institute had both numeration styles and categories
# for preprint references.
# build regexps and add them for this institute:
# First, order the numeration styles by line-length, and build a
# grouped regexp for recognising numeration:
ordered_patterns = \
order_reportnum_patterns_bylen(preprint_numeration_ptns)
# create a grouped regexp for numeration part of
# preprint reference:
numeration_regexp = \
create_institute_numeration_group_regexp_pattern(
ordered_patterns)
# for each "classification" part of preprint references, create a
# complete regex:
# will be in the style "(categ)-(numatn1|numatn2|numatn3|...)"
for classification in preprint_classifications:
search_pattern_str = ur'(?:^|[^a-zA-Z0-9\/\.\-])([\[\(]?(?P<categ>' \
+ classification[0].strip() + u')' \
+ numeration_regexp + ur'[\]\)]?)'
re_search_pattern = re.compile(search_pattern_str,
re.UNICODE)
preprint_reference_search_regexp_patterns[(kb_line_num,
classification[0])] =\
re_search_pattern
standardised_preprint_reference_categories[(kb_line_num,
classification[0])] =\
classification[1]
preprint_reference_search_regexp_patterns = {} # a dictionary of patterns
# used to recognise
# categories of preprints
# as used by various
# institutes
standardised_preprint_reference_categories = {} # dictionary of
# standardised category
# strings for preprint cats
current_institute_preprint_classifications = [] # list of tuples containing
# preprint categories in
# their raw & standardised
# forms, as read from KB
current_institute_numerations = [] # list of preprint
# numeration patterns, as
# read from the KB
# pattern to recognise an institute name line in the KB
re_institute_name = re.compile(ur'^\*{5}\s*(.+)\s*\*{5}$', re.UNICODE)
# pattern to recognise an institute preprint categ line in the KB
re_preprint_classification = \
re.compile(ur'^\s*(\w.*)\s*---\s*(\w.*)\s*$', re.UNICODE)
# pattern to recognise a preprint numeration-style line in KB
re_numeration_pattern = re.compile(ur'^\<(.+)\>$', re.UNICODE)
kb_line_num = 0 # when making the dictionary of patterns, which is
# keyed by the category search string, this counter
# will ensure that patterns in the dictionary are not
# overwritten if 2 institutes have the same category
# styles.
with file_resolving(fpath) as fh:
for rawline in fh:
if rawline.startswith('#'):
continue
kb_line_num += 1
m_institute_name = re_institute_name.search(rawline)
if m_institute_name:
# This KB line is the name of an institute
# append the last institute's pattern list to the list of
# institutes:
_add_institute_preprint_patterns(current_institute_preprint_classifications,
current_institute_numerations,
preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories,
kb_line_num)
# Now start a new dictionary to contain the search patterns
# for this institute:
current_institute_preprint_classifications = []
current_institute_numerations = []
# move on to the next line
continue
m_preprint_classification = \
re_preprint_classification.search(rawline)
if m_preprint_classification:
# This KB line contains a preprint classification for
# the current institute
try:
current_institute_preprint_classifications.append((m_preprint_classification.group(1),
m_preprint_classification.group(2)))
except (AttributeError, NameError):
# didn't match this line correctly - skip it
pass
# move on to the next line
continue
m_numeration_pattern = re_numeration_pattern.search(rawline)
if m_numeration_pattern:
# This KB line contains a preprint item numeration pattern
# for the current institute
try:
current_institute_numerations.append(
m_numeration_pattern.group(1))
except (AttributeError, NameError):
# didn't match the numeration pattern correctly - skip it
pass
continue
_add_institute_preprint_patterns(current_institute_preprint_classifications,
current_institute_numerations,
preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories,
kb_line_num)
# return the preprint reference patterns and the replacement strings
# for non-standard categ-strings:
return (preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories) | python | def build_reportnum_kb(fpath):
"""Given the path to a knowledge base file containing the details
of institutes and the patterns that their preprint report
numbering schemes take, create a dictionary of regexp search
patterns to recognise these preprint references in reference
lines, and a dictionary of replacements for non-standard preprint
categories in these references.
The knowledge base file should consist only of lines that take one
of the following 3 formats:
#####Institute Name####
(the name of the institute to which the preprint reference patterns
belong, e.g. '#####LANL#####', surrounded by 5 # on either side.)
<pattern>
(numeration patterns for an institute's preprints, surrounded by
< and >.)
seek-term --- replace-term
(i.e. a seek phrase on the left hand side, a replace phrase on the
right hand side, with the two phrases being separated by 3 hyphens.)
E.g.:
ASTRO PH ---astro-ph
The left-hand side term is a non-standard version of the preprint
reference category; the right-hand side term is the standard version.
If the KB file cannot be read from, or an unexpected line is
encountered in the KB, an error message is output to standard error
and execution is halted with an error-code 0.
@param fpath: (string) the path to the knowledge base file.
@return: (tuple) containing 2 dictionaries. The first contains regexp
search patterns used to identify preprint references in a line. This
dictionary is keyed by a tuple containing the line number of the
pattern in the KB and the non-standard category string.
E.g.: (3, 'ASTRO PH').
The second dictionary contains the standardised category string,
and is keyed by the non-standard category string. E.g.: 'astro-ph'.
"""
def _add_institute_preprint_patterns(preprint_classifications,
preprint_numeration_ptns,
preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories,
kb_line_num):
"""For a list of preprint category strings and preprint numeration
patterns for a given institute, create the regexp patterns for
each of the preprint types. Add the regexp patterns to the
dictionary of search patterns
(preprint_reference_search_regexp_patterns), keyed by the line
number of the institute in the KB, and the preprint category
search string. Also add the standardised preprint category string
to another dictionary, keyed by the line number of its position
in the KB and its non-standardised version.
@param preprint_classifications: (list) of tuples whereby each tuple
contains a preprint category search string and the line number of
the name of institute to which it belongs in the KB.
E.g.: (45, 'ASTRO PH').
@param preprint_numeration_ptns: (list) of preprint reference
numeration search patterns (strings)
@param preprint_reference_search_regexp_patterns: (dictionary) of
regexp patterns used to search in document lines.
@param standardised_preprint_reference_categories: (dictionary)
containing the standardised strings for preprint reference
categories. (E.g. 'astro-ph'.)
@param kb_line_num: (integer) - the line number int the KB at
which a given institute name was found.
@return: None
"""
if preprint_classifications and preprint_numeration_ptns:
# the previous institute had both numeration styles and categories
# for preprint references.
# build regexps and add them for this institute:
# First, order the numeration styles by line-length, and build a
# grouped regexp for recognising numeration:
ordered_patterns = \
order_reportnum_patterns_bylen(preprint_numeration_ptns)
# create a grouped regexp for numeration part of
# preprint reference:
numeration_regexp = \
create_institute_numeration_group_regexp_pattern(
ordered_patterns)
# for each "classification" part of preprint references, create a
# complete regex:
# will be in the style "(categ)-(numatn1|numatn2|numatn3|...)"
for classification in preprint_classifications:
search_pattern_str = ur'(?:^|[^a-zA-Z0-9\/\.\-])([\[\(]?(?P<categ>' \
+ classification[0].strip() + u')' \
+ numeration_regexp + ur'[\]\)]?)'
re_search_pattern = re.compile(search_pattern_str,
re.UNICODE)
preprint_reference_search_regexp_patterns[(kb_line_num,
classification[0])] =\
re_search_pattern
standardised_preprint_reference_categories[(kb_line_num,
classification[0])] =\
classification[1]
preprint_reference_search_regexp_patterns = {} # a dictionary of patterns
# used to recognise
# categories of preprints
# as used by various
# institutes
standardised_preprint_reference_categories = {} # dictionary of
# standardised category
# strings for preprint cats
current_institute_preprint_classifications = [] # list of tuples containing
# preprint categories in
# their raw & standardised
# forms, as read from KB
current_institute_numerations = [] # list of preprint
# numeration patterns, as
# read from the KB
# pattern to recognise an institute name line in the KB
re_institute_name = re.compile(ur'^\*{5}\s*(.+)\s*\*{5}$', re.UNICODE)
# pattern to recognise an institute preprint categ line in the KB
re_preprint_classification = \
re.compile(ur'^\s*(\w.*)\s*---\s*(\w.*)\s*$', re.UNICODE)
# pattern to recognise a preprint numeration-style line in KB
re_numeration_pattern = re.compile(ur'^\<(.+)\>$', re.UNICODE)
kb_line_num = 0 # when making the dictionary of patterns, which is
# keyed by the category search string, this counter
# will ensure that patterns in the dictionary are not
# overwritten if 2 institutes have the same category
# styles.
with file_resolving(fpath) as fh:
for rawline in fh:
if rawline.startswith('#'):
continue
kb_line_num += 1
m_institute_name = re_institute_name.search(rawline)
if m_institute_name:
# This KB line is the name of an institute
# append the last institute's pattern list to the list of
# institutes:
_add_institute_preprint_patterns(current_institute_preprint_classifications,
current_institute_numerations,
preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories,
kb_line_num)
# Now start a new dictionary to contain the search patterns
# for this institute:
current_institute_preprint_classifications = []
current_institute_numerations = []
# move on to the next line
continue
m_preprint_classification = \
re_preprint_classification.search(rawline)
if m_preprint_classification:
# This KB line contains a preprint classification for
# the current institute
try:
current_institute_preprint_classifications.append((m_preprint_classification.group(1),
m_preprint_classification.group(2)))
except (AttributeError, NameError):
# didn't match this line correctly - skip it
pass
# move on to the next line
continue
m_numeration_pattern = re_numeration_pattern.search(rawline)
if m_numeration_pattern:
# This KB line contains a preprint item numeration pattern
# for the current institute
try:
current_institute_numerations.append(
m_numeration_pattern.group(1))
except (AttributeError, NameError):
# didn't match the numeration pattern correctly - skip it
pass
continue
_add_institute_preprint_patterns(current_institute_preprint_classifications,
current_institute_numerations,
preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories,
kb_line_num)
# return the preprint reference patterns and the replacement strings
# for non-standard categ-strings:
return (preprint_reference_search_regexp_patterns,
standardised_preprint_reference_categories) | [
"def",
"build_reportnum_kb",
"(",
"fpath",
")",
":",
"def",
"_add_institute_preprint_patterns",
"(",
"preprint_classifications",
",",
"preprint_numeration_ptns",
",",
"preprint_reference_search_regexp_patterns",
",",
"standardised_preprint_reference_categories",
",",
"kb_line_num",
")",
":",
"\"\"\"For a list of preprint category strings and preprint numeration\n patterns for a given institute, create the regexp patterns for\n each of the preprint types. Add the regexp patterns to the\n dictionary of search patterns\n (preprint_reference_search_regexp_patterns), keyed by the line\n number of the institute in the KB, and the preprint category\n search string. Also add the standardised preprint category string\n to another dictionary, keyed by the line number of its position\n in the KB and its non-standardised version.\n @param preprint_classifications: (list) of tuples whereby each tuple\n contains a preprint category search string and the line number of\n the name of institute to which it belongs in the KB.\n E.g.: (45, 'ASTRO PH').\n @param preprint_numeration_ptns: (list) of preprint reference\n numeration search patterns (strings)\n @param preprint_reference_search_regexp_patterns: (dictionary) of\n regexp patterns used to search in document lines.\n @param standardised_preprint_reference_categories: (dictionary)\n containing the standardised strings for preprint reference\n categories. (E.g. 'astro-ph'.)\n @param kb_line_num: (integer) - the line number int the KB at\n which a given institute name was found.\n @return: None\n \"\"\"",
"if",
"preprint_classifications",
"and",
"preprint_numeration_ptns",
":",
"# the previous institute had both numeration styles and categories",
"# for preprint references.",
"# build regexps and add them for this institute:",
"# First, order the numeration styles by line-length, and build a",
"# grouped regexp for recognising numeration:",
"ordered_patterns",
"=",
"order_reportnum_patterns_bylen",
"(",
"preprint_numeration_ptns",
")",
"# create a grouped regexp for numeration part of",
"# preprint reference:",
"numeration_regexp",
"=",
"create_institute_numeration_group_regexp_pattern",
"(",
"ordered_patterns",
")",
"# for each \"classification\" part of preprint references, create a",
"# complete regex:",
"# will be in the style \"(categ)-(numatn1|numatn2|numatn3|...)\"",
"for",
"classification",
"in",
"preprint_classifications",
":",
"search_pattern_str",
"=",
"ur'(?:^|[^a-zA-Z0-9\\/\\.\\-])([\\[\\(]?(?P<categ>'",
"+",
"classification",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"+",
"u')'",
"+",
"numeration_regexp",
"+",
"ur'[\\]\\)]?)'",
"re_search_pattern",
"=",
"re",
".",
"compile",
"(",
"search_pattern_str",
",",
"re",
".",
"UNICODE",
")",
"preprint_reference_search_regexp_patterns",
"[",
"(",
"kb_line_num",
",",
"classification",
"[",
"0",
"]",
")",
"]",
"=",
"re_search_pattern",
"standardised_preprint_reference_categories",
"[",
"(",
"kb_line_num",
",",
"classification",
"[",
"0",
"]",
")",
"]",
"=",
"classification",
"[",
"1",
"]",
"preprint_reference_search_regexp_patterns",
"=",
"{",
"}",
"# a dictionary of patterns",
"# used to recognise",
"# categories of preprints",
"# as used by various",
"# institutes",
"standardised_preprint_reference_categories",
"=",
"{",
"}",
"# dictionary of",
"# standardised category",
"# strings for preprint cats",
"current_institute_preprint_classifications",
"=",
"[",
"]",
"# list of tuples containing",
"# preprint categories in",
"# their raw & standardised",
"# forms, as read from KB",
"current_institute_numerations",
"=",
"[",
"]",
"# list of preprint",
"# numeration patterns, as",
"# read from the KB",
"# pattern to recognise an institute name line in the KB",
"re_institute_name",
"=",
"re",
".",
"compile",
"(",
"ur'^\\*{5}\\s*(.+)\\s*\\*{5}$'",
",",
"re",
".",
"UNICODE",
")",
"# pattern to recognise an institute preprint categ line in the KB",
"re_preprint_classification",
"=",
"re",
".",
"compile",
"(",
"ur'^\\s*(\\w.*)\\s*---\\s*(\\w.*)\\s*$'",
",",
"re",
".",
"UNICODE",
")",
"# pattern to recognise a preprint numeration-style line in KB",
"re_numeration_pattern",
"=",
"re",
".",
"compile",
"(",
"ur'^\\<(.+)\\>$'",
",",
"re",
".",
"UNICODE",
")",
"kb_line_num",
"=",
"0",
"# when making the dictionary of patterns, which is",
"# keyed by the category search string, this counter",
"# will ensure that patterns in the dictionary are not",
"# overwritten if 2 institutes have the same category",
"# styles.",
"with",
"file_resolving",
"(",
"fpath",
")",
"as",
"fh",
":",
"for",
"rawline",
"in",
"fh",
":",
"if",
"rawline",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"kb_line_num",
"+=",
"1",
"m_institute_name",
"=",
"re_institute_name",
".",
"search",
"(",
"rawline",
")",
"if",
"m_institute_name",
":",
"# This KB line is the name of an institute",
"# append the last institute's pattern list to the list of",
"# institutes:",
"_add_institute_preprint_patterns",
"(",
"current_institute_preprint_classifications",
",",
"current_institute_numerations",
",",
"preprint_reference_search_regexp_patterns",
",",
"standardised_preprint_reference_categories",
",",
"kb_line_num",
")",
"# Now start a new dictionary to contain the search patterns",
"# for this institute:",
"current_institute_preprint_classifications",
"=",
"[",
"]",
"current_institute_numerations",
"=",
"[",
"]",
"# move on to the next line",
"continue",
"m_preprint_classification",
"=",
"re_preprint_classification",
".",
"search",
"(",
"rawline",
")",
"if",
"m_preprint_classification",
":",
"# This KB line contains a preprint classification for",
"# the current institute",
"try",
":",
"current_institute_preprint_classifications",
".",
"append",
"(",
"(",
"m_preprint_classification",
".",
"group",
"(",
"1",
")",
",",
"m_preprint_classification",
".",
"group",
"(",
"2",
")",
")",
")",
"except",
"(",
"AttributeError",
",",
"NameError",
")",
":",
"# didn't match this line correctly - skip it",
"pass",
"# move on to the next line",
"continue",
"m_numeration_pattern",
"=",
"re_numeration_pattern",
".",
"search",
"(",
"rawline",
")",
"if",
"m_numeration_pattern",
":",
"# This KB line contains a preprint item numeration pattern",
"# for the current institute",
"try",
":",
"current_institute_numerations",
".",
"append",
"(",
"m_numeration_pattern",
".",
"group",
"(",
"1",
")",
")",
"except",
"(",
"AttributeError",
",",
"NameError",
")",
":",
"# didn't match the numeration pattern correctly - skip it",
"pass",
"continue",
"_add_institute_preprint_patterns",
"(",
"current_institute_preprint_classifications",
",",
"current_institute_numerations",
",",
"preprint_reference_search_regexp_patterns",
",",
"standardised_preprint_reference_categories",
",",
"kb_line_num",
")",
"# return the preprint reference patterns and the replacement strings",
"# for non-standard categ-strings:",
"return",
"(",
"preprint_reference_search_regexp_patterns",
",",
"standardised_preprint_reference_categories",
")"
] | Given the path to a knowledge base file containing the details
of institutes and the patterns that their preprint report
numbering schemes take, create a dictionary of regexp search
patterns to recognise these preprint references in reference
lines, and a dictionary of replacements for non-standard preprint
categories in these references.
The knowledge base file should consist only of lines that take one
of the following 3 formats:
#####Institute Name####
(the name of the institute to which the preprint reference patterns
belong, e.g. '#####LANL#####', surrounded by 5 # on either side.)
<pattern>
(numeration patterns for an institute's preprints, surrounded by
< and >.)
seek-term --- replace-term
(i.e. a seek phrase on the left hand side, a replace phrase on the
right hand side, with the two phrases being separated by 3 hyphens.)
E.g.:
ASTRO PH ---astro-ph
The left-hand side term is a non-standard version of the preprint
reference category; the right-hand side term is the standard version.
If the KB file cannot be read from, or an unexpected line is
encountered in the KB, an error message is output to standard error
and execution is halted with an error-code 0.
@param fpath: (string) the path to the knowledge base file.
@return: (tuple) containing 2 dictionaries. The first contains regexp
search patterns used to identify preprint references in a line. This
dictionary is keyed by a tuple containing the line number of the
pattern in the KB and the non-standard category string.
E.g.: (3, 'ASTRO PH').
The second dictionary contains the standardised category string,
and is keyed by the non-standard category string. E.g.: 'astro-ph'. | [
"Given",
"the",
"path",
"to",
"a",
"knowledge",
"base",
"file",
"containing",
"the",
"details",
"of",
"institutes",
"and",
"the",
"patterns",
"that",
"their",
"preprint",
"report",
"numbering",
"schemes",
"take",
"create",
"a",
"dictionary",
"of",
"regexp",
"search",
"patterns",
"to",
"recognise",
"these",
"preprint",
"references",
"in",
"reference",
"lines",
"and",
"a",
"dictionary",
"of",
"replacements",
"for",
"non",
"-",
"standard",
"preprint",
"categories",
"in",
"these",
"references",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L222-L415 | train | 236,624 |
inspirehep/refextract | refextract/references/kbs.py | _cmp_bystrlen_reverse | def _cmp_bystrlen_reverse(a, b):
"""A private "cmp" function to be used by the "sort" function of a
list when ordering the titles found in a knowledge base by string-
length - LONGEST -> SHORTEST.
@param a: (string)
@param b: (string)
@return: (integer) - 0 if len(a) == len(b); 1 if len(a) < len(b);
-1 if len(a) > len(b);
"""
if len(a) > len(b):
return -1
elif len(a) < len(b):
return 1
else:
return 0 | python | def _cmp_bystrlen_reverse(a, b):
"""A private "cmp" function to be used by the "sort" function of a
list when ordering the titles found in a knowledge base by string-
length - LONGEST -> SHORTEST.
@param a: (string)
@param b: (string)
@return: (integer) - 0 if len(a) == len(b); 1 if len(a) < len(b);
-1 if len(a) > len(b);
"""
if len(a) > len(b):
return -1
elif len(a) < len(b):
return 1
else:
return 0 | [
"def",
"_cmp_bystrlen_reverse",
"(",
"a",
",",
"b",
")",
":",
"if",
"len",
"(",
"a",
")",
">",
"len",
"(",
"b",
")",
":",
"return",
"-",
"1",
"elif",
"len",
"(",
"a",
")",
"<",
"len",
"(",
"b",
")",
":",
"return",
"1",
"else",
":",
"return",
"0"
] | A private "cmp" function to be used by the "sort" function of a
list when ordering the titles found in a knowledge base by string-
length - LONGEST -> SHORTEST.
@param a: (string)
@param b: (string)
@return: (integer) - 0 if len(a) == len(b); 1 if len(a) < len(b);
-1 if len(a) > len(b); | [
"A",
"private",
"cmp",
"function",
"to",
"be",
"used",
"by",
"the",
"sort",
"function",
"of",
"a",
"list",
"when",
"ordering",
"the",
"titles",
"found",
"in",
"a",
"knowledge",
"base",
"by",
"string",
"-",
"length",
"-",
"LONGEST",
"-",
">",
"SHORTEST",
"."
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L418-L432 | train | 236,625 |
inspirehep/refextract | refextract/references/kbs.py | build_special_journals_kb | def build_special_journals_kb(fpath):
"""Load special journals database from file
Special journals are journals that have a volume which is not unique
among different years. To keep the volume unique we are adding the year
before the volume.
"""
journals = set()
with file_resolving(fpath) as fh:
for line in fh:
# Skip commented lines
if line.startswith('#'):
continue
# Skip empty line
if not line.strip():
continue
journals.add(line.strip())
return journals | python | def build_special_journals_kb(fpath):
"""Load special journals database from file
Special journals are journals that have a volume which is not unique
among different years. To keep the volume unique we are adding the year
before the volume.
"""
journals = set()
with file_resolving(fpath) as fh:
for line in fh:
# Skip commented lines
if line.startswith('#'):
continue
# Skip empty line
if not line.strip():
continue
journals.add(line.strip())
return journals | [
"def",
"build_special_journals_kb",
"(",
"fpath",
")",
":",
"journals",
"=",
"set",
"(",
")",
"with",
"file_resolving",
"(",
"fpath",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"# Skip commented lines",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"# Skip empty line",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"journals",
".",
"add",
"(",
"line",
".",
"strip",
"(",
")",
")",
"return",
"journals"
] | Load special journals database from file
Special journals are journals that have a volume which is not unique
among different years. To keep the volume unique we are adding the year
before the volume. | [
"Load",
"special",
"journals",
"database",
"from",
"file"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L435-L453 | train | 236,626 |
inspirehep/refextract | refextract/references/kbs.py | build_journals_re_kb | def build_journals_re_kb(fpath):
"""Load journals regexps knowledge base
@see build_journals_kb
"""
def make_tuple(match):
regexp = match.group('seek')
repl = match.group('repl')
return regexp, repl
kb = []
with file_resolving(fpath) as fh:
for rawline in fh:
if rawline.startswith('#'):
continue
# Extract the seek->replace terms from this KB line:
m_kb_line = re_kb_line.search(rawline)
kb.append(make_tuple(m_kb_line))
return kb | python | def build_journals_re_kb(fpath):
"""Load journals regexps knowledge base
@see build_journals_kb
"""
def make_tuple(match):
regexp = match.group('seek')
repl = match.group('repl')
return regexp, repl
kb = []
with file_resolving(fpath) as fh:
for rawline in fh:
if rawline.startswith('#'):
continue
# Extract the seek->replace terms from this KB line:
m_kb_line = re_kb_line.search(rawline)
kb.append(make_tuple(m_kb_line))
return kb | [
"def",
"build_journals_re_kb",
"(",
"fpath",
")",
":",
"def",
"make_tuple",
"(",
"match",
")",
":",
"regexp",
"=",
"match",
".",
"group",
"(",
"'seek'",
")",
"repl",
"=",
"match",
".",
"group",
"(",
"'repl'",
")",
"return",
"regexp",
",",
"repl",
"kb",
"=",
"[",
"]",
"with",
"file_resolving",
"(",
"fpath",
")",
"as",
"fh",
":",
"for",
"rawline",
"in",
"fh",
":",
"if",
"rawline",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"# Extract the seek->replace terms from this KB line:",
"m_kb_line",
"=",
"re_kb_line",
".",
"search",
"(",
"rawline",
")",
"kb",
".",
"append",
"(",
"make_tuple",
"(",
"m_kb_line",
")",
")",
"return",
"kb"
] | Load journals regexps knowledge base
@see build_journals_kb | [
"Load",
"journals",
"regexps",
"knowledge",
"base"
] | d70e3787be3c495a3a07d1517b53f81d51c788c7 | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L492-L512 | train | 236,627 |
brettcannon/gidgethub | gidgethub/sansio.py | _parse_content_type | def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]:
"""Tease out the content-type and character encoding.
A default character encoding of UTF-8 is used, so the content-type
must be used to determine if any decoding is necessary to begin
with.
"""
if not content_type:
return None, "utf-8"
else:
type_, parameters = cgi.parse_header(content_type)
encoding = parameters.get("charset", "utf-8")
return type_, encoding | python | def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]:
"""Tease out the content-type and character encoding.
A default character encoding of UTF-8 is used, so the content-type
must be used to determine if any decoding is necessary to begin
with.
"""
if not content_type:
return None, "utf-8"
else:
type_, parameters = cgi.parse_header(content_type)
encoding = parameters.get("charset", "utf-8")
return type_, encoding | [
"def",
"_parse_content_type",
"(",
"content_type",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"str",
"]",
":",
"if",
"not",
"content_type",
":",
"return",
"None",
",",
"\"utf-8\"",
"else",
":",
"type_",
",",
"parameters",
"=",
"cgi",
".",
"parse_header",
"(",
"content_type",
")",
"encoding",
"=",
"parameters",
".",
"get",
"(",
"\"charset\"",
",",
"\"utf-8\"",
")",
"return",
"type_",
",",
"encoding"
] | Tease out the content-type and character encoding.
A default character encoding of UTF-8 is used, so the content-type
must be used to determine if any decoding is necessary to begin
with. | [
"Tease",
"out",
"the",
"content",
"-",
"type",
"and",
"character",
"encoding",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L24-L36 | train | 236,628 |
brettcannon/gidgethub | gidgethub/sansio.py | _decode_body | def _decode_body(content_type: Optional[str], body: bytes,
*, strict: bool = False) -> Any:
"""Decode an HTTP body based on the specified content type.
If 'strict' is true, then raise ValueError if the content type
is not recognized. Otherwise simply returned the body as a decoded
string.
"""
type_, encoding = _parse_content_type(content_type)
if not len(body) or not content_type:
return None
decoded_body = body.decode(encoding)
if type_ == "application/json":
return json.loads(decoded_body)
elif type_ == "application/x-www-form-urlencoded":
return json.loads(urllib.parse.parse_qs(decoded_body)["payload"][0])
elif strict:
raise ValueError(f"unrecognized content type: {type_!r}")
return decoded_body | python | def _decode_body(content_type: Optional[str], body: bytes,
*, strict: bool = False) -> Any:
"""Decode an HTTP body based on the specified content type.
If 'strict' is true, then raise ValueError if the content type
is not recognized. Otherwise simply returned the body as a decoded
string.
"""
type_, encoding = _parse_content_type(content_type)
if not len(body) or not content_type:
return None
decoded_body = body.decode(encoding)
if type_ == "application/json":
return json.loads(decoded_body)
elif type_ == "application/x-www-form-urlencoded":
return json.loads(urllib.parse.parse_qs(decoded_body)["payload"][0])
elif strict:
raise ValueError(f"unrecognized content type: {type_!r}")
return decoded_body | [
"def",
"_decode_body",
"(",
"content_type",
":",
"Optional",
"[",
"str",
"]",
",",
"body",
":",
"bytes",
",",
"*",
",",
"strict",
":",
"bool",
"=",
"False",
")",
"->",
"Any",
":",
"type_",
",",
"encoding",
"=",
"_parse_content_type",
"(",
"content_type",
")",
"if",
"not",
"len",
"(",
"body",
")",
"or",
"not",
"content_type",
":",
"return",
"None",
"decoded_body",
"=",
"body",
".",
"decode",
"(",
"encoding",
")",
"if",
"type_",
"==",
"\"application/json\"",
":",
"return",
"json",
".",
"loads",
"(",
"decoded_body",
")",
"elif",
"type_",
"==",
"\"application/x-www-form-urlencoded\"",
":",
"return",
"json",
".",
"loads",
"(",
"urllib",
".",
"parse",
".",
"parse_qs",
"(",
"decoded_body",
")",
"[",
"\"payload\"",
"]",
"[",
"0",
"]",
")",
"elif",
"strict",
":",
"raise",
"ValueError",
"(",
"f\"unrecognized content type: {type_!r}\"",
")",
"return",
"decoded_body"
] | Decode an HTTP body based on the specified content type.
If 'strict' is true, then raise ValueError if the content type
is not recognized. Otherwise simply returned the body as a decoded
string. | [
"Decode",
"an",
"HTTP",
"body",
"based",
"on",
"the",
"specified",
"content",
"type",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L39-L57 | train | 236,629 |
brettcannon/gidgethub | gidgethub/sansio.py | validate_event | def validate_event(payload: bytes, *, signature: str, secret: str) -> None:
"""Validate the signature of a webhook event."""
# https://developer.github.com/webhooks/securing/#validating-payloads-from-github
signature_prefix = "sha1="
if not signature.startswith(signature_prefix):
raise ValidationFailure("signature does not start with "
f"{repr(signature_prefix)}")
hmac_ = hmac.new(secret.encode("UTF-8"), msg=payload, digestmod="sha1")
calculated_sig = signature_prefix + hmac_.hexdigest()
if not hmac.compare_digest(signature, calculated_sig):
raise ValidationFailure("payload's signature does not align "
"with the secret") | python | def validate_event(payload: bytes, *, signature: str, secret: str) -> None:
"""Validate the signature of a webhook event."""
# https://developer.github.com/webhooks/securing/#validating-payloads-from-github
signature_prefix = "sha1="
if not signature.startswith(signature_prefix):
raise ValidationFailure("signature does not start with "
f"{repr(signature_prefix)}")
hmac_ = hmac.new(secret.encode("UTF-8"), msg=payload, digestmod="sha1")
calculated_sig = signature_prefix + hmac_.hexdigest()
if not hmac.compare_digest(signature, calculated_sig):
raise ValidationFailure("payload's signature does not align "
"with the secret") | [
"def",
"validate_event",
"(",
"payload",
":",
"bytes",
",",
"*",
",",
"signature",
":",
"str",
",",
"secret",
":",
"str",
")",
"->",
"None",
":",
"# https://developer.github.com/webhooks/securing/#validating-payloads-from-github",
"signature_prefix",
"=",
"\"sha1=\"",
"if",
"not",
"signature",
".",
"startswith",
"(",
"signature_prefix",
")",
":",
"raise",
"ValidationFailure",
"(",
"\"signature does not start with \"",
"f\"{repr(signature_prefix)}\"",
")",
"hmac_",
"=",
"hmac",
".",
"new",
"(",
"secret",
".",
"encode",
"(",
"\"UTF-8\"",
")",
",",
"msg",
"=",
"payload",
",",
"digestmod",
"=",
"\"sha1\"",
")",
"calculated_sig",
"=",
"signature_prefix",
"+",
"hmac_",
".",
"hexdigest",
"(",
")",
"if",
"not",
"hmac",
".",
"compare_digest",
"(",
"signature",
",",
"calculated_sig",
")",
":",
"raise",
"ValidationFailure",
"(",
"\"payload's signature does not align \"",
"\"with the secret\"",
")"
] | Validate the signature of a webhook event. | [
"Validate",
"the",
"signature",
"of",
"a",
"webhook",
"event",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L60-L71 | train | 236,630 |
brettcannon/gidgethub | gidgethub/sansio.py | accept_format | def accept_format(*, version: str = "v3", media: Optional[str] = None,
json: bool = True) -> str:
"""Construct the specification of the format that a request should return.
The version argument defaults to v3 of the GitHub API and is applicable to
all requests. The media argument along with 'json' specifies what format
the request should return, e.g. requesting the rendered HTML of a comment.
Do note that not all of GitHub's API supports alternative formats.
The default arguments of this function will always return the latest stable
version of the GitHub API in the default format that this library is
designed to support.
"""
# https://developer.github.com/v3/media/
# https://developer.github.com/v3/#current-version
accept = f"application/vnd.github.{version}"
if media is not None:
accept += f".{media}"
if json:
accept += "+json"
return accept | python | def accept_format(*, version: str = "v3", media: Optional[str] = None,
json: bool = True) -> str:
"""Construct the specification of the format that a request should return.
The version argument defaults to v3 of the GitHub API and is applicable to
all requests. The media argument along with 'json' specifies what format
the request should return, e.g. requesting the rendered HTML of a comment.
Do note that not all of GitHub's API supports alternative formats.
The default arguments of this function will always return the latest stable
version of the GitHub API in the default format that this library is
designed to support.
"""
# https://developer.github.com/v3/media/
# https://developer.github.com/v3/#current-version
accept = f"application/vnd.github.{version}"
if media is not None:
accept += f".{media}"
if json:
accept += "+json"
return accept | [
"def",
"accept_format",
"(",
"*",
",",
"version",
":",
"str",
"=",
"\"v3\"",
",",
"media",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"json",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"# https://developer.github.com/v3/media/",
"# https://developer.github.com/v3/#current-version",
"accept",
"=",
"f\"application/vnd.github.{version}\"",
"if",
"media",
"is",
"not",
"None",
":",
"accept",
"+=",
"f\".{media}\"",
"if",
"json",
":",
"accept",
"+=",
"\"+json\"",
"return",
"accept"
] | Construct the specification of the format that a request should return.
The version argument defaults to v3 of the GitHub API and is applicable to
all requests. The media argument along with 'json' specifies what format
the request should return, e.g. requesting the rendered HTML of a comment.
Do note that not all of GitHub's API supports alternative formats.
The default arguments of this function will always return the latest stable
version of the GitHub API in the default format that this library is
designed to support. | [
"Construct",
"the",
"specification",
"of",
"the",
"format",
"that",
"a",
"request",
"should",
"return",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L125-L145 | train | 236,631 |
brettcannon/gidgethub | gidgethub/sansio.py | create_headers | def create_headers(requester: str, *, accept: str = accept_format(),
oauth_token: Optional[str] = None,
jwt: Optional[str] = None) -> Dict[str, str]:
"""Create a dict representing GitHub-specific header fields.
The user agent is set according to who the requester is. GitHub asks it be
either a username or project name.
The 'accept' argument corresponds to the 'accept' field and defaults to the
default result of accept_format(). You should only need to change this value
if you are using a different version of the API -- e.g. one that is under
development -- or if you are looking for a different format return type,
e.g. wanting the rendered HTML of a Markdown file.
The 'oauth_token' allows making an authenticated request using a personal access
token. This can be important if you need the expanded rate limit provided
by an authenticated request.
The 'jwt' allows authenticating as a GitHub App by passing in the
bearer token.
You can only supply only one of oauth_token or jwt, not both.
For consistency, all keys in the returned dict will be lowercased.
"""
# user-agent: https://developer.github.com/v3/#user-agent-required
# accept: https://developer.github.com/v3/#current-version
# https://developer.github.com/v3/media/
# authorization: https://developer.github.com/v3/#authentication
# authenticating as a GitHub App: https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app
if oauth_token is not None and jwt is not None:
raise ValueError("Cannot pass both oauth_token and jwt.")
headers = {"user-agent": requester, "accept": accept}
if oauth_token is not None:
headers["authorization"] = f"token {oauth_token}"
elif jwt is not None:
headers["authorization"] = f"bearer {jwt}"
return headers | python | def create_headers(requester: str, *, accept: str = accept_format(),
oauth_token: Optional[str] = None,
jwt: Optional[str] = None) -> Dict[str, str]:
"""Create a dict representing GitHub-specific header fields.
The user agent is set according to who the requester is. GitHub asks it be
either a username or project name.
The 'accept' argument corresponds to the 'accept' field and defaults to the
default result of accept_format(). You should only need to change this value
if you are using a different version of the API -- e.g. one that is under
development -- or if you are looking for a different format return type,
e.g. wanting the rendered HTML of a Markdown file.
The 'oauth_token' allows making an authenticated request using a personal access
token. This can be important if you need the expanded rate limit provided
by an authenticated request.
The 'jwt' allows authenticating as a GitHub App by passing in the
bearer token.
You can only supply only one of oauth_token or jwt, not both.
For consistency, all keys in the returned dict will be lowercased.
"""
# user-agent: https://developer.github.com/v3/#user-agent-required
# accept: https://developer.github.com/v3/#current-version
# https://developer.github.com/v3/media/
# authorization: https://developer.github.com/v3/#authentication
# authenticating as a GitHub App: https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app
if oauth_token is not None and jwt is not None:
raise ValueError("Cannot pass both oauth_token and jwt.")
headers = {"user-agent": requester, "accept": accept}
if oauth_token is not None:
headers["authorization"] = f"token {oauth_token}"
elif jwt is not None:
headers["authorization"] = f"bearer {jwt}"
return headers | [
"def",
"create_headers",
"(",
"requester",
":",
"str",
",",
"*",
",",
"accept",
":",
"str",
"=",
"accept_format",
"(",
")",
",",
"oauth_token",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"jwt",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"# user-agent: https://developer.github.com/v3/#user-agent-required",
"# accept: https://developer.github.com/v3/#current-version",
"# https://developer.github.com/v3/media/",
"# authorization: https://developer.github.com/v3/#authentication",
"# authenticating as a GitHub App: https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-a-github-app",
"if",
"oauth_token",
"is",
"not",
"None",
"and",
"jwt",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot pass both oauth_token and jwt.\"",
")",
"headers",
"=",
"{",
"\"user-agent\"",
":",
"requester",
",",
"\"accept\"",
":",
"accept",
"}",
"if",
"oauth_token",
"is",
"not",
"None",
":",
"headers",
"[",
"\"authorization\"",
"]",
"=",
"f\"token {oauth_token}\"",
"elif",
"jwt",
"is",
"not",
"None",
":",
"headers",
"[",
"\"authorization\"",
"]",
"=",
"f\"bearer {jwt}\"",
"return",
"headers"
] | Create a dict representing GitHub-specific header fields.
The user agent is set according to who the requester is. GitHub asks it be
either a username or project name.
The 'accept' argument corresponds to the 'accept' field and defaults to the
default result of accept_format(). You should only need to change this value
if you are using a different version of the API -- e.g. one that is under
development -- or if you are looking for a different format return type,
e.g. wanting the rendered HTML of a Markdown file.
The 'oauth_token' allows making an authenticated request using a personal access
token. This can be important if you need the expanded rate limit provided
by an authenticated request.
The 'jwt' allows authenticating as a GitHub App by passing in the
bearer token.
You can only supply only one of oauth_token or jwt, not both.
For consistency, all keys in the returned dict will be lowercased. | [
"Create",
"a",
"dict",
"representing",
"GitHub",
"-",
"specific",
"header",
"fields",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L148-L186 | train | 236,632 |
brettcannon/gidgethub | gidgethub/sansio.py | decipher_response | def decipher_response(status_code: int, headers: Mapping[str, str],
body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]:
"""Decipher an HTTP response for a GitHub API request.
The mapping providing the headers is expected to support lowercase keys.
The parameters of this function correspond to the three main parts
of an HTTP response: the status code, headers, and body. Assuming
no errors which lead to an exception being raised, a 3-item tuple
is returned. The first item is the decoded body (typically a JSON
object, but possibly None or a string depending on the content
type of the body). The second item is an instance of RateLimit
based on what the response specified.
The last item of the tuple is the URL where to request the next
part of results. If there are no more results then None is
returned. Do be aware that the URL can be a URI template and so
may need to be expanded.
If the status code is anything other than 200, 201, or 204, then
an HTTPException is raised.
"""
data = _decode_body(headers.get("content-type"), body)
if status_code in {200, 201, 204}:
return data, RateLimit.from_http(headers), _next_link(headers.get("link"))
else:
try:
message = data["message"]
except (TypeError, KeyError):
message = None
exc_type: Type[HTTPException]
if status_code >= 500:
exc_type = GitHubBroken
elif status_code >= 400:
exc_type = BadRequest
if status_code == 403:
rate_limit = RateLimit.from_http(headers)
if rate_limit and not rate_limit.remaining:
raise RateLimitExceeded(rate_limit, message)
elif status_code == 422:
errors = data.get("errors", None)
if errors:
fields = ", ".join(repr(e["field"]) for e in errors)
message = f"{message} for {fields}"
else:
message = data["message"]
raise InvalidField(errors, message)
elif status_code >= 300:
exc_type = RedirectionException
else:
exc_type = HTTPException
status_code_enum = http.HTTPStatus(status_code)
args: Union[Tuple[http.HTTPStatus, str], Tuple[http.HTTPStatus]]
if message:
args = status_code_enum, message
else:
args = status_code_enum,
raise exc_type(*args) | python | def decipher_response(status_code: int, headers: Mapping[str, str],
body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]:
"""Decipher an HTTP response for a GitHub API request.
The mapping providing the headers is expected to support lowercase keys.
The parameters of this function correspond to the three main parts
of an HTTP response: the status code, headers, and body. Assuming
no errors which lead to an exception being raised, a 3-item tuple
is returned. The first item is the decoded body (typically a JSON
object, but possibly None or a string depending on the content
type of the body). The second item is an instance of RateLimit
based on what the response specified.
The last item of the tuple is the URL where to request the next
part of results. If there are no more results then None is
returned. Do be aware that the URL can be a URI template and so
may need to be expanded.
If the status code is anything other than 200, 201, or 204, then
an HTTPException is raised.
"""
data = _decode_body(headers.get("content-type"), body)
if status_code in {200, 201, 204}:
return data, RateLimit.from_http(headers), _next_link(headers.get("link"))
else:
try:
message = data["message"]
except (TypeError, KeyError):
message = None
exc_type: Type[HTTPException]
if status_code >= 500:
exc_type = GitHubBroken
elif status_code >= 400:
exc_type = BadRequest
if status_code == 403:
rate_limit = RateLimit.from_http(headers)
if rate_limit and not rate_limit.remaining:
raise RateLimitExceeded(rate_limit, message)
elif status_code == 422:
errors = data.get("errors", None)
if errors:
fields = ", ".join(repr(e["field"]) for e in errors)
message = f"{message} for {fields}"
else:
message = data["message"]
raise InvalidField(errors, message)
elif status_code >= 300:
exc_type = RedirectionException
else:
exc_type = HTTPException
status_code_enum = http.HTTPStatus(status_code)
args: Union[Tuple[http.HTTPStatus, str], Tuple[http.HTTPStatus]]
if message:
args = status_code_enum, message
else:
args = status_code_enum,
raise exc_type(*args) | [
"def",
"decipher_response",
"(",
"status_code",
":",
"int",
",",
"headers",
":",
"Mapping",
"[",
"str",
",",
"str",
"]",
",",
"body",
":",
"bytes",
")",
"->",
"Tuple",
"[",
"Any",
",",
"Optional",
"[",
"RateLimit",
"]",
",",
"Optional",
"[",
"str",
"]",
"]",
":",
"data",
"=",
"_decode_body",
"(",
"headers",
".",
"get",
"(",
"\"content-type\"",
")",
",",
"body",
")",
"if",
"status_code",
"in",
"{",
"200",
",",
"201",
",",
"204",
"}",
":",
"return",
"data",
",",
"RateLimit",
".",
"from_http",
"(",
"headers",
")",
",",
"_next_link",
"(",
"headers",
".",
"get",
"(",
"\"link\"",
")",
")",
"else",
":",
"try",
":",
"message",
"=",
"data",
"[",
"\"message\"",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"message",
"=",
"None",
"exc_type",
":",
"Type",
"[",
"HTTPException",
"]",
"if",
"status_code",
">=",
"500",
":",
"exc_type",
"=",
"GitHubBroken",
"elif",
"status_code",
">=",
"400",
":",
"exc_type",
"=",
"BadRequest",
"if",
"status_code",
"==",
"403",
":",
"rate_limit",
"=",
"RateLimit",
".",
"from_http",
"(",
"headers",
")",
"if",
"rate_limit",
"and",
"not",
"rate_limit",
".",
"remaining",
":",
"raise",
"RateLimitExceeded",
"(",
"rate_limit",
",",
"message",
")",
"elif",
"status_code",
"==",
"422",
":",
"errors",
"=",
"data",
".",
"get",
"(",
"\"errors\"",
",",
"None",
")",
"if",
"errors",
":",
"fields",
"=",
"\", \"",
".",
"join",
"(",
"repr",
"(",
"e",
"[",
"\"field\"",
"]",
")",
"for",
"e",
"in",
"errors",
")",
"message",
"=",
"f\"{message} for {fields}\"",
"else",
":",
"message",
"=",
"data",
"[",
"\"message\"",
"]",
"raise",
"InvalidField",
"(",
"errors",
",",
"message",
")",
"elif",
"status_code",
">=",
"300",
":",
"exc_type",
"=",
"RedirectionException",
"else",
":",
"exc_type",
"=",
"HTTPException",
"status_code_enum",
"=",
"http",
".",
"HTTPStatus",
"(",
"status_code",
")",
"args",
":",
"Union",
"[",
"Tuple",
"[",
"http",
".",
"HTTPStatus",
",",
"str",
"]",
",",
"Tuple",
"[",
"http",
".",
"HTTPStatus",
"]",
"]",
"if",
"message",
":",
"args",
"=",
"status_code_enum",
",",
"message",
"else",
":",
"args",
"=",
"status_code_enum",
",",
"raise",
"exc_type",
"(",
"*",
"args",
")"
] | Decipher an HTTP response for a GitHub API request.
The mapping providing the headers is expected to support lowercase keys.
The parameters of this function correspond to the three main parts
of an HTTP response: the status code, headers, and body. Assuming
no errors which lead to an exception being raised, a 3-item tuple
is returned. The first item is the decoded body (typically a JSON
object, but possibly None or a string depending on the content
type of the body). The second item is an instance of RateLimit
based on what the response specified.
The last item of the tuple is the URL where to request the next
part of results. If there are no more results then None is
returned. Do be aware that the URL can be a URI template and so
may need to be expanded.
If the status code is anything other than 200, 201, or 204, then
an HTTPException is raised. | [
"Decipher",
"an",
"HTTP",
"response",
"for",
"a",
"GitHub",
"API",
"request",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L269-L326 | train | 236,633 |
brettcannon/gidgethub | gidgethub/sansio.py | format_url | def format_url(url: str, url_vars: Mapping[str, Any]) -> str:
"""Construct a URL for the GitHub API.
The URL may be absolute or relative. In the latter case the appropriate
domain will be added. This is to help when copying the relative URL directly
from the GitHub developer documentation.
The dict provided in url_vars is used in URI template formatting.
"""
url = urllib.parse.urljoin(DOMAIN, url) # Works even if 'url' is fully-qualified.
expanded_url: str = uritemplate.expand(url, var_dict=url_vars)
return expanded_url | python | def format_url(url: str, url_vars: Mapping[str, Any]) -> str:
"""Construct a URL for the GitHub API.
The URL may be absolute or relative. In the latter case the appropriate
domain will be added. This is to help when copying the relative URL directly
from the GitHub developer documentation.
The dict provided in url_vars is used in URI template formatting.
"""
url = urllib.parse.urljoin(DOMAIN, url) # Works even if 'url' is fully-qualified.
expanded_url: str = uritemplate.expand(url, var_dict=url_vars)
return expanded_url | [
"def",
"format_url",
"(",
"url",
":",
"str",
",",
"url_vars",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"str",
":",
"url",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"DOMAIN",
",",
"url",
")",
"# Works even if 'url' is fully-qualified.",
"expanded_url",
":",
"str",
"=",
"uritemplate",
".",
"expand",
"(",
"url",
",",
"var_dict",
"=",
"url_vars",
")",
"return",
"expanded_url"
] | Construct a URL for the GitHub API.
The URL may be absolute or relative. In the latter case the appropriate
domain will be added. This is to help when copying the relative URL directly
from the GitHub developer documentation.
The dict provided in url_vars is used in URI template formatting. | [
"Construct",
"a",
"URL",
"for",
"the",
"GitHub",
"API",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L331-L342 | train | 236,634 |
brettcannon/gidgethub | gidgethub/sansio.py | Event.from_http | def from_http(cls, headers: Mapping[str, str], body: bytes,
*, secret: Optional[str] = None) -> "Event":
"""Construct an event from HTTP headers and JSON body data.
The mapping providing the headers is expected to support lowercase keys.
Since this method assumes the body of the HTTP request is JSON, a check
is performed for a content-type of "application/json" (GitHub does
support other content-types). If the content-type does not match,
BadRequest is raised.
If the appropriate headers are provided for event validation, then it
will be performed unconditionally. Any failure in validation
(including not providing a secret) will lead to ValidationFailure being
raised.
"""
if "x-hub-signature" in headers:
if secret is None:
raise ValidationFailure("secret not provided")
validate_event(body, signature=headers["x-hub-signature"],
secret=secret)
elif secret is not None:
raise ValidationFailure("signature is missing")
try:
data = _decode_body(headers["content-type"], body, strict=True)
except (KeyError, ValueError) as exc:
raise BadRequest(http.HTTPStatus(415),
"expected a content-type of "
"'application/json' or "
"'application/x-www-form-urlencoded'") from exc
return cls(data, event=headers["x-github-event"],
delivery_id=headers["x-github-delivery"]) | python | def from_http(cls, headers: Mapping[str, str], body: bytes,
*, secret: Optional[str] = None) -> "Event":
"""Construct an event from HTTP headers and JSON body data.
The mapping providing the headers is expected to support lowercase keys.
Since this method assumes the body of the HTTP request is JSON, a check
is performed for a content-type of "application/json" (GitHub does
support other content-types). If the content-type does not match,
BadRequest is raised.
If the appropriate headers are provided for event validation, then it
will be performed unconditionally. Any failure in validation
(including not providing a secret) will lead to ValidationFailure being
raised.
"""
if "x-hub-signature" in headers:
if secret is None:
raise ValidationFailure("secret not provided")
validate_event(body, signature=headers["x-hub-signature"],
secret=secret)
elif secret is not None:
raise ValidationFailure("signature is missing")
try:
data = _decode_body(headers["content-type"], body, strict=True)
except (KeyError, ValueError) as exc:
raise BadRequest(http.HTTPStatus(415),
"expected a content-type of "
"'application/json' or "
"'application/x-www-form-urlencoded'") from exc
return cls(data, event=headers["x-github-event"],
delivery_id=headers["x-github-delivery"]) | [
"def",
"from_http",
"(",
"cls",
",",
"headers",
":",
"Mapping",
"[",
"str",
",",
"str",
"]",
",",
"body",
":",
"bytes",
",",
"*",
",",
"secret",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"\"Event\"",
":",
"if",
"\"x-hub-signature\"",
"in",
"headers",
":",
"if",
"secret",
"is",
"None",
":",
"raise",
"ValidationFailure",
"(",
"\"secret not provided\"",
")",
"validate_event",
"(",
"body",
",",
"signature",
"=",
"headers",
"[",
"\"x-hub-signature\"",
"]",
",",
"secret",
"=",
"secret",
")",
"elif",
"secret",
"is",
"not",
"None",
":",
"raise",
"ValidationFailure",
"(",
"\"signature is missing\"",
")",
"try",
":",
"data",
"=",
"_decode_body",
"(",
"headers",
"[",
"\"content-type\"",
"]",
",",
"body",
",",
"strict",
"=",
"True",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
"as",
"exc",
":",
"raise",
"BadRequest",
"(",
"http",
".",
"HTTPStatus",
"(",
"415",
")",
",",
"\"expected a content-type of \"",
"\"'application/json' or \"",
"\"'application/x-www-form-urlencoded'\"",
")",
"from",
"exc",
"return",
"cls",
"(",
"data",
",",
"event",
"=",
"headers",
"[",
"\"x-github-event\"",
"]",
",",
"delivery_id",
"=",
"headers",
"[",
"\"x-github-delivery\"",
"]",
")"
] | Construct an event from HTTP headers and JSON body data.
The mapping providing the headers is expected to support lowercase keys.
Since this method assumes the body of the HTTP request is JSON, a check
is performed for a content-type of "application/json" (GitHub does
support other content-types). If the content-type does not match,
BadRequest is raised.
If the appropriate headers are provided for event validation, then it
will be performed unconditionally. Any failure in validation
(including not providing a secret) will lead to ValidationFailure being
raised. | [
"Construct",
"an",
"event",
"from",
"HTTP",
"headers",
"and",
"JSON",
"body",
"data",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L90-L122 | train | 236,635 |
brettcannon/gidgethub | gidgethub/sansio.py | RateLimit.from_http | def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]:
"""Gather rate limit information from HTTP headers.
The mapping providing the headers is expected to support lowercase
keys. Returns ``None`` if ratelimit info is not found in the headers.
"""
try:
limit = int(headers["x-ratelimit-limit"])
remaining = int(headers["x-ratelimit-remaining"])
reset_epoch = float(headers["x-ratelimit-reset"])
except KeyError:
return None
else:
return cls(limit=limit, remaining=remaining, reset_epoch=reset_epoch) | python | def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]:
"""Gather rate limit information from HTTP headers.
The mapping providing the headers is expected to support lowercase
keys. Returns ``None`` if ratelimit info is not found in the headers.
"""
try:
limit = int(headers["x-ratelimit-limit"])
remaining = int(headers["x-ratelimit-remaining"])
reset_epoch = float(headers["x-ratelimit-reset"])
except KeyError:
return None
else:
return cls(limit=limit, remaining=remaining, reset_epoch=reset_epoch) | [
"def",
"from_http",
"(",
"cls",
",",
"headers",
":",
"Mapping",
"[",
"str",
",",
"str",
"]",
")",
"->",
"Optional",
"[",
"\"RateLimit\"",
"]",
":",
"try",
":",
"limit",
"=",
"int",
"(",
"headers",
"[",
"\"x-ratelimit-limit\"",
"]",
")",
"remaining",
"=",
"int",
"(",
"headers",
"[",
"\"x-ratelimit-remaining\"",
"]",
")",
"reset_epoch",
"=",
"float",
"(",
"headers",
"[",
"\"x-ratelimit-reset\"",
"]",
")",
"except",
"KeyError",
":",
"return",
"None",
"else",
":",
"return",
"cls",
"(",
"limit",
"=",
"limit",
",",
"remaining",
"=",
"remaining",
",",
"reset_epoch",
"=",
"reset_epoch",
")"
] | Gather rate limit information from HTTP headers.
The mapping providing the headers is expected to support lowercase
keys. Returns ``None`` if ratelimit info is not found in the headers. | [
"Gather",
"rate",
"limit",
"information",
"from",
"HTTP",
"headers",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L237-L250 | train | 236,636 |
brettcannon/gidgethub | gidgethub/routing.py | Router.add | def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None:
"""Add a new route.
After registering 'func' for the specified event_type, an
optional data_detail may be provided. By providing an extra
keyword argument, dispatching can occur based on a top-level
key of the data in the event being dispatched.
"""
if len(data_detail) > 1:
msg = ()
raise TypeError("dispatching based on data details is only "
"supported up to one level deep; "
f"{len(data_detail)} levels specified")
elif not data_detail:
callbacks = self._shallow_routes.setdefault(event_type, [])
callbacks.append(func)
else:
data_key, data_value = data_detail.popitem()
data_details = self._deep_routes.setdefault(event_type, {})
specific_detail = data_details.setdefault(data_key, {})
callbacks = specific_detail.setdefault(data_value, [])
callbacks.append(func) | python | def add(self, func: AsyncCallback, event_type: str, **data_detail: Any) -> None:
"""Add a new route.
After registering 'func' for the specified event_type, an
optional data_detail may be provided. By providing an extra
keyword argument, dispatching can occur based on a top-level
key of the data in the event being dispatched.
"""
if len(data_detail) > 1:
msg = ()
raise TypeError("dispatching based on data details is only "
"supported up to one level deep; "
f"{len(data_detail)} levels specified")
elif not data_detail:
callbacks = self._shallow_routes.setdefault(event_type, [])
callbacks.append(func)
else:
data_key, data_value = data_detail.popitem()
data_details = self._deep_routes.setdefault(event_type, {})
specific_detail = data_details.setdefault(data_key, {})
callbacks = specific_detail.setdefault(data_value, [])
callbacks.append(func) | [
"def",
"add",
"(",
"self",
",",
"func",
":",
"AsyncCallback",
",",
"event_type",
":",
"str",
",",
"*",
"*",
"data_detail",
":",
"Any",
")",
"->",
"None",
":",
"if",
"len",
"(",
"data_detail",
")",
">",
"1",
":",
"msg",
"=",
"(",
")",
"raise",
"TypeError",
"(",
"\"dispatching based on data details is only \"",
"\"supported up to one level deep; \"",
"f\"{len(data_detail)} levels specified\"",
")",
"elif",
"not",
"data_detail",
":",
"callbacks",
"=",
"self",
".",
"_shallow_routes",
".",
"setdefault",
"(",
"event_type",
",",
"[",
"]",
")",
"callbacks",
".",
"append",
"(",
"func",
")",
"else",
":",
"data_key",
",",
"data_value",
"=",
"data_detail",
".",
"popitem",
"(",
")",
"data_details",
"=",
"self",
".",
"_deep_routes",
".",
"setdefault",
"(",
"event_type",
",",
"{",
"}",
")",
"specific_detail",
"=",
"data_details",
".",
"setdefault",
"(",
"data_key",
",",
"{",
"}",
")",
"callbacks",
"=",
"specific_detail",
".",
"setdefault",
"(",
"data_value",
",",
"[",
"]",
")",
"callbacks",
".",
"append",
"(",
"func",
")"
] | Add a new route.
After registering 'func' for the specified event_type, an
optional data_detail may be provided. By providing an extra
keyword argument, dispatching can occur based on a top-level
key of the data in the event being dispatched. | [
"Add",
"a",
"new",
"route",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L29-L50 | train | 236,637 |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI._make_request | async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],
data: Any, accept: str,
jwt: Opt[str] = None,
oauth_token: Opt[str] = None,
) -> Tuple[bytes, Opt[str]]:
"""Construct and make an HTTP request."""
if oauth_token is not None and jwt is not None:
raise ValueError("Cannot pass both oauth_token and jwt.")
filled_url = sansio.format_url(url, url_vars)
if jwt is not None:
request_headers = sansio.create_headers(
self.requester, accept=accept,
jwt=jwt)
elif oauth_token is not None:
request_headers = sansio.create_headers(
self.requester, accept=accept,
oauth_token=oauth_token)
else:
# fallback to using oauth_token
request_headers = sansio.create_headers(
self.requester, accept=accept,
oauth_token=self.oauth_token)
cached = cacheable = False
# Can't use None as a "no body" sentinel as it's a legitimate JSON type.
if data == b"":
body = b""
request_headers["content-length"] = "0"
if method == "GET" and self._cache is not None:
cacheable = True
try:
etag, last_modified, data, more = self._cache[filled_url]
cached = True
except KeyError:
pass
else:
if etag is not None:
request_headers["if-none-match"] = etag
if last_modified is not None:
request_headers["if-modified-since"] = last_modified
else:
charset = "utf-8"
body = json.dumps(data).encode(charset)
request_headers['content-type'] = f"application/json; charset={charset}"
request_headers['content-length'] = str(len(body))
if self.rate_limit is not None:
self.rate_limit.remaining -= 1
response = await self._request(method, filled_url, request_headers, body)
if not (response[0] == 304 and cached):
data, self.rate_limit, more = sansio.decipher_response(*response)
has_cache_details = ("etag" in response[1]
or "last-modified" in response[1])
if self._cache is not None and cacheable and has_cache_details:
etag = response[1].get("etag")
last_modified = response[1].get("last-modified")
self._cache[filled_url] = etag, last_modified, data, more
return data, more | python | async def _make_request(self, method: str, url: str, url_vars: Dict[str, str],
data: Any, accept: str,
jwt: Opt[str] = None,
oauth_token: Opt[str] = None,
) -> Tuple[bytes, Opt[str]]:
"""Construct and make an HTTP request."""
if oauth_token is not None and jwt is not None:
raise ValueError("Cannot pass both oauth_token and jwt.")
filled_url = sansio.format_url(url, url_vars)
if jwt is not None:
request_headers = sansio.create_headers(
self.requester, accept=accept,
jwt=jwt)
elif oauth_token is not None:
request_headers = sansio.create_headers(
self.requester, accept=accept,
oauth_token=oauth_token)
else:
# fallback to using oauth_token
request_headers = sansio.create_headers(
self.requester, accept=accept,
oauth_token=self.oauth_token)
cached = cacheable = False
# Can't use None as a "no body" sentinel as it's a legitimate JSON type.
if data == b"":
body = b""
request_headers["content-length"] = "0"
if method == "GET" and self._cache is not None:
cacheable = True
try:
etag, last_modified, data, more = self._cache[filled_url]
cached = True
except KeyError:
pass
else:
if etag is not None:
request_headers["if-none-match"] = etag
if last_modified is not None:
request_headers["if-modified-since"] = last_modified
else:
charset = "utf-8"
body = json.dumps(data).encode(charset)
request_headers['content-type'] = f"application/json; charset={charset}"
request_headers['content-length'] = str(len(body))
if self.rate_limit is not None:
self.rate_limit.remaining -= 1
response = await self._request(method, filled_url, request_headers, body)
if not (response[0] == 304 and cached):
data, self.rate_limit, more = sansio.decipher_response(*response)
has_cache_details = ("etag" in response[1]
or "last-modified" in response[1])
if self._cache is not None and cacheable and has_cache_details:
etag = response[1].get("etag")
last_modified = response[1].get("last-modified")
self._cache[filled_url] = etag, last_modified, data, more
return data, more | [
"async",
"def",
"_make_request",
"(",
"self",
",",
"method",
":",
"str",
",",
"url",
":",
"str",
",",
"url_vars",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"data",
":",
"Any",
",",
"accept",
":",
"str",
",",
"jwt",
":",
"Opt",
"[",
"str",
"]",
"=",
"None",
",",
"oauth_token",
":",
"Opt",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Tuple",
"[",
"bytes",
",",
"Opt",
"[",
"str",
"]",
"]",
":",
"if",
"oauth_token",
"is",
"not",
"None",
"and",
"jwt",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot pass both oauth_token and jwt.\"",
")",
"filled_url",
"=",
"sansio",
".",
"format_url",
"(",
"url",
",",
"url_vars",
")",
"if",
"jwt",
"is",
"not",
"None",
":",
"request_headers",
"=",
"sansio",
".",
"create_headers",
"(",
"self",
".",
"requester",
",",
"accept",
"=",
"accept",
",",
"jwt",
"=",
"jwt",
")",
"elif",
"oauth_token",
"is",
"not",
"None",
":",
"request_headers",
"=",
"sansio",
".",
"create_headers",
"(",
"self",
".",
"requester",
",",
"accept",
"=",
"accept",
",",
"oauth_token",
"=",
"oauth_token",
")",
"else",
":",
"# fallback to using oauth_token",
"request_headers",
"=",
"sansio",
".",
"create_headers",
"(",
"self",
".",
"requester",
",",
"accept",
"=",
"accept",
",",
"oauth_token",
"=",
"self",
".",
"oauth_token",
")",
"cached",
"=",
"cacheable",
"=",
"False",
"# Can't use None as a \"no body\" sentinel as it's a legitimate JSON type.",
"if",
"data",
"==",
"b\"\"",
":",
"body",
"=",
"b\"\"",
"request_headers",
"[",
"\"content-length\"",
"]",
"=",
"\"0\"",
"if",
"method",
"==",
"\"GET\"",
"and",
"self",
".",
"_cache",
"is",
"not",
"None",
":",
"cacheable",
"=",
"True",
"try",
":",
"etag",
",",
"last_modified",
",",
"data",
",",
"more",
"=",
"self",
".",
"_cache",
"[",
"filled_url",
"]",
"cached",
"=",
"True",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"etag",
"is",
"not",
"None",
":",
"request_headers",
"[",
"\"if-none-match\"",
"]",
"=",
"etag",
"if",
"last_modified",
"is",
"not",
"None",
":",
"request_headers",
"[",
"\"if-modified-since\"",
"]",
"=",
"last_modified",
"else",
":",
"charset",
"=",
"\"utf-8\"",
"body",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
".",
"encode",
"(",
"charset",
")",
"request_headers",
"[",
"'content-type'",
"]",
"=",
"f\"application/json; charset={charset}\"",
"request_headers",
"[",
"'content-length'",
"]",
"=",
"str",
"(",
"len",
"(",
"body",
")",
")",
"if",
"self",
".",
"rate_limit",
"is",
"not",
"None",
":",
"self",
".",
"rate_limit",
".",
"remaining",
"-=",
"1",
"response",
"=",
"await",
"self",
".",
"_request",
"(",
"method",
",",
"filled_url",
",",
"request_headers",
",",
"body",
")",
"if",
"not",
"(",
"response",
"[",
"0",
"]",
"==",
"304",
"and",
"cached",
")",
":",
"data",
",",
"self",
".",
"rate_limit",
",",
"more",
"=",
"sansio",
".",
"decipher_response",
"(",
"*",
"response",
")",
"has_cache_details",
"=",
"(",
"\"etag\"",
"in",
"response",
"[",
"1",
"]",
"or",
"\"last-modified\"",
"in",
"response",
"[",
"1",
"]",
")",
"if",
"self",
".",
"_cache",
"is",
"not",
"None",
"and",
"cacheable",
"and",
"has_cache_details",
":",
"etag",
"=",
"response",
"[",
"1",
"]",
".",
"get",
"(",
"\"etag\"",
")",
"last_modified",
"=",
"response",
"[",
"1",
"]",
".",
"get",
"(",
"\"last-modified\"",
")",
"self",
".",
"_cache",
"[",
"filled_url",
"]",
"=",
"etag",
",",
"last_modified",
",",
"data",
",",
"more",
"return",
"data",
",",
"more"
] | Construct and make an HTTP request. | [
"Construct",
"and",
"make",
"an",
"HTTP",
"request",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L34-L89 | train | 236,638 |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI.getitem | async def getitem(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> Any:
"""Send a GET request for a single item to the specified endpoint."""
data, _ = await self._make_request("GET", url, url_vars, b"", accept,
jwt=jwt, oauth_token=oauth_token)
return data | python | async def getitem(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> Any:
"""Send a GET request for a single item to the specified endpoint."""
data, _ = await self._make_request("GET", url, url_vars, b"", accept,
jwt=jwt, oauth_token=oauth_token)
return data | [
"async",
"def",
"getitem",
"(",
"self",
",",
"url",
":",
"str",
",",
"url_vars",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
",",
"*",
",",
"accept",
":",
"str",
"=",
"sansio",
".",
"accept_format",
"(",
")",
",",
"jwt",
":",
"Opt",
"[",
"str",
"]",
"=",
"None",
",",
"oauth_token",
":",
"Opt",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Any",
":",
"data",
",",
"_",
"=",
"await",
"self",
".",
"_make_request",
"(",
"\"GET\"",
",",
"url",
",",
"url_vars",
",",
"b\"\"",
",",
"accept",
",",
"jwt",
"=",
"jwt",
",",
"oauth_token",
"=",
"oauth_token",
")",
"return",
"data"
] | Send a GET request for a single item to the specified endpoint. | [
"Send",
"a",
"GET",
"request",
"for",
"a",
"single",
"item",
"to",
"the",
"specified",
"endpoint",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L91-L100 | train | 236,639 |
brettcannon/gidgethub | gidgethub/abc.py | GitHubAPI.getiter | async def getiter(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> AsyncGenerator[Any, None]:
"""Return an async iterable for all the items at a specified endpoint."""
data, more = await self._make_request("GET", url, url_vars, b"", accept,
jwt=jwt, oauth_token=oauth_token)
if isinstance(data, dict) and "items" in data:
data = data["items"]
for item in data:
yield item
if more:
# `yield from` is not supported in coroutines.
async for item in self.getiter(more, url_vars, accept=accept,
jwt=jwt, oauth_token=oauth_token):
yield item | python | async def getiter(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> AsyncGenerator[Any, None]:
"""Return an async iterable for all the items at a specified endpoint."""
data, more = await self._make_request("GET", url, url_vars, b"", accept,
jwt=jwt, oauth_token=oauth_token)
if isinstance(data, dict) and "items" in data:
data = data["items"]
for item in data:
yield item
if more:
# `yield from` is not supported in coroutines.
async for item in self.getiter(more, url_vars, accept=accept,
jwt=jwt, oauth_token=oauth_token):
yield item | [
"async",
"def",
"getiter",
"(",
"self",
",",
"url",
":",
"str",
",",
"url_vars",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
",",
"*",
",",
"accept",
":",
"str",
"=",
"sansio",
".",
"accept_format",
"(",
")",
",",
"jwt",
":",
"Opt",
"[",
"str",
"]",
"=",
"None",
",",
"oauth_token",
":",
"Opt",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"AsyncGenerator",
"[",
"Any",
",",
"None",
"]",
":",
"data",
",",
"more",
"=",
"await",
"self",
".",
"_make_request",
"(",
"\"GET\"",
",",
"url",
",",
"url_vars",
",",
"b\"\"",
",",
"accept",
",",
"jwt",
"=",
"jwt",
",",
"oauth_token",
"=",
"oauth_token",
")",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
"and",
"\"items\"",
"in",
"data",
":",
"data",
"=",
"data",
"[",
"\"items\"",
"]",
"for",
"item",
"in",
"data",
":",
"yield",
"item",
"if",
"more",
":",
"# `yield from` is not supported in coroutines.",
"async",
"for",
"item",
"in",
"self",
".",
"getiter",
"(",
"more",
",",
"url_vars",
",",
"accept",
"=",
"accept",
",",
"jwt",
"=",
"jwt",
",",
"oauth_token",
"=",
"oauth_token",
")",
":",
"yield",
"item"
] | Return an async iterable for all the items at a specified endpoint. | [
"Return",
"an",
"async",
"iterable",
"for",
"all",
"the",
"items",
"at",
"a",
"specified",
"endpoint",
"."
] | 24feb6c35bba3966c6cc9ec2896729578f6d7ccc | https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L102-L120 | train | 236,640 |
rkargon/pixelsorter | pixelsorter/images2gif.py | NeuQuant.quantize | def quantize(self, image):
""" Use a kdtree to quickly find the closest palette colors for the pixels """
if get_cKDTree():
return self.quantize_with_scipy(image)
else:
print('Scipy not available, falling back to slower version.')
return self.quantize_without_scipy(image) | python | def quantize(self, image):
""" Use a kdtree to quickly find the closest palette colors for the pixels """
if get_cKDTree():
return self.quantize_with_scipy(image)
else:
print('Scipy not available, falling back to slower version.')
return self.quantize_without_scipy(image) | [
"def",
"quantize",
"(",
"self",
",",
"image",
")",
":",
"if",
"get_cKDTree",
"(",
")",
":",
"return",
"self",
".",
"quantize_with_scipy",
"(",
"image",
")",
"else",
":",
"print",
"(",
"'Scipy not available, falling back to slower version.'",
")",
"return",
"self",
".",
"quantize_without_scipy",
"(",
"image",
")"
] | Use a kdtree to quickly find the closest palette colors for the pixels | [
"Use",
"a",
"kdtree",
"to",
"quickly",
"find",
"the",
"closest",
"palette",
"colors",
"for",
"the",
"pixels"
] | 0775d1e487fbcb023e411e1818ba3290b0e8665e | https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1017-L1023 | train | 236,641 |
rkargon/pixelsorter | pixelsorter/images2gif.py | NeuQuant.inxsearch | def inxsearch(self, r, g, b):
"""Search for BGR values 0..255 and return colour index"""
dists = (self.colormap[:, :3] - np.array([r, g, b]))
a = np.argmin((dists * dists).sum(1))
return a | python | def inxsearch(self, r, g, b):
"""Search for BGR values 0..255 and return colour index"""
dists = (self.colormap[:, :3] - np.array([r, g, b]))
a = np.argmin((dists * dists).sum(1))
return a | [
"def",
"inxsearch",
"(",
"self",
",",
"r",
",",
"g",
",",
"b",
")",
":",
"dists",
"=",
"(",
"self",
".",
"colormap",
"[",
":",
",",
":",
"3",
"]",
"-",
"np",
".",
"array",
"(",
"[",
"r",
",",
"g",
",",
"b",
"]",
")",
")",
"a",
"=",
"np",
".",
"argmin",
"(",
"(",
"dists",
"*",
"dists",
")",
".",
"sum",
"(",
"1",
")",
")",
"return",
"a"
] | Search for BGR values 0..255 and return colour index | [
"Search",
"for",
"BGR",
"values",
"0",
"..",
"255",
"and",
"return",
"colour",
"index"
] | 0775d1e487fbcb023e411e1818ba3290b0e8665e | https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1061-L1065 | train | 236,642 |
European-XFEL/karabo-bridge-py | karabo_bridge/cli/glimpse.py | gen_filename | def gen_filename(endpoint):
"""Generate a filename from endpoint with timestamp.
return: str
hostname_port_YearMonthDay_HourMinSecFrac.h5
"""
now = datetime.now().strftime('%Y%m%d_%H%M%S%f')[:-4]
base = endpoint.split('://', 1)[1]
if base.startswith('localhost:'):
base = gethostname().split('.')[0] + base[9:]
base = base.replace(':', '_').replace('/', '_')
return '{}_{}.h5'.format(base, now) | python | def gen_filename(endpoint):
"""Generate a filename from endpoint with timestamp.
return: str
hostname_port_YearMonthDay_HourMinSecFrac.h5
"""
now = datetime.now().strftime('%Y%m%d_%H%M%S%f')[:-4]
base = endpoint.split('://', 1)[1]
if base.startswith('localhost:'):
base = gethostname().split('.')[0] + base[9:]
base = base.replace(':', '_').replace('/', '_')
return '{}_{}.h5'.format(base, now) | [
"def",
"gen_filename",
"(",
"endpoint",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y%m%d_%H%M%S%f'",
")",
"[",
":",
"-",
"4",
"]",
"base",
"=",
"endpoint",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"[",
"1",
"]",
"if",
"base",
".",
"startswith",
"(",
"'localhost:'",
")",
":",
"base",
"=",
"gethostname",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"+",
"base",
"[",
"9",
":",
"]",
"base",
"=",
"base",
".",
"replace",
"(",
"':'",
",",
"'_'",
")",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"return",
"'{}_{}.h5'",
".",
"format",
"(",
"base",
",",
"now",
")"
] | Generate a filename from endpoint with timestamp.
return: str
hostname_port_YearMonthDay_HourMinSecFrac.h5 | [
"Generate",
"a",
"filename",
"from",
"endpoint",
"with",
"timestamp",
"."
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L15-L26 | train | 236,643 |
European-XFEL/karabo-bridge-py | karabo_bridge/cli/glimpse.py | dict_to_hdf5 | def dict_to_hdf5(dic, endpoint):
"""Dump a dict to an HDF5 file.
"""
filename = gen_filename(endpoint)
with h5py.File(filename, 'w') as handler:
walk_dict_to_hdf5(dic, handler)
print('dumped to', filename) | python | def dict_to_hdf5(dic, endpoint):
"""Dump a dict to an HDF5 file.
"""
filename = gen_filename(endpoint)
with h5py.File(filename, 'w') as handler:
walk_dict_to_hdf5(dic, handler)
print('dumped to', filename) | [
"def",
"dict_to_hdf5",
"(",
"dic",
",",
"endpoint",
")",
":",
"filename",
"=",
"gen_filename",
"(",
"endpoint",
")",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"handler",
":",
"walk_dict_to_hdf5",
"(",
"dic",
",",
"handler",
")",
"print",
"(",
"'dumped to'",
",",
"filename",
")"
] | Dump a dict to an HDF5 file. | [
"Dump",
"a",
"dict",
"to",
"an",
"HDF5",
"file",
"."
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L29-L35 | train | 236,644 |
European-XFEL/karabo-bridge-py | karabo_bridge/cli/glimpse.py | hdf5_to_dict | def hdf5_to_dict(filepath, group='/'):
"""load the content of an hdf5 file to a dict.
# TODO: how to split domain_type_dev : parameter : value ?
"""
if not h5py.is_hdf5(filepath):
raise RuntimeError(filepath, 'is not a valid HDF5 file.')
with h5py.File(filepath, 'r') as handler:
dic = walk_hdf5_to_dict(handler[group])
return dic | python | def hdf5_to_dict(filepath, group='/'):
"""load the content of an hdf5 file to a dict.
# TODO: how to split domain_type_dev : parameter : value ?
"""
if not h5py.is_hdf5(filepath):
raise RuntimeError(filepath, 'is not a valid HDF5 file.')
with h5py.File(filepath, 'r') as handler:
dic = walk_hdf5_to_dict(handler[group])
return dic | [
"def",
"hdf5_to_dict",
"(",
"filepath",
",",
"group",
"=",
"'/'",
")",
":",
"if",
"not",
"h5py",
".",
"is_hdf5",
"(",
"filepath",
")",
":",
"raise",
"RuntimeError",
"(",
"filepath",
",",
"'is not a valid HDF5 file.'",
")",
"with",
"h5py",
".",
"File",
"(",
"filepath",
",",
"'r'",
")",
"as",
"handler",
":",
"dic",
"=",
"walk_hdf5_to_dict",
"(",
"handler",
"[",
"group",
"]",
")",
"return",
"dic"
] | load the content of an hdf5 file to a dict.
# TODO: how to split domain_type_dev : parameter : value ? | [
"load",
"the",
"content",
"of",
"an",
"hdf5",
"file",
"to",
"a",
"dict",
"."
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L38-L48 | train | 236,645 |
European-XFEL/karabo-bridge-py | karabo_bridge/cli/glimpse.py | print_one_train | def print_one_train(client, verbosity=0):
"""Retrieve data for one train and print it.
Returns the (data, metadata) dicts from the client.
This is used by the -glimpse and -monitor command line tools.
"""
ts_before = time()
data, meta = client.next()
ts_after = time()
if not data:
print("Empty data")
return
train_id = list(meta.values())[0].get('timestamp.tid', 0)
print("Train ID:", train_id, "--------------------------")
delta = ts_after - ts_before
print('Data from {} sources, REQ-REP took {:.2f} ms'
.format(len(data), delta))
print()
for i, (source, src_data) in enumerate(sorted(data.items()), start=1):
src_metadata = meta.get(source, {})
tid = src_metadata.get('timestamp.tid', 0)
print("Source {}: {!r} @ {}".format(i, source, tid))
try:
ts = src_metadata['timestamp']
except KeyError:
print("No timestamp")
else:
dt = strftime('%Y-%m-%d %H:%M:%S', localtime(ts))
delay = (ts_after - ts) * 1000
print('timestamp: {} ({}) | delay: {:.2f} ms'
.format(dt, ts, delay))
if verbosity < 1:
print("- data:", sorted(src_data))
print("- metadata:", sorted(src_metadata))
else:
print('data:')
pretty_print(src_data, verbosity=verbosity - 1)
if src_metadata:
print('metadata:')
pretty_print(src_metadata)
print()
return data, meta | python | def print_one_train(client, verbosity=0):
"""Retrieve data for one train and print it.
Returns the (data, metadata) dicts from the client.
This is used by the -glimpse and -monitor command line tools.
"""
ts_before = time()
data, meta = client.next()
ts_after = time()
if not data:
print("Empty data")
return
train_id = list(meta.values())[0].get('timestamp.tid', 0)
print("Train ID:", train_id, "--------------------------")
delta = ts_after - ts_before
print('Data from {} sources, REQ-REP took {:.2f} ms'
.format(len(data), delta))
print()
for i, (source, src_data) in enumerate(sorted(data.items()), start=1):
src_metadata = meta.get(source, {})
tid = src_metadata.get('timestamp.tid', 0)
print("Source {}: {!r} @ {}".format(i, source, tid))
try:
ts = src_metadata['timestamp']
except KeyError:
print("No timestamp")
else:
dt = strftime('%Y-%m-%d %H:%M:%S', localtime(ts))
delay = (ts_after - ts) * 1000
print('timestamp: {} ({}) | delay: {:.2f} ms'
.format(dt, ts, delay))
if verbosity < 1:
print("- data:", sorted(src_data))
print("- metadata:", sorted(src_metadata))
else:
print('data:')
pretty_print(src_data, verbosity=verbosity - 1)
if src_metadata:
print('metadata:')
pretty_print(src_metadata)
print()
return data, meta | [
"def",
"print_one_train",
"(",
"client",
",",
"verbosity",
"=",
"0",
")",
":",
"ts_before",
"=",
"time",
"(",
")",
"data",
",",
"meta",
"=",
"client",
".",
"next",
"(",
")",
"ts_after",
"=",
"time",
"(",
")",
"if",
"not",
"data",
":",
"print",
"(",
"\"Empty data\"",
")",
"return",
"train_id",
"=",
"list",
"(",
"meta",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'timestamp.tid'",
",",
"0",
")",
"print",
"(",
"\"Train ID:\"",
",",
"train_id",
",",
"\"--------------------------\"",
")",
"delta",
"=",
"ts_after",
"-",
"ts_before",
"print",
"(",
"'Data from {} sources, REQ-REP took {:.2f} ms'",
".",
"format",
"(",
"len",
"(",
"data",
")",
",",
"delta",
")",
")",
"print",
"(",
")",
"for",
"i",
",",
"(",
"source",
",",
"src_data",
")",
"in",
"enumerate",
"(",
"sorted",
"(",
"data",
".",
"items",
"(",
")",
")",
",",
"start",
"=",
"1",
")",
":",
"src_metadata",
"=",
"meta",
".",
"get",
"(",
"source",
",",
"{",
"}",
")",
"tid",
"=",
"src_metadata",
".",
"get",
"(",
"'timestamp.tid'",
",",
"0",
")",
"print",
"(",
"\"Source {}: {!r} @ {}\"",
".",
"format",
"(",
"i",
",",
"source",
",",
"tid",
")",
")",
"try",
":",
"ts",
"=",
"src_metadata",
"[",
"'timestamp'",
"]",
"except",
"KeyError",
":",
"print",
"(",
"\"No timestamp\"",
")",
"else",
":",
"dt",
"=",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"localtime",
"(",
"ts",
")",
")",
"delay",
"=",
"(",
"ts_after",
"-",
"ts",
")",
"*",
"1000",
"print",
"(",
"'timestamp: {} ({}) | delay: {:.2f} ms'",
".",
"format",
"(",
"dt",
",",
"ts",
",",
"delay",
")",
")",
"if",
"verbosity",
"<",
"1",
":",
"print",
"(",
"\"- data:\"",
",",
"sorted",
"(",
"src_data",
")",
")",
"print",
"(",
"\"- metadata:\"",
",",
"sorted",
"(",
"src_metadata",
")",
")",
"else",
":",
"print",
"(",
"'data:'",
")",
"pretty_print",
"(",
"src_data",
",",
"verbosity",
"=",
"verbosity",
"-",
"1",
")",
"if",
"src_metadata",
":",
"print",
"(",
"'metadata:'",
")",
"pretty_print",
"(",
"src_metadata",
")",
"print",
"(",
")",
"return",
"data",
",",
"meta"
] | Retrieve data for one train and print it.
Returns the (data, metadata) dicts from the client.
This is used by the -glimpse and -monitor command line tools. | [
"Retrieve",
"data",
"for",
"one",
"train",
"and",
"print",
"it",
"."
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L92-L140 | train | 236,646 |
European-XFEL/karabo-bridge-py | karabo_bridge/cli/glimpse.py | pretty_print | def pretty_print(d, ind='', verbosity=0):
"""Pretty print a data dictionary from the bridge client
"""
assert isinstance(d, dict)
for k, v in sorted(d.items()):
str_base = '{} - [{}] {}'.format(ind, type(v).__name__, k)
if isinstance(v, dict):
print(str_base.replace('-', '+', 1))
pretty_print(v, ind=ind+' ', verbosity=verbosity)
continue
elif isinstance(v, np.ndarray):
node = '{}, {}, {}'.format(str_base, v.dtype, v.shape)
if verbosity >= 2:
node += '\n{}'.format(v)
elif isinstance(v, Sequence):
if v and isinstance(v, (list, tuple)):
itemtype = ' of ' + type(v[0]).__name__
pos = str_base.find(']')
str_base = str_base[:pos] + itemtype + str_base[pos:]
node = '{}, {}'.format(str_base, v)
if verbosity < 1 and len(node) > 80:
node = node[:77] + '...'
else:
node = '{}, {}'.format(str_base, v)
print(node) | python | def pretty_print(d, ind='', verbosity=0):
"""Pretty print a data dictionary from the bridge client
"""
assert isinstance(d, dict)
for k, v in sorted(d.items()):
str_base = '{} - [{}] {}'.format(ind, type(v).__name__, k)
if isinstance(v, dict):
print(str_base.replace('-', '+', 1))
pretty_print(v, ind=ind+' ', verbosity=verbosity)
continue
elif isinstance(v, np.ndarray):
node = '{}, {}, {}'.format(str_base, v.dtype, v.shape)
if verbosity >= 2:
node += '\n{}'.format(v)
elif isinstance(v, Sequence):
if v and isinstance(v, (list, tuple)):
itemtype = ' of ' + type(v[0]).__name__
pos = str_base.find(']')
str_base = str_base[:pos] + itemtype + str_base[pos:]
node = '{}, {}'.format(str_base, v)
if verbosity < 1 and len(node) > 80:
node = node[:77] + '...'
else:
node = '{}, {}'.format(str_base, v)
print(node) | [
"def",
"pretty_print",
"(",
"d",
",",
"ind",
"=",
"''",
",",
"verbosity",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"d",
",",
"dict",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"d",
".",
"items",
"(",
")",
")",
":",
"str_base",
"=",
"'{} - [{}] {}'",
".",
"format",
"(",
"ind",
",",
"type",
"(",
"v",
")",
".",
"__name__",
",",
"k",
")",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"print",
"(",
"str_base",
".",
"replace",
"(",
"'-'",
",",
"'+'",
",",
"1",
")",
")",
"pretty_print",
"(",
"v",
",",
"ind",
"=",
"ind",
"+",
"' '",
",",
"verbosity",
"=",
"verbosity",
")",
"continue",
"elif",
"isinstance",
"(",
"v",
",",
"np",
".",
"ndarray",
")",
":",
"node",
"=",
"'{}, {}, {}'",
".",
"format",
"(",
"str_base",
",",
"v",
".",
"dtype",
",",
"v",
".",
"shape",
")",
"if",
"verbosity",
">=",
"2",
":",
"node",
"+=",
"'\\n{}'",
".",
"format",
"(",
"v",
")",
"elif",
"isinstance",
"(",
"v",
",",
"Sequence",
")",
":",
"if",
"v",
"and",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"itemtype",
"=",
"' of '",
"+",
"type",
"(",
"v",
"[",
"0",
"]",
")",
".",
"__name__",
"pos",
"=",
"str_base",
".",
"find",
"(",
"']'",
")",
"str_base",
"=",
"str_base",
"[",
":",
"pos",
"]",
"+",
"itemtype",
"+",
"str_base",
"[",
"pos",
":",
"]",
"node",
"=",
"'{}, {}'",
".",
"format",
"(",
"str_base",
",",
"v",
")",
"if",
"verbosity",
"<",
"1",
"and",
"len",
"(",
"node",
")",
">",
"80",
":",
"node",
"=",
"node",
"[",
":",
"77",
"]",
"+",
"'...'",
"else",
":",
"node",
"=",
"'{}, {}'",
".",
"format",
"(",
"str_base",
",",
"v",
")",
"print",
"(",
"node",
")"
] | Pretty print a data dictionary from the bridge client | [
"Pretty",
"print",
"a",
"data",
"dictionary",
"from",
"the",
"bridge",
"client"
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L143-L168 | train | 236,647 |
European-XFEL/karabo-bridge-py | karabo_bridge/simulation.py | start_gen | def start_gen(port, ser='msgpack', version='2.2', detector='AGIPD',
raw=False, nsources=1, datagen='random', *,
debug=True):
""""Karabo bridge server simulation.
Simulate a Karabo Bridge server and send random data from a detector,
either AGIPD or LPD.
Parameters
----------
port: str
The port to on which the server is bound.
ser: str, optional
The serialization algorithm, default is msgpack.
version: str, optional
The container version of the serialized data.
detector: str, optional
The data format to send, default is AGIPD detector.
raw: bool, optional
Generate raw data output if True, else CORRECTED. Default is False.
nsources: int, optional
Number of sources.
datagen: string, optional
Generator function used to generate detector data. Default is random.
"""
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.setsockopt(zmq.LINGER, 0)
socket.bind('tcp://*:{}'.format(port))
if ser != 'msgpack':
raise ValueError("Unknown serialisation format %s" % ser)
serialize = partial(msgpack.dumps, use_bin_type=True)
det = Detector.getDetector(detector, raw=raw, gen=datagen)
generator = generate(det, nsources)
print('Simulated Karabo-bridge server started on:\ntcp://{}:{}'.format(
uname().nodename, port))
t_prev = time()
n = 0
try:
while True:
msg = socket.recv()
if msg == b'next':
train = next(generator)
msg = containize(train, ser, serialize, version)
socket.send_multipart(msg, copy=False)
if debug:
print('Server : emitted train:',
train[1][list(train[1].keys())[0]]['timestamp.tid'])
n += 1
if n % TIMING_INTERVAL == 0:
t_now = time()
print('Sent {} trains in {:.2f} seconds ({:.2f} Hz)'
''.format(TIMING_INTERVAL, t_now - t_prev,
TIMING_INTERVAL / (t_now - t_prev)))
t_prev = t_now
else:
print('wrong request')
break
except KeyboardInterrupt:
print('\nStopped.')
finally:
socket.close()
context.destroy() | python | def start_gen(port, ser='msgpack', version='2.2', detector='AGIPD',
raw=False, nsources=1, datagen='random', *,
debug=True):
""""Karabo bridge server simulation.
Simulate a Karabo Bridge server and send random data from a detector,
either AGIPD or LPD.
Parameters
----------
port: str
The port to on which the server is bound.
ser: str, optional
The serialization algorithm, default is msgpack.
version: str, optional
The container version of the serialized data.
detector: str, optional
The data format to send, default is AGIPD detector.
raw: bool, optional
Generate raw data output if True, else CORRECTED. Default is False.
nsources: int, optional
Number of sources.
datagen: string, optional
Generator function used to generate detector data. Default is random.
"""
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.setsockopt(zmq.LINGER, 0)
socket.bind('tcp://*:{}'.format(port))
if ser != 'msgpack':
raise ValueError("Unknown serialisation format %s" % ser)
serialize = partial(msgpack.dumps, use_bin_type=True)
det = Detector.getDetector(detector, raw=raw, gen=datagen)
generator = generate(det, nsources)
print('Simulated Karabo-bridge server started on:\ntcp://{}:{}'.format(
uname().nodename, port))
t_prev = time()
n = 0
try:
while True:
msg = socket.recv()
if msg == b'next':
train = next(generator)
msg = containize(train, ser, serialize, version)
socket.send_multipart(msg, copy=False)
if debug:
print('Server : emitted train:',
train[1][list(train[1].keys())[0]]['timestamp.tid'])
n += 1
if n % TIMING_INTERVAL == 0:
t_now = time()
print('Sent {} trains in {:.2f} seconds ({:.2f} Hz)'
''.format(TIMING_INTERVAL, t_now - t_prev,
TIMING_INTERVAL / (t_now - t_prev)))
t_prev = t_now
else:
print('wrong request')
break
except KeyboardInterrupt:
print('\nStopped.')
finally:
socket.close()
context.destroy() | [
"def",
"start_gen",
"(",
"port",
",",
"ser",
"=",
"'msgpack'",
",",
"version",
"=",
"'2.2'",
",",
"detector",
"=",
"'AGIPD'",
",",
"raw",
"=",
"False",
",",
"nsources",
"=",
"1",
",",
"datagen",
"=",
"'random'",
",",
"*",
",",
"debug",
"=",
"True",
")",
":",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"socket",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"REP",
")",
"socket",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"0",
")",
"socket",
".",
"bind",
"(",
"'tcp://*:{}'",
".",
"format",
"(",
"port",
")",
")",
"if",
"ser",
"!=",
"'msgpack'",
":",
"raise",
"ValueError",
"(",
"\"Unknown serialisation format %s\"",
"%",
"ser",
")",
"serialize",
"=",
"partial",
"(",
"msgpack",
".",
"dumps",
",",
"use_bin_type",
"=",
"True",
")",
"det",
"=",
"Detector",
".",
"getDetector",
"(",
"detector",
",",
"raw",
"=",
"raw",
",",
"gen",
"=",
"datagen",
")",
"generator",
"=",
"generate",
"(",
"det",
",",
"nsources",
")",
"print",
"(",
"'Simulated Karabo-bridge server started on:\\ntcp://{}:{}'",
".",
"format",
"(",
"uname",
"(",
")",
".",
"nodename",
",",
"port",
")",
")",
"t_prev",
"=",
"time",
"(",
")",
"n",
"=",
"0",
"try",
":",
"while",
"True",
":",
"msg",
"=",
"socket",
".",
"recv",
"(",
")",
"if",
"msg",
"==",
"b'next'",
":",
"train",
"=",
"next",
"(",
"generator",
")",
"msg",
"=",
"containize",
"(",
"train",
",",
"ser",
",",
"serialize",
",",
"version",
")",
"socket",
".",
"send_multipart",
"(",
"msg",
",",
"copy",
"=",
"False",
")",
"if",
"debug",
":",
"print",
"(",
"'Server : emitted train:'",
",",
"train",
"[",
"1",
"]",
"[",
"list",
"(",
"train",
"[",
"1",
"]",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"]",
"[",
"'timestamp.tid'",
"]",
")",
"n",
"+=",
"1",
"if",
"n",
"%",
"TIMING_INTERVAL",
"==",
"0",
":",
"t_now",
"=",
"time",
"(",
")",
"print",
"(",
"'Sent {} trains in {:.2f} seconds ({:.2f} Hz)'",
"''",
".",
"format",
"(",
"TIMING_INTERVAL",
",",
"t_now",
"-",
"t_prev",
",",
"TIMING_INTERVAL",
"/",
"(",
"t_now",
"-",
"t_prev",
")",
")",
")",
"t_prev",
"=",
"t_now",
"else",
":",
"print",
"(",
"'wrong request'",
")",
"break",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"'\\nStopped.'",
")",
"finally",
":",
"socket",
".",
"close",
"(",
")",
"context",
".",
"destroy",
"(",
")"
] | Karabo bridge server simulation.
Simulate a Karabo Bridge server and send random data from a detector,
either AGIPD or LPD.
Parameters
----------
port: str
The port to on which the server is bound.
ser: str, optional
The serialization algorithm, default is msgpack.
version: str, optional
The container version of the serialized data.
detector: str, optional
The data format to send, default is AGIPD detector.
raw: bool, optional
Generate raw data output if True, else CORRECTED. Default is False.
nsources: int, optional
Number of sources.
datagen: string, optional
Generator function used to generate detector data. Default is random. | [
"Karabo",
"bridge",
"server",
"simulation",
"."
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/simulation.py#L262-L328 | train | 236,648 |
European-XFEL/karabo-bridge-py | karabo_bridge/client.py | Client.next | def next(self):
"""Request next data container.
This function call is blocking.
Returns
-------
data : dict
The data for this train, keyed by source name.
meta : dict
The metadata for this train, keyed by source name.
This dictionary is populated for protocol version 1.0 and 2.2.
For other protocol versions, metadata information is available in
`data` dict.
Raises
------
TimeoutError
If timeout is reached before receiving data.
"""
if self._pattern == zmq.REQ and not self._recv_ready:
self._socket.send(b'next')
self._recv_ready = True
try:
msg = self._socket.recv_multipart(copy=False)
except zmq.error.Again:
raise TimeoutError(
'No data received from {} in the last {} ms'.format(
self._socket.getsockopt_string(zmq.LAST_ENDPOINT),
self._socket.getsockopt(zmq.RCVTIMEO)))
self._recv_ready = False
return self._deserialize(msg) | python | def next(self):
"""Request next data container.
This function call is blocking.
Returns
-------
data : dict
The data for this train, keyed by source name.
meta : dict
The metadata for this train, keyed by source name.
This dictionary is populated for protocol version 1.0 and 2.2.
For other protocol versions, metadata information is available in
`data` dict.
Raises
------
TimeoutError
If timeout is reached before receiving data.
"""
if self._pattern == zmq.REQ and not self._recv_ready:
self._socket.send(b'next')
self._recv_ready = True
try:
msg = self._socket.recv_multipart(copy=False)
except zmq.error.Again:
raise TimeoutError(
'No data received from {} in the last {} ms'.format(
self._socket.getsockopt_string(zmq.LAST_ENDPOINT),
self._socket.getsockopt(zmq.RCVTIMEO)))
self._recv_ready = False
return self._deserialize(msg) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pattern",
"==",
"zmq",
".",
"REQ",
"and",
"not",
"self",
".",
"_recv_ready",
":",
"self",
".",
"_socket",
".",
"send",
"(",
"b'next'",
")",
"self",
".",
"_recv_ready",
"=",
"True",
"try",
":",
"msg",
"=",
"self",
".",
"_socket",
".",
"recv_multipart",
"(",
"copy",
"=",
"False",
")",
"except",
"zmq",
".",
"error",
".",
"Again",
":",
"raise",
"TimeoutError",
"(",
"'No data received from {} in the last {} ms'",
".",
"format",
"(",
"self",
".",
"_socket",
".",
"getsockopt_string",
"(",
"zmq",
".",
"LAST_ENDPOINT",
")",
",",
"self",
".",
"_socket",
".",
"getsockopt",
"(",
"zmq",
".",
"RCVTIMEO",
")",
")",
")",
"self",
".",
"_recv_ready",
"=",
"False",
"return",
"self",
".",
"_deserialize",
"(",
"msg",
")"
] | Request next data container.
This function call is blocking.
Returns
-------
data : dict
The data for this train, keyed by source name.
meta : dict
The metadata for this train, keyed by source name.
This dictionary is populated for protocol version 1.0 and 2.2.
For other protocol versions, metadata information is available in
`data` dict.
Raises
------
TimeoutError
If timeout is reached before receiving data. | [
"Request",
"next",
"data",
"container",
"."
] | ca20d72b8beb0039649d10cb01d027db42efd91c | https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/client.py#L90-L122 | train | 236,649 |
materialsvirtuallab/monty | monty/io.py | zopen | def zopen(filename, *args, **kwargs):
"""
This function wraps around the bz2, gzip and standard python's open
function to deal intelligently with bzipped, gzipped or standard text
files.
Args:
filename (str/Path): filename or pathlib.Path.
\*args: Standard args for python open(..). E.g., 'r' for read, 'w' for
write.
\*\*kwargs: Standard kwargs for python open(..).
Returns:
File-like object. Supports with context.
"""
if Path is not None and isinstance(filename, Path):
filename = str(filename)
name, ext = os.path.splitext(filename)
ext = ext.upper()
if ext == ".BZ2":
if PY_VERSION[0] >= 3:
return bz2.open(filename, *args, **kwargs)
else:
args = list(args)
if len(args) > 0:
args[0] = "".join([c for c in args[0] if c != "t"])
if "mode" in kwargs:
kwargs["mode"] = "".join([c for c in kwargs["mode"]
if c != "t"])
return bz2.BZ2File(filename, *args, **kwargs)
elif ext in (".GZ", ".Z"):
return gzip.open(filename, *args, **kwargs)
else:
return io.open(filename, *args, **kwargs) | python | def zopen(filename, *args, **kwargs):
"""
This function wraps around the bz2, gzip and standard python's open
function to deal intelligently with bzipped, gzipped or standard text
files.
Args:
filename (str/Path): filename or pathlib.Path.
\*args: Standard args for python open(..). E.g., 'r' for read, 'w' for
write.
\*\*kwargs: Standard kwargs for python open(..).
Returns:
File-like object. Supports with context.
"""
if Path is not None and isinstance(filename, Path):
filename = str(filename)
name, ext = os.path.splitext(filename)
ext = ext.upper()
if ext == ".BZ2":
if PY_VERSION[0] >= 3:
return bz2.open(filename, *args, **kwargs)
else:
args = list(args)
if len(args) > 0:
args[0] = "".join([c for c in args[0] if c != "t"])
if "mode" in kwargs:
kwargs["mode"] = "".join([c for c in kwargs["mode"]
if c != "t"])
return bz2.BZ2File(filename, *args, **kwargs)
elif ext in (".GZ", ".Z"):
return gzip.open(filename, *args, **kwargs)
else:
return io.open(filename, *args, **kwargs) | [
"def",
"zopen",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"Path",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"filename",
",",
"Path",
")",
":",
"filename",
"=",
"str",
"(",
"filename",
")",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"ext",
"=",
"ext",
".",
"upper",
"(",
")",
"if",
"ext",
"==",
"\".BZ2\"",
":",
"if",
"PY_VERSION",
"[",
"0",
"]",
">=",
"3",
":",
"return",
"bz2",
".",
"open",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"args",
"=",
"list",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"args",
"[",
"0",
"]",
"=",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"args",
"[",
"0",
"]",
"if",
"c",
"!=",
"\"t\"",
"]",
")",
"if",
"\"mode\"",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"mode\"",
"]",
"=",
"\"\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"kwargs",
"[",
"\"mode\"",
"]",
"if",
"c",
"!=",
"\"t\"",
"]",
")",
"return",
"bz2",
".",
"BZ2File",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"elif",
"ext",
"in",
"(",
"\".GZ\"",
",",
"\".Z\"",
")",
":",
"return",
"gzip",
".",
"open",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"io",
".",
"open",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This function wraps around the bz2, gzip and standard python's open
function to deal intelligently with bzipped, gzipped or standard text
files.
Args:
filename (str/Path): filename or pathlib.Path.
\*args: Standard args for python open(..). E.g., 'r' for read, 'w' for
write.
\*\*kwargs: Standard kwargs for python open(..).
Returns:
File-like object. Supports with context. | [
"This",
"function",
"wraps",
"around",
"the",
"bz2",
"gzip",
"and",
"standard",
"python",
"s",
"open",
"function",
"to",
"deal",
"intelligently",
"with",
"bzipped",
"gzipped",
"or",
"standard",
"text",
"files",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L38-L72 | train | 236,650 |
materialsvirtuallab/monty | monty/io.py | reverse_readline | def reverse_readline(m_file, blk_size=4096, max_mem=4000000):
"""
Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.
http://code.activestate.com/recipes/439045-read-a-text-file-backwards
-yet-another-implementat/
Reads file forwards and reverses in memory for files smaller than the
max_mem parameter, or for gzip files where reverse seeks are not supported.
Files larger than max_mem are dynamically read backwards.
Args:
m_file (File): File stream to read (backwards)
blk_size (int): The buffer size. Defaults to 4096.
max_mem (int): The maximum amount of memory to involve in this
operation. This is used to determine when to reverse a file
in-memory versus seeking portions of a file. For bz2 files,
this sets the maximum block size.
Returns:
Generator that returns lines from the file. Similar behavior to the
file.readline() method, except the lines are returned from the back
of the file.
"""
# Check if the file stream is a bit stream or not
is_text = isinstance(m_file, io.TextIOWrapper)
try:
file_size = os.path.getsize(m_file.name)
except AttributeError:
# Bz2 files do not have name attribute. Just set file_size to above
# max_mem for now.
file_size = max_mem + 1
# If the file size is within our desired RAM use, just reverse it in memory
# GZip files must use this method because there is no way to negative seek
if file_size < max_mem or isinstance(m_file, gzip.GzipFile):
for line in reversed(m_file.readlines()):
yield line.rstrip()
else:
if isinstance(m_file, bz2.BZ2File):
# for bz2 files, seeks are expensive. It is therefore in our best
# interest to maximize the blk_size within limits of desired RAM
# use.
blk_size = min(max_mem, file_size)
buf = ""
m_file.seek(0, 2)
if is_text:
lastchar = m_file.read(1)
else:
lastchar = m_file.read(1).decode("utf-8")
trailing_newline = (lastchar == "\n")
while 1:
newline_pos = buf.rfind("\n")
pos = m_file.tell()
if newline_pos != -1:
# Found a newline
line = buf[newline_pos + 1:]
buf = buf[:newline_pos]
if pos or newline_pos or trailing_newline:
line += "\n"
yield line
elif pos:
# Need to fill buffer
toread = min(blk_size, pos)
m_file.seek(pos - toread, 0)
if is_text:
buf = m_file.read(toread) + buf
else:
buf = m_file.read(toread).decode("utf-8") + buf
m_file.seek(pos - toread, 0)
if pos == toread:
buf = "\n" + buf
else:
# Start-of-file
return | python | def reverse_readline(m_file, blk_size=4096, max_mem=4000000):
"""
Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.
http://code.activestate.com/recipes/439045-read-a-text-file-backwards
-yet-another-implementat/
Reads file forwards and reverses in memory for files smaller than the
max_mem parameter, or for gzip files where reverse seeks are not supported.
Files larger than max_mem are dynamically read backwards.
Args:
m_file (File): File stream to read (backwards)
blk_size (int): The buffer size. Defaults to 4096.
max_mem (int): The maximum amount of memory to involve in this
operation. This is used to determine when to reverse a file
in-memory versus seeking portions of a file. For bz2 files,
this sets the maximum block size.
Returns:
Generator that returns lines from the file. Similar behavior to the
file.readline() method, except the lines are returned from the back
of the file.
"""
# Check if the file stream is a bit stream or not
is_text = isinstance(m_file, io.TextIOWrapper)
try:
file_size = os.path.getsize(m_file.name)
except AttributeError:
# Bz2 files do not have name attribute. Just set file_size to above
# max_mem for now.
file_size = max_mem + 1
# If the file size is within our desired RAM use, just reverse it in memory
# GZip files must use this method because there is no way to negative seek
if file_size < max_mem or isinstance(m_file, gzip.GzipFile):
for line in reversed(m_file.readlines()):
yield line.rstrip()
else:
if isinstance(m_file, bz2.BZ2File):
# for bz2 files, seeks are expensive. It is therefore in our best
# interest to maximize the blk_size within limits of desired RAM
# use.
blk_size = min(max_mem, file_size)
buf = ""
m_file.seek(0, 2)
if is_text:
lastchar = m_file.read(1)
else:
lastchar = m_file.read(1).decode("utf-8")
trailing_newline = (lastchar == "\n")
while 1:
newline_pos = buf.rfind("\n")
pos = m_file.tell()
if newline_pos != -1:
# Found a newline
line = buf[newline_pos + 1:]
buf = buf[:newline_pos]
if pos or newline_pos or trailing_newline:
line += "\n"
yield line
elif pos:
# Need to fill buffer
toread = min(blk_size, pos)
m_file.seek(pos - toread, 0)
if is_text:
buf = m_file.read(toread) + buf
else:
buf = m_file.read(toread).decode("utf-8") + buf
m_file.seek(pos - toread, 0)
if pos == toread:
buf = "\n" + buf
else:
# Start-of-file
return | [
"def",
"reverse_readline",
"(",
"m_file",
",",
"blk_size",
"=",
"4096",
",",
"max_mem",
"=",
"4000000",
")",
":",
"# Check if the file stream is a bit stream or not",
"is_text",
"=",
"isinstance",
"(",
"m_file",
",",
"io",
".",
"TextIOWrapper",
")",
"try",
":",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"m_file",
".",
"name",
")",
"except",
"AttributeError",
":",
"# Bz2 files do not have name attribute. Just set file_size to above",
"# max_mem for now.",
"file_size",
"=",
"max_mem",
"+",
"1",
"# If the file size is within our desired RAM use, just reverse it in memory",
"# GZip files must use this method because there is no way to negative seek",
"if",
"file_size",
"<",
"max_mem",
"or",
"isinstance",
"(",
"m_file",
",",
"gzip",
".",
"GzipFile",
")",
":",
"for",
"line",
"in",
"reversed",
"(",
"m_file",
".",
"readlines",
"(",
")",
")",
":",
"yield",
"line",
".",
"rstrip",
"(",
")",
"else",
":",
"if",
"isinstance",
"(",
"m_file",
",",
"bz2",
".",
"BZ2File",
")",
":",
"# for bz2 files, seeks are expensive. It is therefore in our best",
"# interest to maximize the blk_size within limits of desired RAM",
"# use.",
"blk_size",
"=",
"min",
"(",
"max_mem",
",",
"file_size",
")",
"buf",
"=",
"\"\"",
"m_file",
".",
"seek",
"(",
"0",
",",
"2",
")",
"if",
"is_text",
":",
"lastchar",
"=",
"m_file",
".",
"read",
"(",
"1",
")",
"else",
":",
"lastchar",
"=",
"m_file",
".",
"read",
"(",
"1",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"trailing_newline",
"=",
"(",
"lastchar",
"==",
"\"\\n\"",
")",
"while",
"1",
":",
"newline_pos",
"=",
"buf",
".",
"rfind",
"(",
"\"\\n\"",
")",
"pos",
"=",
"m_file",
".",
"tell",
"(",
")",
"if",
"newline_pos",
"!=",
"-",
"1",
":",
"# Found a newline",
"line",
"=",
"buf",
"[",
"newline_pos",
"+",
"1",
":",
"]",
"buf",
"=",
"buf",
"[",
":",
"newline_pos",
"]",
"if",
"pos",
"or",
"newline_pos",
"or",
"trailing_newline",
":",
"line",
"+=",
"\"\\n\"",
"yield",
"line",
"elif",
"pos",
":",
"# Need to fill buffer",
"toread",
"=",
"min",
"(",
"blk_size",
",",
"pos",
")",
"m_file",
".",
"seek",
"(",
"pos",
"-",
"toread",
",",
"0",
")",
"if",
"is_text",
":",
"buf",
"=",
"m_file",
".",
"read",
"(",
"toread",
")",
"+",
"buf",
"else",
":",
"buf",
"=",
"m_file",
".",
"read",
"(",
"toread",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"+",
"buf",
"m_file",
".",
"seek",
"(",
"pos",
"-",
"toread",
",",
"0",
")",
"if",
"pos",
"==",
"toread",
":",
"buf",
"=",
"\"\\n\"",
"+",
"buf",
"else",
":",
"# Start-of-file",
"return"
] | Generator method to read a file line-by-line, but backwards. This allows
one to efficiently get data at the end of a file.
Based on code by Peter Astrand <astrand@cendio.se>, using modifications by
Raymond Hettinger and Kevin German.
http://code.activestate.com/recipes/439045-read-a-text-file-backwards
-yet-another-implementat/
Reads file forwards and reverses in memory for files smaller than the
max_mem parameter, or for gzip files where reverse seeks are not supported.
Files larger than max_mem are dynamically read backwards.
Args:
m_file (File): File stream to read (backwards)
blk_size (int): The buffer size. Defaults to 4096.
max_mem (int): The maximum amount of memory to involve in this
operation. This is used to determine when to reverse a file
in-memory versus seeking portions of a file. For bz2 files,
this sets the maximum block size.
Returns:
Generator that returns lines from the file. Similar behavior to the
file.readline() method, except the lines are returned from the back
of the file. | [
"Generator",
"method",
"to",
"read",
"a",
"file",
"line",
"-",
"by",
"-",
"line",
"but",
"backwards",
".",
"This",
"allows",
"one",
"to",
"efficiently",
"get",
"data",
"at",
"the",
"end",
"of",
"a",
"file",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L105-L187 | train | 236,651 |
materialsvirtuallab/monty | monty/io.py | get_open_fds | def get_open_fds():
"""
Return the number of open file descriptors for current process
.. warning: will only work on UNIX-like OS-es.
"""
pid = os.getpid()
procs = subprocess.check_output(["lsof", '-w', '-Ff', "-p", str(pid)])
procs = procs.decode("utf-8")
return len([s for s in procs.split('\n')
if s and s[0] == 'f' and s[1:].isdigit()]) | python | def get_open_fds():
"""
Return the number of open file descriptors for current process
.. warning: will only work on UNIX-like OS-es.
"""
pid = os.getpid()
procs = subprocess.check_output(["lsof", '-w', '-Ff', "-p", str(pid)])
procs = procs.decode("utf-8")
return len([s for s in procs.split('\n')
if s and s[0] == 'f' and s[1:].isdigit()]) | [
"def",
"get_open_fds",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"procs",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"lsof\"",
",",
"'-w'",
",",
"'-Ff'",
",",
"\"-p\"",
",",
"str",
"(",
"pid",
")",
"]",
")",
"procs",
"=",
"procs",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"len",
"(",
"[",
"s",
"for",
"s",
"in",
"procs",
".",
"split",
"(",
"'\\n'",
")",
"if",
"s",
"and",
"s",
"[",
"0",
"]",
"==",
"'f'",
"and",
"s",
"[",
"1",
":",
"]",
".",
"isdigit",
"(",
")",
"]",
")"
] | Return the number of open file descriptors for current process
.. warning: will only work on UNIX-like OS-es. | [
"Return",
"the",
"number",
"of",
"open",
"file",
"descriptors",
"for",
"current",
"process"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L287-L298 | train | 236,652 |
materialsvirtuallab/monty | monty/io.py | FileLock.acquire | def acquire(self):
"""
Acquire the lock, if possible. If the lock is in use, it check again
every `delay` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception.
"""
start_time = time.time()
while True:
try:
self.fd = os.open(self.lockfile,
os.O_CREAT | os.O_EXCL | os.O_RDWR)
break
except (OSError,) as e:
if e.errno != errno.EEXIST:
raise
if (time.time() - start_time) >= self.timeout:
raise FileLockException("%s: Timeout occured." %
self.lockfile)
time.sleep(self.delay)
self.is_locked = True | python | def acquire(self):
"""
Acquire the lock, if possible. If the lock is in use, it check again
every `delay` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception.
"""
start_time = time.time()
while True:
try:
self.fd = os.open(self.lockfile,
os.O_CREAT | os.O_EXCL | os.O_RDWR)
break
except (OSError,) as e:
if e.errno != errno.EEXIST:
raise
if (time.time() - start_time) >= self.timeout:
raise FileLockException("%s: Timeout occured." %
self.lockfile)
time.sleep(self.delay)
self.is_locked = True | [
"def",
"acquire",
"(",
"self",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"self",
".",
"fd",
"=",
"os",
".",
"open",
"(",
"self",
".",
"lockfile",
",",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_EXCL",
"|",
"os",
".",
"O_RDWR",
")",
"break",
"except",
"(",
"OSError",
",",
")",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"if",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
">=",
"self",
".",
"timeout",
":",
"raise",
"FileLockException",
"(",
"\"%s: Timeout occured.\"",
"%",
"self",
".",
"lockfile",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"delay",
")",
"self",
".",
"is_locked",
"=",
"True"
] | Acquire the lock, if possible. If the lock is in use, it check again
every `delay` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception. | [
"Acquire",
"the",
"lock",
"if",
"possible",
".",
"If",
"the",
"lock",
"is",
"in",
"use",
"it",
"check",
"again",
"every",
"delay",
"seconds",
".",
"It",
"does",
"this",
"until",
"it",
"either",
"gets",
"the",
"lock",
"or",
"exceeds",
"timeout",
"number",
"of",
"seconds",
"in",
"which",
"case",
"it",
"throws",
"an",
"exception",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L229-L250 | train | 236,653 |
materialsvirtuallab/monty | monty/io.py | FileLock.release | def release(self):
""" Get rid of the lock by deleting the lockfile.
When working in a `with` statement, this gets automatically
called at the end.
"""
if self.is_locked:
os.close(self.fd)
os.unlink(self.lockfile)
self.is_locked = False | python | def release(self):
""" Get rid of the lock by deleting the lockfile.
When working in a `with` statement, this gets automatically
called at the end.
"""
if self.is_locked:
os.close(self.fd)
os.unlink(self.lockfile)
self.is_locked = False | [
"def",
"release",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_locked",
":",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")",
"os",
".",
"unlink",
"(",
"self",
".",
"lockfile",
")",
"self",
".",
"is_locked",
"=",
"False"
] | Get rid of the lock by deleting the lockfile.
When working in a `with` statement, this gets automatically
called at the end. | [
"Get",
"rid",
"of",
"the",
"lock",
"by",
"deleting",
"the",
"lockfile",
".",
"When",
"working",
"in",
"a",
"with",
"statement",
"this",
"gets",
"automatically",
"called",
"at",
"the",
"end",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L252-L260 | train | 236,654 |
materialsvirtuallab/monty | monty/fnmatch.py | WildCard.filter | def filter(self, names):
"""
Returns a list with the names matching the pattern.
"""
names = list_strings(names)
fnames = []
for f in names:
for pat in self.pats:
if fnmatch.fnmatch(f, pat):
fnames.append(f)
return fnames | python | def filter(self, names):
"""
Returns a list with the names matching the pattern.
"""
names = list_strings(names)
fnames = []
for f in names:
for pat in self.pats:
if fnmatch.fnmatch(f, pat):
fnames.append(f)
return fnames | [
"def",
"filter",
"(",
"self",
",",
"names",
")",
":",
"names",
"=",
"list_strings",
"(",
"names",
")",
"fnames",
"=",
"[",
"]",
"for",
"f",
"in",
"names",
":",
"for",
"pat",
"in",
"self",
".",
"pats",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"f",
",",
"pat",
")",
":",
"fnames",
".",
"append",
"(",
"f",
")",
"return",
"fnames"
] | Returns a list with the names matching the pattern. | [
"Returns",
"a",
"list",
"with",
"the",
"names",
"matching",
"the",
"pattern",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fnmatch.py#L41-L53 | train | 236,655 |
materialsvirtuallab/monty | monty/fnmatch.py | WildCard.match | def match(self, name):
"""
Returns True if name matches one of the patterns.
"""
for pat in self.pats:
if fnmatch.fnmatch(name, pat):
return True
return False | python | def match(self, name):
"""
Returns True if name matches one of the patterns.
"""
for pat in self.pats:
if fnmatch.fnmatch(name, pat):
return True
return False | [
"def",
"match",
"(",
"self",
",",
"name",
")",
":",
"for",
"pat",
"in",
"self",
".",
"pats",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"name",
",",
"pat",
")",
":",
"return",
"True",
"return",
"False"
] | Returns True if name matches one of the patterns. | [
"Returns",
"True",
"if",
"name",
"matches",
"one",
"of",
"the",
"patterns",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fnmatch.py#L55-L63 | train | 236,656 |
materialsvirtuallab/monty | monty/dev.py | deprecated | def deprecated(replacement=None, message=None):
"""
Decorator to mark classes or functions as deprecated,
with a possible replacement.
Args:
replacement (callable): A replacement class or method.
message (str): A warning message to be displayed.
Returns:
Original function, but with a warning to use the updated class.
"""
def wrap(old):
def wrapped(*args, **kwargs):
msg = "%s is deprecated" % old.__name__
if replacement is not None:
if isinstance(replacement, property):
r = replacement.fget
elif isinstance(replacement, (classmethod, staticmethod)):
r = replacement.__func__
else:
r = replacement
msg += "; use %s in %s instead." % (r.__name__, r.__module__)
if message is not None:
msg += "\n" + message
warnings.simplefilter('default')
warnings.warn(msg, DeprecationWarning, stacklevel=2)
return old(*args, **kwargs)
return wrapped
return wrap | python | def deprecated(replacement=None, message=None):
"""
Decorator to mark classes or functions as deprecated,
with a possible replacement.
Args:
replacement (callable): A replacement class or method.
message (str): A warning message to be displayed.
Returns:
Original function, but with a warning to use the updated class.
"""
def wrap(old):
def wrapped(*args, **kwargs):
msg = "%s is deprecated" % old.__name__
if replacement is not None:
if isinstance(replacement, property):
r = replacement.fget
elif isinstance(replacement, (classmethod, staticmethod)):
r = replacement.__func__
else:
r = replacement
msg += "; use %s in %s instead." % (r.__name__, r.__module__)
if message is not None:
msg += "\n" + message
warnings.simplefilter('default')
warnings.warn(msg, DeprecationWarning, stacklevel=2)
return old(*args, **kwargs)
return wrapped
return wrap | [
"def",
"deprecated",
"(",
"replacement",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"old",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"\"%s is deprecated\"",
"%",
"old",
".",
"__name__",
"if",
"replacement",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"replacement",
",",
"property",
")",
":",
"r",
"=",
"replacement",
".",
"fget",
"elif",
"isinstance",
"(",
"replacement",
",",
"(",
"classmethod",
",",
"staticmethod",
")",
")",
":",
"r",
"=",
"replacement",
".",
"__func__",
"else",
":",
"r",
"=",
"replacement",
"msg",
"+=",
"\"; use %s in %s instead.\"",
"%",
"(",
"r",
".",
"__name__",
",",
"r",
".",
"__module__",
")",
"if",
"message",
"is",
"not",
"None",
":",
"msg",
"+=",
"\"\\n\"",
"+",
"message",
"warnings",
".",
"simplefilter",
"(",
"'default'",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"old",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped",
"return",
"wrap"
] | Decorator to mark classes or functions as deprecated,
with a possible replacement.
Args:
replacement (callable): A replacement class or method.
message (str): A warning message to be displayed.
Returns:
Original function, but with a warning to use the updated class. | [
"Decorator",
"to",
"mark",
"classes",
"or",
"functions",
"as",
"deprecated",
"with",
"a",
"possible",
"replacement",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L26-L58 | train | 236,657 |
materialsvirtuallab/monty | monty/dev.py | install_excepthook | def install_excepthook(hook_type="color", **kwargs):
"""
This function replaces the original python traceback with an improved
version from Ipython. Use `color` for colourful traceback formatting,
`verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword
arguments passed to the constructor. See IPython.core.ultratb.py for more
info.
Return:
0 if hook is installed successfully.
"""
try:
from IPython.core import ultratb
except ImportError:
import warnings
warnings.warn(
"Cannot install excepthook, IPyhon.core.ultratb not available")
return 1
# Select the hook.
hook = dict(
color=ultratb.ColorTB,
verbose=ultratb.VerboseTB,
).get(hook_type.lower(), None)
if hook is None:
return 2
import sys
sys.excepthook = hook(**kwargs)
return 0 | python | def install_excepthook(hook_type="color", **kwargs):
"""
This function replaces the original python traceback with an improved
version from Ipython. Use `color` for colourful traceback formatting,
`verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword
arguments passed to the constructor. See IPython.core.ultratb.py for more
info.
Return:
0 if hook is installed successfully.
"""
try:
from IPython.core import ultratb
except ImportError:
import warnings
warnings.warn(
"Cannot install excepthook, IPyhon.core.ultratb not available")
return 1
# Select the hook.
hook = dict(
color=ultratb.ColorTB,
verbose=ultratb.VerboseTB,
).get(hook_type.lower(), None)
if hook is None:
return 2
import sys
sys.excepthook = hook(**kwargs)
return 0 | [
"def",
"install_excepthook",
"(",
"hook_type",
"=",
"\"color\"",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"from",
"IPython",
".",
"core",
"import",
"ultratb",
"except",
"ImportError",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"Cannot install excepthook, IPyhon.core.ultratb not available\"",
")",
"return",
"1",
"# Select the hook.",
"hook",
"=",
"dict",
"(",
"color",
"=",
"ultratb",
".",
"ColorTB",
",",
"verbose",
"=",
"ultratb",
".",
"VerboseTB",
",",
")",
".",
"get",
"(",
"hook_type",
".",
"lower",
"(",
")",
",",
"None",
")",
"if",
"hook",
"is",
"None",
":",
"return",
"2",
"import",
"sys",
"sys",
".",
"excepthook",
"=",
"hook",
"(",
"*",
"*",
"kwargs",
")",
"return",
"0"
] | This function replaces the original python traceback with an improved
version from Ipython. Use `color` for colourful traceback formatting,
`verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword
arguments passed to the constructor. See IPython.core.ultratb.py for more
info.
Return:
0 if hook is installed successfully. | [
"This",
"function",
"replaces",
"the",
"original",
"python",
"traceback",
"with",
"an",
"improved",
"version",
"from",
"Ipython",
".",
"Use",
"color",
"for",
"colourful",
"traceback",
"formatting",
"verbose",
"for",
"Ka",
"-",
"Ping",
"Yee",
"s",
"cgitb",
".",
"py",
"version",
"kwargs",
"are",
"the",
"keyword",
"arguments",
"passed",
"to",
"the",
"constructor",
".",
"See",
"IPython",
".",
"core",
".",
"ultratb",
".",
"py",
"for",
"more",
"info",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/dev.py#L198-L228 | train | 236,658 |
materialsvirtuallab/monty | monty/re.py | regrep | def regrep(filename, patterns, reverse=False, terminate_on_match=False,
postprocess=str):
"""
A powerful regular expression version of grep.
Args:
filename (str): Filename to grep.
patterns (dict): A dict of patterns, e.g.,
{"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}.
reverse (bool): Read files in reverse. Defaults to false. Useful for
large files, especially when used with terminate_on_match.
terminate_on_match (bool): Whether to terminate when there is at
least one match in each key in pattern.
postprocess (callable): A post processing function to convert all
matches. Defaults to str, i.e., no change.
Returns:
A dict of the following form:
{key1: [[[matches...], lineno], [[matches...], lineno],
[[matches...], lineno], ...],
key2: ...}
For reverse reads, the lineno is given as a -ve number. Please note
that 0-based indexing is used.
"""
compiled = {k: re.compile(v) for k, v in patterns.items()}
matches = collections.defaultdict(list)
gen = reverse_readfile(filename) if reverse else zopen(filename, "rt")
for i, l in enumerate(gen):
for k, p in compiled.items():
m = p.search(l)
if m:
matches[k].append([[postprocess(g) for g in m.groups()],
-i if reverse else i])
if terminate_on_match and all([
len(matches.get(k, [])) for k in compiled.keys()]):
break
try:
# Try to close open file handle. Pass if it is a generator.
gen.close()
except:
pass
return matches | python | def regrep(filename, patterns, reverse=False, terminate_on_match=False,
postprocess=str):
"""
A powerful regular expression version of grep.
Args:
filename (str): Filename to grep.
patterns (dict): A dict of patterns, e.g.,
{"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}.
reverse (bool): Read files in reverse. Defaults to false. Useful for
large files, especially when used with terminate_on_match.
terminate_on_match (bool): Whether to terminate when there is at
least one match in each key in pattern.
postprocess (callable): A post processing function to convert all
matches. Defaults to str, i.e., no change.
Returns:
A dict of the following form:
{key1: [[[matches...], lineno], [[matches...], lineno],
[[matches...], lineno], ...],
key2: ...}
For reverse reads, the lineno is given as a -ve number. Please note
that 0-based indexing is used.
"""
compiled = {k: re.compile(v) for k, v in patterns.items()}
matches = collections.defaultdict(list)
gen = reverse_readfile(filename) if reverse else zopen(filename, "rt")
for i, l in enumerate(gen):
for k, p in compiled.items():
m = p.search(l)
if m:
matches[k].append([[postprocess(g) for g in m.groups()],
-i if reverse else i])
if terminate_on_match and all([
len(matches.get(k, [])) for k in compiled.keys()]):
break
try:
# Try to close open file handle. Pass if it is a generator.
gen.close()
except:
pass
return matches | [
"def",
"regrep",
"(",
"filename",
",",
"patterns",
",",
"reverse",
"=",
"False",
",",
"terminate_on_match",
"=",
"False",
",",
"postprocess",
"=",
"str",
")",
":",
"compiled",
"=",
"{",
"k",
":",
"re",
".",
"compile",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"patterns",
".",
"items",
"(",
")",
"}",
"matches",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"gen",
"=",
"reverse_readfile",
"(",
"filename",
")",
"if",
"reverse",
"else",
"zopen",
"(",
"filename",
",",
"\"rt\"",
")",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"gen",
")",
":",
"for",
"k",
",",
"p",
"in",
"compiled",
".",
"items",
"(",
")",
":",
"m",
"=",
"p",
".",
"search",
"(",
"l",
")",
"if",
"m",
":",
"matches",
"[",
"k",
"]",
".",
"append",
"(",
"[",
"[",
"postprocess",
"(",
"g",
")",
"for",
"g",
"in",
"m",
".",
"groups",
"(",
")",
"]",
",",
"-",
"i",
"if",
"reverse",
"else",
"i",
"]",
")",
"if",
"terminate_on_match",
"and",
"all",
"(",
"[",
"len",
"(",
"matches",
".",
"get",
"(",
"k",
",",
"[",
"]",
")",
")",
"for",
"k",
"in",
"compiled",
".",
"keys",
"(",
")",
"]",
")",
":",
"break",
"try",
":",
"# Try to close open file handle. Pass if it is a generator.",
"gen",
".",
"close",
"(",
")",
"except",
":",
"pass",
"return",
"matches"
] | A powerful regular expression version of grep.
Args:
filename (str): Filename to grep.
patterns (dict): A dict of patterns, e.g.,
{"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}.
reverse (bool): Read files in reverse. Defaults to false. Useful for
large files, especially when used with terminate_on_match.
terminate_on_match (bool): Whether to terminate when there is at
least one match in each key in pattern.
postprocess (callable): A post processing function to convert all
matches. Defaults to str, i.e., no change.
Returns:
A dict of the following form:
{key1: [[[matches...], lineno], [[matches...], lineno],
[[matches...], lineno], ...],
key2: ...}
For reverse reads, the lineno is given as a -ve number. Please note
that 0-based indexing is used. | [
"A",
"powerful",
"regular",
"expression",
"version",
"of",
"grep",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/re.py#L21-L62 | train | 236,659 |
materialsvirtuallab/monty | monty/design_patterns.py | cached_class | def cached_class(klass):
"""
Decorator to cache class instances by constructor arguments.
This results in a class that behaves like a singleton for each
set of constructor arguments, ensuring efficiency.
Note that this should be used for *immutable classes only*. Having
a cached mutable class makes very little sense. For efficiency,
avoid using this decorator for situations where there are many
constructor arguments permutations.
The keywords argument dictionary is converted to a tuple because
dicts are mutable; keywords themselves are strings and
so are always hashable, but if any arguments (keyword
or positional) are non-hashable, that set of arguments
is not cached.
"""
cache = {}
@wraps(klass, assigned=("__name__", "__module__"), updated=())
class _decorated(klass):
# The wraps decorator can't do this because __doc__
# isn't writable once the class is created
__doc__ = klass.__doc__
def __new__(cls, *args, **kwargs):
key = (cls,) + args + tuple(kwargs.items())
try:
inst = cache.get(key, None)
except TypeError:
# Can't cache this set of arguments
inst = key = None
if inst is None:
# Technically this is cheating, but it works,
# and takes care of initializing the instance
# (so we can override __init__ below safely);
# calling up to klass.__new__ would be the
# "official" way to create the instance, but
# that raises DeprecationWarning if there are
# args or kwargs and klass does not override
# __new__ (which most classes don't), because
# object.__new__ takes no parameters (and in
# Python 3 the warning will become an error)
inst = klass(*args, **kwargs)
# This makes isinstance and issubclass work
# properly
inst.__class__ = cls
if key is not None:
cache[key] = inst
return inst
def __init__(self, *args, **kwargs):
# This will be called every time __new__ is
# called, so we skip initializing here and do
# it only when the instance is created above
pass
return _decorated | python | def cached_class(klass):
"""
Decorator to cache class instances by constructor arguments.
This results in a class that behaves like a singleton for each
set of constructor arguments, ensuring efficiency.
Note that this should be used for *immutable classes only*. Having
a cached mutable class makes very little sense. For efficiency,
avoid using this decorator for situations where there are many
constructor arguments permutations.
The keywords argument dictionary is converted to a tuple because
dicts are mutable; keywords themselves are strings and
so are always hashable, but if any arguments (keyword
or positional) are non-hashable, that set of arguments
is not cached.
"""
cache = {}
@wraps(klass, assigned=("__name__", "__module__"), updated=())
class _decorated(klass):
# The wraps decorator can't do this because __doc__
# isn't writable once the class is created
__doc__ = klass.__doc__
def __new__(cls, *args, **kwargs):
key = (cls,) + args + tuple(kwargs.items())
try:
inst = cache.get(key, None)
except TypeError:
# Can't cache this set of arguments
inst = key = None
if inst is None:
# Technically this is cheating, but it works,
# and takes care of initializing the instance
# (so we can override __init__ below safely);
# calling up to klass.__new__ would be the
# "official" way to create the instance, but
# that raises DeprecationWarning if there are
# args or kwargs and klass does not override
# __new__ (which most classes don't), because
# object.__new__ takes no parameters (and in
# Python 3 the warning will become an error)
inst = klass(*args, **kwargs)
# This makes isinstance and issubclass work
# properly
inst.__class__ = cls
if key is not None:
cache[key] = inst
return inst
def __init__(self, *args, **kwargs):
# This will be called every time __new__ is
# called, so we skip initializing here and do
# it only when the instance is created above
pass
return _decorated | [
"def",
"cached_class",
"(",
"klass",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"klass",
",",
"assigned",
"=",
"(",
"\"__name__\"",
",",
"\"__module__\"",
")",
",",
"updated",
"=",
"(",
")",
")",
"class",
"_decorated",
"(",
"klass",
")",
":",
"# The wraps decorator can't do this because __doc__",
"# isn't writable once the class is created",
"__doc__",
"=",
"klass",
".",
"__doc__",
"def",
"__new__",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"(",
"cls",
",",
")",
"+",
"args",
"+",
"tuple",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
"try",
":",
"inst",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"None",
")",
"except",
"TypeError",
":",
"# Can't cache this set of arguments",
"inst",
"=",
"key",
"=",
"None",
"if",
"inst",
"is",
"None",
":",
"# Technically this is cheating, but it works,",
"# and takes care of initializing the instance",
"# (so we can override __init__ below safely);",
"# calling up to klass.__new__ would be the",
"# \"official\" way to create the instance, but",
"# that raises DeprecationWarning if there are",
"# args or kwargs and klass does not override",
"# __new__ (which most classes don't), because",
"# object.__new__ takes no parameters (and in",
"# Python 3 the warning will become an error)",
"inst",
"=",
"klass",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# This makes isinstance and issubclass work",
"# properly",
"inst",
".",
"__class__",
"=",
"cls",
"if",
"key",
"is",
"not",
"None",
":",
"cache",
"[",
"key",
"]",
"=",
"inst",
"return",
"inst",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# This will be called every time __new__ is",
"# called, so we skip initializing here and do",
"# it only when the instance is created above",
"pass",
"return",
"_decorated"
] | Decorator to cache class instances by constructor arguments.
This results in a class that behaves like a singleton for each
set of constructor arguments, ensuring efficiency.
Note that this should be used for *immutable classes only*. Having
a cached mutable class makes very little sense. For efficiency,
avoid using this decorator for situations where there are many
constructor arguments permutations.
The keywords argument dictionary is converted to a tuple because
dicts are mutable; keywords themselves are strings and
so are always hashable, but if any arguments (keyword
or positional) are non-hashable, that set of arguments
is not cached. | [
"Decorator",
"to",
"cache",
"class",
"instances",
"by",
"constructor",
"arguments",
".",
"This",
"results",
"in",
"a",
"class",
"that",
"behaves",
"like",
"a",
"singleton",
"for",
"each",
"set",
"of",
"constructor",
"arguments",
"ensuring",
"efficiency",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/design_patterns.py#L37-L94 | train | 236,660 |
materialsvirtuallab/monty | monty/operator.py | operator_from_str | def operator_from_str(op):
"""
Return the operator associated to the given string `op`.
raises:
`KeyError` if invalid string.
>>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2
"""
d = {"==": operator.eq,
"!=": operator.ne,
">": operator.gt,
">=": operator.ge,
"<": operator.lt,
"<=": operator.le,
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'%': operator.mod,
'^': operator.xor,
}
try:
d['/'] = operator.truediv
except AttributeError:
pass
return d[op] | python | def operator_from_str(op):
"""
Return the operator associated to the given string `op`.
raises:
`KeyError` if invalid string.
>>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2
"""
d = {"==": operator.eq,
"!=": operator.ne,
">": operator.gt,
">=": operator.ge,
"<": operator.lt,
"<=": operator.le,
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'%': operator.mod,
'^': operator.xor,
}
try:
d['/'] = operator.truediv
except AttributeError:
pass
return d[op] | [
"def",
"operator_from_str",
"(",
"op",
")",
":",
"d",
"=",
"{",
"\"==\"",
":",
"operator",
".",
"eq",
",",
"\"!=\"",
":",
"operator",
".",
"ne",
",",
"\">\"",
":",
"operator",
".",
"gt",
",",
"\">=\"",
":",
"operator",
".",
"ge",
",",
"\"<\"",
":",
"operator",
".",
"lt",
",",
"\"<=\"",
":",
"operator",
".",
"le",
",",
"'+'",
":",
"operator",
".",
"add",
",",
"'-'",
":",
"operator",
".",
"sub",
",",
"'*'",
":",
"operator",
".",
"mul",
",",
"'%'",
":",
"operator",
".",
"mod",
",",
"'^'",
":",
"operator",
".",
"xor",
",",
"}",
"try",
":",
"d",
"[",
"'/'",
"]",
"=",
"operator",
".",
"truediv",
"except",
"AttributeError",
":",
"pass",
"return",
"d",
"[",
"op",
"]"
] | Return the operator associated to the given string `op`.
raises:
`KeyError` if invalid string.
>>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 | [
"Return",
"the",
"operator",
"associated",
"to",
"the",
"given",
"string",
"op",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/operator.py#L9-L36 | train | 236,661 |
materialsvirtuallab/monty | monty/subprocess.py | Command.run | def run(self, timeout=None, **kwargs):
"""
Run a command in a separated thread and wait timeout seconds.
kwargs are keyword arguments passed to Popen.
Return: self
"""
from subprocess import Popen, PIPE
def target(**kw):
try:
# print('Thread started')
self.process = Popen(self.command, **kw)
self.output, self.error = self.process.communicate()
self.retcode = self.process.returncode
# print('Thread stopped')
except:
import traceback
self.error = traceback.format_exc()
self.retcode = -1
# default stdout and stderr
if 'stdout' not in kwargs:
kwargs['stdout'] = PIPE
if 'stderr' not in kwargs:
kwargs['stderr'] = PIPE
# thread
import threading
thread = threading.Thread(target=target, kwargs=kwargs)
thread.start()
thread.join(timeout)
if thread.is_alive():
# print("Terminating process")
self.process.terminate()
self.killed = True
thread.join()
return self | python | def run(self, timeout=None, **kwargs):
"""
Run a command in a separated thread and wait timeout seconds.
kwargs are keyword arguments passed to Popen.
Return: self
"""
from subprocess import Popen, PIPE
def target(**kw):
try:
# print('Thread started')
self.process = Popen(self.command, **kw)
self.output, self.error = self.process.communicate()
self.retcode = self.process.returncode
# print('Thread stopped')
except:
import traceback
self.error = traceback.format_exc()
self.retcode = -1
# default stdout and stderr
if 'stdout' not in kwargs:
kwargs['stdout'] = PIPE
if 'stderr' not in kwargs:
kwargs['stderr'] = PIPE
# thread
import threading
thread = threading.Thread(target=target, kwargs=kwargs)
thread.start()
thread.join(timeout)
if thread.is_alive():
# print("Terminating process")
self.process.terminate()
self.killed = True
thread.join()
return self | [
"def",
"run",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"subprocess",
"import",
"Popen",
",",
"PIPE",
"def",
"target",
"(",
"*",
"*",
"kw",
")",
":",
"try",
":",
"# print('Thread started')",
"self",
".",
"process",
"=",
"Popen",
"(",
"self",
".",
"command",
",",
"*",
"*",
"kw",
")",
"self",
".",
"output",
",",
"self",
".",
"error",
"=",
"self",
".",
"process",
".",
"communicate",
"(",
")",
"self",
".",
"retcode",
"=",
"self",
".",
"process",
".",
"returncode",
"# print('Thread stopped')",
"except",
":",
"import",
"traceback",
"self",
".",
"error",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"self",
".",
"retcode",
"=",
"-",
"1",
"# default stdout and stderr",
"if",
"'stdout'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'stdout'",
"]",
"=",
"PIPE",
"if",
"'stderr'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'stderr'",
"]",
"=",
"PIPE",
"# thread",
"import",
"threading",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"target",
",",
"kwargs",
"=",
"kwargs",
")",
"thread",
".",
"start",
"(",
")",
"thread",
".",
"join",
"(",
"timeout",
")",
"if",
"thread",
".",
"is_alive",
"(",
")",
":",
"# print(\"Terminating process\")",
"self",
".",
"process",
".",
"terminate",
"(",
")",
"self",
".",
"killed",
"=",
"True",
"thread",
".",
"join",
"(",
")",
"return",
"self"
] | Run a command in a separated thread and wait timeout seconds.
kwargs are keyword arguments passed to Popen.
Return: self | [
"Run",
"a",
"command",
"in",
"a",
"separated",
"thread",
"and",
"wait",
"timeout",
"seconds",
".",
"kwargs",
"are",
"keyword",
"arguments",
"passed",
"to",
"Popen",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/subprocess.py#L59-L99 | train | 236,662 |
materialsvirtuallab/monty | monty/string.py | marquee | def marquee(text="", width=78, mark='*'):
"""
Return the input string centered in a 'marquee'.
Args:
text (str): Input string
width (int): Width of final output string.
mark (str): Character used to fill string.
:Examples:
>>> marquee('A test', width=40)
'**************** A test ****************'
>>> marquee('A test', width=40, mark='-')
'---------------- A test ----------------'
marquee('A test',40, ' ')
' A test '
"""
if not text:
return (mark*width)[:width]
nmark = (width-len(text)-2)//len(mark)//2
if nmark < 0:
nmark = 0
marks = mark * nmark
return '%s %s %s' % (marks, text, marks) | python | def marquee(text="", width=78, mark='*'):
"""
Return the input string centered in a 'marquee'.
Args:
text (str): Input string
width (int): Width of final output string.
mark (str): Character used to fill string.
:Examples:
>>> marquee('A test', width=40)
'**************** A test ****************'
>>> marquee('A test', width=40, mark='-')
'---------------- A test ----------------'
marquee('A test',40, ' ')
' A test '
"""
if not text:
return (mark*width)[:width]
nmark = (width-len(text)-2)//len(mark)//2
if nmark < 0:
nmark = 0
marks = mark * nmark
return '%s %s %s' % (marks, text, marks) | [
"def",
"marquee",
"(",
"text",
"=",
"\"\"",
",",
"width",
"=",
"78",
",",
"mark",
"=",
"'*'",
")",
":",
"if",
"not",
"text",
":",
"return",
"(",
"mark",
"*",
"width",
")",
"[",
":",
"width",
"]",
"nmark",
"=",
"(",
"width",
"-",
"len",
"(",
"text",
")",
"-",
"2",
")",
"//",
"len",
"(",
"mark",
")",
"//",
"2",
"if",
"nmark",
"<",
"0",
":",
"nmark",
"=",
"0",
"marks",
"=",
"mark",
"*",
"nmark",
"return",
"'%s %s %s'",
"%",
"(",
"marks",
",",
"text",
",",
"marks",
")"
] | Return the input string centered in a 'marquee'.
Args:
text (str): Input string
width (int): Width of final output string.
mark (str): Character used to fill string.
:Examples:
>>> marquee('A test', width=40)
'**************** A test ****************'
>>> marquee('A test', width=40, mark='-')
'---------------- A test ----------------'
marquee('A test',40, ' ')
' A test ' | [
"Return",
"the",
"input",
"string",
"centered",
"in",
"a",
"marquee",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L90-L118 | train | 236,663 |
materialsvirtuallab/monty | monty/string.py | boxed | def boxed(msg, ch="=", pad=5):
"""
Returns a string in a box
Args:
msg: Input string.
ch: Character used to form the box.
pad: Number of characters ch added before and after msg.
>>> print(boxed("hello", ch="*", pad=2))
***********
** hello **
***********
"""
if pad > 0:
msg = pad * ch + " " + msg.strip() + " " + pad * ch
return "\n".join([len(msg) * ch,
msg,
len(msg) * ch,
]) | python | def boxed(msg, ch="=", pad=5):
"""
Returns a string in a box
Args:
msg: Input string.
ch: Character used to form the box.
pad: Number of characters ch added before and after msg.
>>> print(boxed("hello", ch="*", pad=2))
***********
** hello **
***********
"""
if pad > 0:
msg = pad * ch + " " + msg.strip() + " " + pad * ch
return "\n".join([len(msg) * ch,
msg,
len(msg) * ch,
]) | [
"def",
"boxed",
"(",
"msg",
",",
"ch",
"=",
"\"=\"",
",",
"pad",
"=",
"5",
")",
":",
"if",
"pad",
">",
"0",
":",
"msg",
"=",
"pad",
"*",
"ch",
"+",
"\" \"",
"+",
"msg",
".",
"strip",
"(",
")",
"+",
"\" \"",
"+",
"pad",
"*",
"ch",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"len",
"(",
"msg",
")",
"*",
"ch",
",",
"msg",
",",
"len",
"(",
"msg",
")",
"*",
"ch",
",",
"]",
")"
] | Returns a string in a box
Args:
msg: Input string.
ch: Character used to form the box.
pad: Number of characters ch added before and after msg.
>>> print(boxed("hello", ch="*", pad=2))
***********
** hello **
*********** | [
"Returns",
"a",
"string",
"in",
"a",
"box"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L121-L141 | train | 236,664 |
materialsvirtuallab/monty | monty/string.py | indent | def indent(lines, amount, ch=' '):
"""Indent the lines in a string by padding each one with proper number of pad characters"""
padding = amount * ch
return padding + ('\n' + padding).join(lines.split('\n')) | python | def indent(lines, amount, ch=' '):
"""Indent the lines in a string by padding each one with proper number of pad characters"""
padding = amount * ch
return padding + ('\n' + padding).join(lines.split('\n')) | [
"def",
"indent",
"(",
"lines",
",",
"amount",
",",
"ch",
"=",
"' '",
")",
":",
"padding",
"=",
"amount",
"*",
"ch",
"return",
"padding",
"+",
"(",
"'\\n'",
"+",
"padding",
")",
".",
"join",
"(",
"lines",
".",
"split",
"(",
"'\\n'",
")",
")"
] | Indent the lines in a string by padding each one with proper number of pad characters | [
"Indent",
"the",
"lines",
"in",
"a",
"string",
"by",
"padding",
"each",
"one",
"with",
"proper",
"number",
"of",
"pad",
"characters"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/string.py#L149-L152 | train | 236,665 |
materialsvirtuallab/monty | monty/functools.py | prof_main | def prof_main(main):
"""
Decorator for profiling main programs.
Profiling is activated by prepending the command line options
supported by the original main program with the keyword `prof`.
Example:
$ script.py arg --foo=1
becomes
$ script.py prof arg --foo=1
The decorated main accepts two new arguments:
prof_file: Name of the output file with profiling data
If not given, a temporary file is created.
sortby: Profiling data are sorted according to this value.
default is "time". See sort_stats.
"""
@wraps(main)
def wrapper(*args, **kwargs):
import sys
try:
do_prof = sys.argv[1] == "prof"
if do_prof: sys.argv.pop(1)
except Exception:
do_prof = False
if not do_prof:
sys.exit(main())
else:
print("Entering profiling mode...")
import pstats, cProfile, tempfile
prof_file = kwargs.get("prof_file", None)
if prof_file is None:
_, prof_file = tempfile.mkstemp()
print("Profiling data stored in %s" % prof_file)
sortby = kwargs.get("sortby", "time")
cProfile.runctx("main()", globals(), locals(), prof_file)
s = pstats.Stats(prof_file)
s.strip_dirs().sort_stats(sortby).print_stats()
if "retval" not in kwargs:
sys.exit(0)
else:
return kwargs["retval"]
return wrapper | python | def prof_main(main):
"""
Decorator for profiling main programs.
Profiling is activated by prepending the command line options
supported by the original main program with the keyword `prof`.
Example:
$ script.py arg --foo=1
becomes
$ script.py prof arg --foo=1
The decorated main accepts two new arguments:
prof_file: Name of the output file with profiling data
If not given, a temporary file is created.
sortby: Profiling data are sorted according to this value.
default is "time". See sort_stats.
"""
@wraps(main)
def wrapper(*args, **kwargs):
import sys
try:
do_prof = sys.argv[1] == "prof"
if do_prof: sys.argv.pop(1)
except Exception:
do_prof = False
if not do_prof:
sys.exit(main())
else:
print("Entering profiling mode...")
import pstats, cProfile, tempfile
prof_file = kwargs.get("prof_file", None)
if prof_file is None:
_, prof_file = tempfile.mkstemp()
print("Profiling data stored in %s" % prof_file)
sortby = kwargs.get("sortby", "time")
cProfile.runctx("main()", globals(), locals(), prof_file)
s = pstats.Stats(prof_file)
s.strip_dirs().sort_stats(sortby).print_stats()
if "retval" not in kwargs:
sys.exit(0)
else:
return kwargs["retval"]
return wrapper | [
"def",
"prof_main",
"(",
"main",
")",
":",
"@",
"wraps",
"(",
"main",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"sys",
"try",
":",
"do_prof",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"prof\"",
"if",
"do_prof",
":",
"sys",
".",
"argv",
".",
"pop",
"(",
"1",
")",
"except",
"Exception",
":",
"do_prof",
"=",
"False",
"if",
"not",
"do_prof",
":",
"sys",
".",
"exit",
"(",
"main",
"(",
")",
")",
"else",
":",
"print",
"(",
"\"Entering profiling mode...\"",
")",
"import",
"pstats",
",",
"cProfile",
",",
"tempfile",
"prof_file",
"=",
"kwargs",
".",
"get",
"(",
"\"prof_file\"",
",",
"None",
")",
"if",
"prof_file",
"is",
"None",
":",
"_",
",",
"prof_file",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"print",
"(",
"\"Profiling data stored in %s\"",
"%",
"prof_file",
")",
"sortby",
"=",
"kwargs",
".",
"get",
"(",
"\"sortby\"",
",",
"\"time\"",
")",
"cProfile",
".",
"runctx",
"(",
"\"main()\"",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"prof_file",
")",
"s",
"=",
"pstats",
".",
"Stats",
"(",
"prof_file",
")",
"s",
".",
"strip_dirs",
"(",
")",
".",
"sort_stats",
"(",
"sortby",
")",
".",
"print_stats",
"(",
")",
"if",
"\"retval\"",
"not",
"in",
"kwargs",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"else",
":",
"return",
"kwargs",
"[",
"\"retval\"",
"]",
"return",
"wrapper"
] | Decorator for profiling main programs.
Profiling is activated by prepending the command line options
supported by the original main program with the keyword `prof`.
Example:
$ script.py arg --foo=1
becomes
$ script.py prof arg --foo=1
The decorated main accepts two new arguments:
prof_file: Name of the output file with profiling data
If not given, a temporary file is created.
sortby: Profiling data are sorted according to this value.
default is "time". See sort_stats. | [
"Decorator",
"for",
"profiling",
"main",
"programs",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L380-L429 | train | 236,666 |
materialsvirtuallab/monty | monty/functools.py | lazy_property.invalidate | def invalidate(cls, inst, name):
"""Invalidate a lazy attribute.
This obviously violates the lazy contract. A subclass of lazy
may however have a contract where invalidation is appropriate.
"""
inst_cls = inst.__class__
if not hasattr(inst, '__dict__'):
raise AttributeError("'%s' object has no attribute '__dict__'"
% (inst_cls.__name__,))
if name.startswith('__') and not name.endswith('__'):
name = '_%s%s' % (inst_cls.__name__, name)
if not isinstance(getattr(inst_cls, name), cls):
raise AttributeError("'%s.%s' is not a %s attribute"
% (inst_cls.__name__, name, cls.__name__))
if name in inst.__dict__:
del inst.__dict__[name] | python | def invalidate(cls, inst, name):
"""Invalidate a lazy attribute.
This obviously violates the lazy contract. A subclass of lazy
may however have a contract where invalidation is appropriate.
"""
inst_cls = inst.__class__
if not hasattr(inst, '__dict__'):
raise AttributeError("'%s' object has no attribute '__dict__'"
% (inst_cls.__name__,))
if name.startswith('__') and not name.endswith('__'):
name = '_%s%s' % (inst_cls.__name__, name)
if not isinstance(getattr(inst_cls, name), cls):
raise AttributeError("'%s.%s' is not a %s attribute"
% (inst_cls.__name__, name, cls.__name__))
if name in inst.__dict__:
del inst.__dict__[name] | [
"def",
"invalidate",
"(",
"cls",
",",
"inst",
",",
"name",
")",
":",
"inst_cls",
"=",
"inst",
".",
"__class__",
"if",
"not",
"hasattr",
"(",
"inst",
",",
"'__dict__'",
")",
":",
"raise",
"AttributeError",
"(",
"\"'%s' object has no attribute '__dict__'\"",
"%",
"(",
"inst_cls",
".",
"__name__",
",",
")",
")",
"if",
"name",
".",
"startswith",
"(",
"'__'",
")",
"and",
"not",
"name",
".",
"endswith",
"(",
"'__'",
")",
":",
"name",
"=",
"'_%s%s'",
"%",
"(",
"inst_cls",
".",
"__name__",
",",
"name",
")",
"if",
"not",
"isinstance",
"(",
"getattr",
"(",
"inst_cls",
",",
"name",
")",
",",
"cls",
")",
":",
"raise",
"AttributeError",
"(",
"\"'%s.%s' is not a %s attribute\"",
"%",
"(",
"inst_cls",
".",
"__name__",
",",
"name",
",",
"cls",
".",
"__name__",
")",
")",
"if",
"name",
"in",
"inst",
".",
"__dict__",
":",
"del",
"inst",
".",
"__dict__",
"[",
"name",
"]"
] | Invalidate a lazy attribute.
This obviously violates the lazy contract. A subclass of lazy
may however have a contract where invalidation is appropriate. | [
"Invalidate",
"a",
"lazy",
"attribute",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/functools.py#L257-L277 | train | 236,667 |
materialsvirtuallab/monty | monty/collections.py | as_set | def as_set(obj):
"""
Convert obj into a set, returns None if obj is None.
>>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2])
"""
if obj is None or isinstance(obj, collections.Set):
return obj
if not isinstance(obj, collections.Iterable):
return set((obj,))
else:
return set(obj) | python | def as_set(obj):
"""
Convert obj into a set, returns None if obj is None.
>>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2])
"""
if obj is None or isinstance(obj, collections.Set):
return obj
if not isinstance(obj, collections.Iterable):
return set((obj,))
else:
return set(obj) | [
"def",
"as_set",
"(",
"obj",
")",
":",
"if",
"obj",
"is",
"None",
"or",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"Set",
")",
":",
"return",
"obj",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"collections",
".",
"Iterable",
")",
":",
"return",
"set",
"(",
"(",
"obj",
",",
")",
")",
"else",
":",
"return",
"set",
"(",
"obj",
")"
] | Convert obj into a set, returns None if obj is None.
>>> assert as_set(None) is None and as_set(1) == set([1]) and as_set(range(1,3)) == set([1, 2]) | [
"Convert",
"obj",
"into",
"a",
"set",
"returns",
"None",
"if",
"obj",
"is",
"None",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/collections.py#L30-L42 | train | 236,668 |
materialsvirtuallab/monty | monty/logging.py | logged | def logged(level=logging.DEBUG):
"""
Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.
Args:
level: Level to log method at. Defaults to DEBUG.
"""
def wrap(f):
_logger = logging.getLogger("{}.{}".format(f.__module__, f.__name__))
def wrapped_f(*args, **kwargs):
_logger.log(level, "Called at {} with args = {} and kwargs = {}"
.format(datetime.datetime.now(), args, kwargs))
data = f(*args, **kwargs)
_logger.log(level, "Done at {} with args = {} and kwargs = {}"
.format(datetime.datetime.now(), args, kwargs))
return data
return wrapped_f
return wrap | python | def logged(level=logging.DEBUG):
"""
Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.
Args:
level: Level to log method at. Defaults to DEBUG.
"""
def wrap(f):
_logger = logging.getLogger("{}.{}".format(f.__module__, f.__name__))
def wrapped_f(*args, **kwargs):
_logger.log(level, "Called at {} with args = {} and kwargs = {}"
.format(datetime.datetime.now(), args, kwargs))
data = f(*args, **kwargs)
_logger.log(level, "Done at {} with args = {} and kwargs = {}"
.format(datetime.datetime.now(), args, kwargs))
return data
return wrapped_f
return wrap | [
"def",
"logged",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"f",
".",
"__module__",
",",
"f",
".",
"__name__",
")",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_logger",
".",
"log",
"(",
"level",
",",
"\"Called at {} with args = {} and kwargs = {}\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"args",
",",
"kwargs",
")",
")",
"data",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_logger",
".",
"log",
"(",
"level",
",",
"\"Done at {} with args = {} and kwargs = {}\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"args",
",",
"kwargs",
")",
")",
"return",
"data",
"return",
"wrapped_f",
"return",
"wrap"
] | Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.
Args:
level: Level to log method at. Defaults to DEBUG. | [
"Useful",
"logging",
"decorator",
".",
"If",
"a",
"method",
"is",
"logged",
"the",
"beginning",
"and",
"end",
"of",
"the",
"method",
"call",
"will",
"be",
"logged",
"at",
"a",
"pre",
"-",
"specified",
"level",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/logging.py#L24-L44 | train | 236,669 |
materialsvirtuallab/monty | monty/logging.py | enable_logging | def enable_logging(main):
"""
This decorator is used to decorate main functions.
It adds the initialization of the logger and an argument parser that allows
one to select the loglevel.
Useful if we are writing simple main functions that call libraries where
the logging module is used
Args:
main:
main function.
"""
@functools.wraps(main)
def wrapper(*args, **kwargs):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--loglevel', default="ERROR", type=str,
help="Set the loglevel. Possible values: CRITICAL, ERROR (default),"
"WARNING, INFO, DEBUG")
options = parser.parse_args()
# loglevel is bound to the string value obtained from the command line
# argument.
# Convert to upper case to allow the user to specify --loglevel=DEBUG
# or --loglevel=debug
numeric_level = getattr(logging, options.loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % options.loglevel)
logging.basicConfig(level=numeric_level)
retcode = main(*args, **kwargs)
return retcode
return wrapper | python | def enable_logging(main):
"""
This decorator is used to decorate main functions.
It adds the initialization of the logger and an argument parser that allows
one to select the loglevel.
Useful if we are writing simple main functions that call libraries where
the logging module is used
Args:
main:
main function.
"""
@functools.wraps(main)
def wrapper(*args, **kwargs):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--loglevel', default="ERROR", type=str,
help="Set the loglevel. Possible values: CRITICAL, ERROR (default),"
"WARNING, INFO, DEBUG")
options = parser.parse_args()
# loglevel is bound to the string value obtained from the command line
# argument.
# Convert to upper case to allow the user to specify --loglevel=DEBUG
# or --loglevel=debug
numeric_level = getattr(logging, options.loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % options.loglevel)
logging.basicConfig(level=numeric_level)
retcode = main(*args, **kwargs)
return retcode
return wrapper | [
"def",
"enable_logging",
"(",
"main",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"main",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--loglevel'",
",",
"default",
"=",
"\"ERROR\"",
",",
"type",
"=",
"str",
",",
"help",
"=",
"\"Set the loglevel. Possible values: CRITICAL, ERROR (default),\"",
"\"WARNING, INFO, DEBUG\"",
")",
"options",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# loglevel is bound to the string value obtained from the command line",
"# argument.",
"# Convert to upper case to allow the user to specify --loglevel=DEBUG",
"# or --loglevel=debug",
"numeric_level",
"=",
"getattr",
"(",
"logging",
",",
"options",
".",
"loglevel",
".",
"upper",
"(",
")",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"numeric_level",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid log level: %s'",
"%",
"options",
".",
"loglevel",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"numeric_level",
")",
"retcode",
"=",
"main",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"retcode",
"return",
"wrapper"
] | This decorator is used to decorate main functions.
It adds the initialization of the logger and an argument parser that allows
one to select the loglevel.
Useful if we are writing simple main functions that call libraries where
the logging module is used
Args:
main:
main function. | [
"This",
"decorator",
"is",
"used",
"to",
"decorate",
"main",
"functions",
".",
"It",
"adds",
"the",
"initialization",
"of",
"the",
"logger",
"and",
"an",
"argument",
"parser",
"that",
"allows",
"one",
"to",
"select",
"the",
"loglevel",
".",
"Useful",
"if",
"we",
"are",
"writing",
"simple",
"main",
"functions",
"that",
"call",
"libraries",
"where",
"the",
"logging",
"module",
"is",
"used"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/logging.py#L47-L83 | train | 236,670 |
materialsvirtuallab/monty | monty/os/path.py | which | def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return os.path.isfile(fp) and os.access(fp, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None | python | def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return os.path.isfile(fp) and os.access(fp, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None | [
"def",
"which",
"(",
"cmd",
")",
":",
"def",
"is_exe",
"(",
"fp",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"fp",
")",
"and",
"os",
".",
"access",
"(",
"fp",
",",
"os",
".",
"X_OK",
")",
"fpath",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"cmd",
")",
"if",
"fpath",
":",
"if",
"is_exe",
"(",
"cmd",
")",
":",
"return",
"cmd",
"else",
":",
"for",
"path",
"in",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"exe_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"cmd",
")",
"if",
"is_exe",
"(",
"exe_file",
")",
":",
"return",
"exe_file",
"return",
"None"
] | Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python") | [
"Returns",
"full",
"path",
"to",
"a",
"executable",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/os/path.py#L15-L41 | train | 236,671 |
materialsvirtuallab/monty | monty/inspect.py | all_subclasses | def all_subclasses(cls):
"""
Given a class `cls`, this recursive function returns a list with
all subclasses, subclasses of subclasses, and so on.
"""
subclasses = cls.__subclasses__()
return subclasses + [g for s in subclasses for g in all_subclasses(s)] | python | def all_subclasses(cls):
"""
Given a class `cls`, this recursive function returns a list with
all subclasses, subclasses of subclasses, and so on.
"""
subclasses = cls.__subclasses__()
return subclasses + [g for s in subclasses for g in all_subclasses(s)] | [
"def",
"all_subclasses",
"(",
"cls",
")",
":",
"subclasses",
"=",
"cls",
".",
"__subclasses__",
"(",
")",
"return",
"subclasses",
"+",
"[",
"g",
"for",
"s",
"in",
"subclasses",
"for",
"g",
"in",
"all_subclasses",
"(",
"s",
")",
"]"
] | Given a class `cls`, this recursive function returns a list with
all subclasses, subclasses of subclasses, and so on. | [
"Given",
"a",
"class",
"cls",
"this",
"recursive",
"function",
"returns",
"a",
"list",
"with",
"all",
"subclasses",
"subclasses",
"of",
"subclasses",
"and",
"so",
"on",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L11-L17 | train | 236,672 |
materialsvirtuallab/monty | monty/inspect.py | find_top_pyfile | def find_top_pyfile():
"""
This function inspects the Cpython frame to find the path of the script.
"""
import os
frame = currentframe()
while True:
if frame.f_back is None:
finfo = getframeinfo(frame)
#print(getframeinfo(frame))
return os.path.abspath(finfo.filename)
frame = frame.f_back | python | def find_top_pyfile():
"""
This function inspects the Cpython frame to find the path of the script.
"""
import os
frame = currentframe()
while True:
if frame.f_back is None:
finfo = getframeinfo(frame)
#print(getframeinfo(frame))
return os.path.abspath(finfo.filename)
frame = frame.f_back | [
"def",
"find_top_pyfile",
"(",
")",
":",
"import",
"os",
"frame",
"=",
"currentframe",
"(",
")",
"while",
"True",
":",
"if",
"frame",
".",
"f_back",
"is",
"None",
":",
"finfo",
"=",
"getframeinfo",
"(",
"frame",
")",
"#print(getframeinfo(frame))",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"finfo",
".",
"filename",
")",
"frame",
"=",
"frame",
".",
"f_back"
] | This function inspects the Cpython frame to find the path of the script. | [
"This",
"function",
"inspects",
"the",
"Cpython",
"frame",
"to",
"find",
"the",
"path",
"of",
"the",
"script",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/inspect.py#L20-L32 | train | 236,673 |
materialsvirtuallab/monty | monty/pprint.py | pprint_table | def pprint_table(table, out=sys.stdout, rstrip=False):
"""
Prints out a table of data, padded for alignment
Each row must have the same number of columns.
Args:
table: The table to print. A list of lists.
out: Output stream (file-like object)
rstrip: if True, trailing withespaces are removed from the entries.
"""
def max_width_col(table, col_idx):
"""
Get the maximum width of the given column index
"""
return max([len(row[col_idx]) for row in table])
if rstrip:
for row_idx, row in enumerate(table):
table[row_idx] = [c.rstrip() for c in row]
col_paddings = []
ncols = len(table[0])
for i in range(ncols):
col_paddings.append(max_width_col(table, i))
for row in table:
# left col
out.write(row[0].ljust(col_paddings[0] + 1))
# rest of the cols
for i in range(1, len(row)):
col = row[i].rjust(col_paddings[i] + 2)
out.write(col)
out.write("\n") | python | def pprint_table(table, out=sys.stdout, rstrip=False):
"""
Prints out a table of data, padded for alignment
Each row must have the same number of columns.
Args:
table: The table to print. A list of lists.
out: Output stream (file-like object)
rstrip: if True, trailing withespaces are removed from the entries.
"""
def max_width_col(table, col_idx):
"""
Get the maximum width of the given column index
"""
return max([len(row[col_idx]) for row in table])
if rstrip:
for row_idx, row in enumerate(table):
table[row_idx] = [c.rstrip() for c in row]
col_paddings = []
ncols = len(table[0])
for i in range(ncols):
col_paddings.append(max_width_col(table, i))
for row in table:
# left col
out.write(row[0].ljust(col_paddings[0] + 1))
# rest of the cols
for i in range(1, len(row)):
col = row[i].rjust(col_paddings[i] + 2)
out.write(col)
out.write("\n") | [
"def",
"pprint_table",
"(",
"table",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"rstrip",
"=",
"False",
")",
":",
"def",
"max_width_col",
"(",
"table",
",",
"col_idx",
")",
":",
"\"\"\"\n Get the maximum width of the given column index\n \"\"\"",
"return",
"max",
"(",
"[",
"len",
"(",
"row",
"[",
"col_idx",
"]",
")",
"for",
"row",
"in",
"table",
"]",
")",
"if",
"rstrip",
":",
"for",
"row_idx",
",",
"row",
"in",
"enumerate",
"(",
"table",
")",
":",
"table",
"[",
"row_idx",
"]",
"=",
"[",
"c",
".",
"rstrip",
"(",
")",
"for",
"c",
"in",
"row",
"]",
"col_paddings",
"=",
"[",
"]",
"ncols",
"=",
"len",
"(",
"table",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"ncols",
")",
":",
"col_paddings",
".",
"append",
"(",
"max_width_col",
"(",
"table",
",",
"i",
")",
")",
"for",
"row",
"in",
"table",
":",
"# left col",
"out",
".",
"write",
"(",
"row",
"[",
"0",
"]",
".",
"ljust",
"(",
"col_paddings",
"[",
"0",
"]",
"+",
"1",
")",
")",
"# rest of the cols",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"row",
")",
")",
":",
"col",
"=",
"row",
"[",
"i",
"]",
".",
"rjust",
"(",
"col_paddings",
"[",
"i",
"]",
"+",
"2",
")",
"out",
".",
"write",
"(",
"col",
")",
"out",
".",
"write",
"(",
"\"\\n\"",
")"
] | Prints out a table of data, padded for alignment
Each row must have the same number of columns.
Args:
table: The table to print. A list of lists.
out: Output stream (file-like object)
rstrip: if True, trailing withespaces are removed from the entries. | [
"Prints",
"out",
"a",
"table",
"of",
"data",
"padded",
"for",
"alignment",
"Each",
"row",
"must",
"have",
"the",
"same",
"number",
"of",
"columns",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/pprint.py#L10-L42 | train | 236,674 |
materialsvirtuallab/monty | monty/fractions.py | gcd | def gcd(*numbers):
"""
Returns the greatest common divisor for a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Greatest common divisor of numbers.
"""
n = numbers[0]
for i in numbers:
n = pygcd(n, i)
return n | python | def gcd(*numbers):
"""
Returns the greatest common divisor for a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Greatest common divisor of numbers.
"""
n = numbers[0]
for i in numbers:
n = pygcd(n, i)
return n | [
"def",
"gcd",
"(",
"*",
"numbers",
")",
":",
"n",
"=",
"numbers",
"[",
"0",
"]",
"for",
"i",
"in",
"numbers",
":",
"n",
"=",
"pygcd",
"(",
"n",
",",
"i",
")",
"return",
"n"
] | Returns the greatest common divisor for a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Greatest common divisor of numbers. | [
"Returns",
"the",
"greatest",
"common",
"divisor",
"for",
"a",
"sequence",
"of",
"numbers",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L22-L35 | train | 236,675 |
materialsvirtuallab/monty | monty/fractions.py | lcm | def lcm(*numbers):
"""
Return lowest common multiple of a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Lowest common multiple of numbers.
"""
n = 1
for i in numbers:
n = (i * n) // gcd(i, n)
return n | python | def lcm(*numbers):
"""
Return lowest common multiple of a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Lowest common multiple of numbers.
"""
n = 1
for i in numbers:
n = (i * n) // gcd(i, n)
return n | [
"def",
"lcm",
"(",
"*",
"numbers",
")",
":",
"n",
"=",
"1",
"for",
"i",
"in",
"numbers",
":",
"n",
"=",
"(",
"i",
"*",
"n",
")",
"//",
"gcd",
"(",
"i",
",",
"n",
")",
"return",
"n"
] | Return lowest common multiple of a sequence of numbers.
Args:
\*numbers: Sequence of numbers.
Returns:
(int) Lowest common multiple of numbers. | [
"Return",
"lowest",
"common",
"multiple",
"of",
"a",
"sequence",
"of",
"numbers",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L38-L51 | train | 236,676 |
materialsvirtuallab/monty | monty/fractions.py | gcd_float | def gcd_float(numbers, tol=1e-8):
"""
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers.
"""
def pair_gcd_tol(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b > tol:
a, b = b, a % b
return a
n = numbers[0]
for i in numbers:
n = pair_gcd_tol(n, i)
return n | python | def gcd_float(numbers, tol=1e-8):
"""
Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers.
"""
def pair_gcd_tol(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b > tol:
a, b = b, a % b
return a
n = numbers[0]
for i in numbers:
n = pair_gcd_tol(n, i)
return n | [
"def",
"gcd_float",
"(",
"numbers",
",",
"tol",
"=",
"1e-8",
")",
":",
"def",
"pair_gcd_tol",
"(",
"a",
",",
"b",
")",
":",
"\"\"\"Calculate the Greatest Common Divisor of a and b.\n\n Unless b==0, the result will have the same sign as b (so that when\n b is divided by it, the result comes out positive).\n \"\"\"",
"while",
"b",
">",
"tol",
":",
"a",
",",
"b",
"=",
"b",
",",
"a",
"%",
"b",
"return",
"a",
"n",
"=",
"numbers",
"[",
"0",
"]",
"for",
"i",
"in",
"numbers",
":",
"n",
"=",
"pair_gcd_tol",
"(",
"n",
",",
"i",
")",
"return",
"n"
] | Returns the greatest common divisor for a sequence of numbers.
Uses a numerical tolerance, so can be used on floats
Args:
numbers: Sequence of numbers.
tol: Numerical tolerance
Returns:
(int) Greatest common divisor of numbers. | [
"Returns",
"the",
"greatest",
"common",
"divisor",
"for",
"a",
"sequence",
"of",
"numbers",
".",
"Uses",
"a",
"numerical",
"tolerance",
"so",
"can",
"be",
"used",
"on",
"floats"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/fractions.py#L54-L80 | train | 236,677 |
materialsvirtuallab/monty | monty/itertools.py | chunks | def chunks(items, n):
"""
Yield successive n-sized chunks from a list-like object.
>>> import pprint
>>> pprint.pprint(list(chunks(range(1, 25), 10)))
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
(11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
(21, 22, 23, 24)]
"""
it = iter(items)
chunk = tuple(itertools.islice(it, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(it, n)) | python | def chunks(items, n):
"""
Yield successive n-sized chunks from a list-like object.
>>> import pprint
>>> pprint.pprint(list(chunks(range(1, 25), 10)))
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
(11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
(21, 22, 23, 24)]
"""
it = iter(items)
chunk = tuple(itertools.islice(it, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(it, n)) | [
"def",
"chunks",
"(",
"items",
",",
"n",
")",
":",
"it",
"=",
"iter",
"(",
"items",
")",
"chunk",
"=",
"tuple",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
")",
")",
"while",
"chunk",
":",
"yield",
"chunk",
"chunk",
"=",
"tuple",
"(",
"itertools",
".",
"islice",
"(",
"it",
",",
"n",
")",
")"
] | Yield successive n-sized chunks from a list-like object.
>>> import pprint
>>> pprint.pprint(list(chunks(range(1, 25), 10)))
[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
(11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
(21, 22, 23, 24)] | [
"Yield",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"a",
"list",
"-",
"like",
"object",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L7-L21 | train | 236,678 |
materialsvirtuallab/monty | monty/itertools.py | iterator_from_slice | def iterator_from_slice(s):
"""
Constructs an iterator given a slice object s.
.. note::
The function returns an infinite iterator if s.stop is None
"""
import numpy as np
start = s.start if s.start is not None else 0
step = s.step if s.step is not None else 1
if s.stop is None:
# Infinite iterator.
return itertools.count(start=start, step=step)
else:
# xrange-like iterator that supports float.
return iter(np.arange(start, s.stop, step)) | python | def iterator_from_slice(s):
"""
Constructs an iterator given a slice object s.
.. note::
The function returns an infinite iterator if s.stop is None
"""
import numpy as np
start = s.start if s.start is not None else 0
step = s.step if s.step is not None else 1
if s.stop is None:
# Infinite iterator.
return itertools.count(start=start, step=step)
else:
# xrange-like iterator that supports float.
return iter(np.arange(start, s.stop, step)) | [
"def",
"iterator_from_slice",
"(",
"s",
")",
":",
"import",
"numpy",
"as",
"np",
"start",
"=",
"s",
".",
"start",
"if",
"s",
".",
"start",
"is",
"not",
"None",
"else",
"0",
"step",
"=",
"s",
".",
"step",
"if",
"s",
".",
"step",
"is",
"not",
"None",
"else",
"1",
"if",
"s",
".",
"stop",
"is",
"None",
":",
"# Infinite iterator.",
"return",
"itertools",
".",
"count",
"(",
"start",
"=",
"start",
",",
"step",
"=",
"step",
")",
"else",
":",
"# xrange-like iterator that supports float.",
"return",
"iter",
"(",
"np",
".",
"arange",
"(",
"start",
",",
"s",
".",
"stop",
",",
"step",
")",
")"
] | Constructs an iterator given a slice object s.
.. note::
The function returns an infinite iterator if s.stop is None | [
"Constructs",
"an",
"iterator",
"given",
"a",
"slice",
"object",
"s",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/itertools.py#L24-L41 | train | 236,679 |
materialsvirtuallab/monty | monty/termcolor.py | colored_map | def colored_map(text, cmap):
"""
Return colorized text. cmap is a dict mapping tokens to color options.
.. Example:
colored_key("foo bar", {bar: "green"})
colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}})
"""
if not __ISON: return text
for key, v in cmap.items():
if isinstance(v, dict):
text = text.replace(key, colored(key, **v))
else:
text = text.replace(key, colored(key, color=v))
return text | python | def colored_map(text, cmap):
"""
Return colorized text. cmap is a dict mapping tokens to color options.
.. Example:
colored_key("foo bar", {bar: "green"})
colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}})
"""
if not __ISON: return text
for key, v in cmap.items():
if isinstance(v, dict):
text = text.replace(key, colored(key, **v))
else:
text = text.replace(key, colored(key, color=v))
return text | [
"def",
"colored_map",
"(",
"text",
",",
"cmap",
")",
":",
"if",
"not",
"__ISON",
":",
"return",
"text",
"for",
"key",
",",
"v",
"in",
"cmap",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"key",
",",
"colored",
"(",
"key",
",",
"*",
"*",
"v",
")",
")",
"else",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"key",
",",
"colored",
"(",
"key",
",",
"color",
"=",
"v",
")",
")",
"return",
"text"
] | Return colorized text. cmap is a dict mapping tokens to color options.
.. Example:
colored_key("foo bar", {bar: "green"})
colored_key("foo bar", {bar: {"color": "green", "on_color": "on_red"}}) | [
"Return",
"colorized",
"text",
".",
"cmap",
"is",
"a",
"dict",
"mapping",
"tokens",
"to",
"color",
"options",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L161-L176 | train | 236,680 |
materialsvirtuallab/monty | monty/termcolor.py | cprint_map | def cprint_map(text, cmap, **kwargs):
"""
Print colorize text.
cmap is a dict mapping keys to color options.
kwargs are passed to print function
Example:
cprint_map("Hello world", {"Hello": "red"})
"""
try:
print(colored_map(text, cmap), **kwargs)
except TypeError:
# flush is not supported by py2.7
kwargs.pop("flush", None)
print(colored_map(text, cmap), **kwargs) | python | def cprint_map(text, cmap, **kwargs):
"""
Print colorize text.
cmap is a dict mapping keys to color options.
kwargs are passed to print function
Example:
cprint_map("Hello world", {"Hello": "red"})
"""
try:
print(colored_map(text, cmap), **kwargs)
except TypeError:
# flush is not supported by py2.7
kwargs.pop("flush", None)
print(colored_map(text, cmap), **kwargs) | [
"def",
"cprint_map",
"(",
"text",
",",
"cmap",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"print",
"(",
"colored_map",
"(",
"text",
",",
"cmap",
")",
",",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
":",
"# flush is not supported by py2.7",
"kwargs",
".",
"pop",
"(",
"\"flush\"",
",",
"None",
")",
"print",
"(",
"colored_map",
"(",
"text",
",",
"cmap",
")",
",",
"*",
"*",
"kwargs",
")"
] | Print colorize text.
cmap is a dict mapping keys to color options.
kwargs are passed to print function
Example:
cprint_map("Hello world", {"Hello": "red"}) | [
"Print",
"colorize",
"text",
".",
"cmap",
"is",
"a",
"dict",
"mapping",
"keys",
"to",
"color",
"options",
".",
"kwargs",
"are",
"passed",
"to",
"print",
"function"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L179-L193 | train | 236,681 |
materialsvirtuallab/monty | monty/json.py | MSONable.as_dict | def as_dict(self):
"""
A JSON serializable dict representation of an object.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__}
try:
parent_module = self.__class__.__module__.split('.')[0]
module_version = import_module(parent_module).__version__
d["@version"] = u"{}".format(module_version)
except AttributeError:
d["@version"] = None
args = getargspec(self.__class__.__init__).args
def recursive_as_dict(obj):
if isinstance(obj, (list, tuple)):
return [recursive_as_dict(it) for it in obj]
elif isinstance(obj, dict):
return {kk: recursive_as_dict(vv) for kk, vv in obj.items()}
elif hasattr(obj, "as_dict"):
return obj.as_dict()
return obj
for c in args:
if c != "self":
try:
a = self.__getattribute__(c)
except AttributeError:
try:
a = self.__getattribute__("_" + c)
except AttributeError:
raise NotImplementedError(
"Unable to automatically determine as_dict "
"format from class. MSONAble requires all "
"args to be present as either self.argname or "
"self._argname, and kwargs to be present under"
"a self.kwargs variable to automatically "
"determine the dict format. Alternatively, "
"you can implement both as_dict and from_dict.")
d[c] = recursive_as_dict(a)
if hasattr(self, "kwargs"):
d.update(**self.kwargs)
if hasattr(self, "_kwargs"):
d.update(**self._kwargs)
return d | python | def as_dict(self):
"""
A JSON serializable dict representation of an object.
"""
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__}
try:
parent_module = self.__class__.__module__.split('.')[0]
module_version = import_module(parent_module).__version__
d["@version"] = u"{}".format(module_version)
except AttributeError:
d["@version"] = None
args = getargspec(self.__class__.__init__).args
def recursive_as_dict(obj):
if isinstance(obj, (list, tuple)):
return [recursive_as_dict(it) for it in obj]
elif isinstance(obj, dict):
return {kk: recursive_as_dict(vv) for kk, vv in obj.items()}
elif hasattr(obj, "as_dict"):
return obj.as_dict()
return obj
for c in args:
if c != "self":
try:
a = self.__getattribute__(c)
except AttributeError:
try:
a = self.__getattribute__("_" + c)
except AttributeError:
raise NotImplementedError(
"Unable to automatically determine as_dict "
"format from class. MSONAble requires all "
"args to be present as either self.argname or "
"self._argname, and kwargs to be present under"
"a self.kwargs variable to automatically "
"determine the dict format. Alternatively, "
"you can implement both as_dict and from_dict.")
d[c] = recursive_as_dict(a)
if hasattr(self, "kwargs"):
d.update(**self.kwargs)
if hasattr(self, "_kwargs"):
d.update(**self._kwargs)
return d | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"\"@module\"",
":",
"self",
".",
"__class__",
".",
"__module__",
",",
"\"@class\"",
":",
"self",
".",
"__class__",
".",
"__name__",
"}",
"try",
":",
"parent_module",
"=",
"self",
".",
"__class__",
".",
"__module__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"module_version",
"=",
"import_module",
"(",
"parent_module",
")",
".",
"__version__",
"d",
"[",
"\"@version\"",
"]",
"=",
"u\"{}\"",
".",
"format",
"(",
"module_version",
")",
"except",
"AttributeError",
":",
"d",
"[",
"\"@version\"",
"]",
"=",
"None",
"args",
"=",
"getargspec",
"(",
"self",
".",
"__class__",
".",
"__init__",
")",
".",
"args",
"def",
"recursive_as_dict",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"recursive_as_dict",
"(",
"it",
")",
"for",
"it",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"kk",
":",
"recursive_as_dict",
"(",
"vv",
")",
"for",
"kk",
",",
"vv",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"elif",
"hasattr",
"(",
"obj",
",",
"\"as_dict\"",
")",
":",
"return",
"obj",
".",
"as_dict",
"(",
")",
"return",
"obj",
"for",
"c",
"in",
"args",
":",
"if",
"c",
"!=",
"\"self\"",
":",
"try",
":",
"a",
"=",
"self",
".",
"__getattribute__",
"(",
"c",
")",
"except",
"AttributeError",
":",
"try",
":",
"a",
"=",
"self",
".",
"__getattribute__",
"(",
"\"_\"",
"+",
"c",
")",
"except",
"AttributeError",
":",
"raise",
"NotImplementedError",
"(",
"\"Unable to automatically determine as_dict \"",
"\"format from class. MSONAble requires all \"",
"\"args to be present as either self.argname or \"",
"\"self._argname, and kwargs to be present under\"",
"\"a self.kwargs variable to automatically \"",
"\"determine the dict format. Alternatively, \"",
"\"you can implement both as_dict and from_dict.\"",
")",
"d",
"[",
"c",
"]",
"=",
"recursive_as_dict",
"(",
"a",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"kwargs\"",
")",
":",
"d",
".",
"update",
"(",
"*",
"*",
"self",
".",
"kwargs",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"_kwargs\"",
")",
":",
"d",
".",
"update",
"(",
"*",
"*",
"self",
".",
"_kwargs",
")",
"return",
"d"
] | A JSON serializable dict representation of an object. | [
"A",
"JSON",
"serializable",
"dict",
"representation",
"of",
"an",
"object",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L74-L120 | train | 236,682 |
materialsvirtuallab/monty | monty/json.py | MontyDecoder.process_decoded | def process_decoded(self, d):
"""
Recursive method to support decoding dicts and lists containing
pymatgen objects.
"""
if isinstance(d, dict):
if "@module" in d and "@class" in d:
modname = d["@module"]
classname = d["@class"]
else:
modname = None
classname = None
if modname and modname not in ["bson.objectid", "numpy"]:
if modname == "datetime" and classname == "datetime":
try:
dt = datetime.datetime.strptime(d["string"],
"%Y-%m-%d %H:%M:%S.%f")
except ValueError:
dt = datetime.datetime.strptime(d["string"],
"%Y-%m-%d %H:%M:%S")
return dt
mod = __import__(modname, globals(), locals(), [classname], 0)
if hasattr(mod, classname):
cls_ = getattr(mod, classname)
data = {k: v for k, v in d.items()
if not k.startswith("@")}
if hasattr(cls_, "from_dict"):
return cls_.from_dict(data)
elif np is not None and modname == "numpy" and classname == \
"array":
return np.array(d["data"], dtype=d["dtype"])
elif (bson is not None) and modname == "bson.objectid" and \
classname == "ObjectId":
return bson.objectid.ObjectId(d["oid"])
return {self.process_decoded(k): self.process_decoded(v)
for k, v in d.items()}
elif isinstance(d, list):
return [self.process_decoded(x) for x in d]
return d | python | def process_decoded(self, d):
"""
Recursive method to support decoding dicts and lists containing
pymatgen objects.
"""
if isinstance(d, dict):
if "@module" in d and "@class" in d:
modname = d["@module"]
classname = d["@class"]
else:
modname = None
classname = None
if modname and modname not in ["bson.objectid", "numpy"]:
if modname == "datetime" and classname == "datetime":
try:
dt = datetime.datetime.strptime(d["string"],
"%Y-%m-%d %H:%M:%S.%f")
except ValueError:
dt = datetime.datetime.strptime(d["string"],
"%Y-%m-%d %H:%M:%S")
return dt
mod = __import__(modname, globals(), locals(), [classname], 0)
if hasattr(mod, classname):
cls_ = getattr(mod, classname)
data = {k: v for k, v in d.items()
if not k.startswith("@")}
if hasattr(cls_, "from_dict"):
return cls_.from_dict(data)
elif np is not None and modname == "numpy" and classname == \
"array":
return np.array(d["data"], dtype=d["dtype"])
elif (bson is not None) and modname == "bson.objectid" and \
classname == "ObjectId":
return bson.objectid.ObjectId(d["oid"])
return {self.process_decoded(k): self.process_decoded(v)
for k, v in d.items()}
elif isinstance(d, list):
return [self.process_decoded(x) for x in d]
return d | [
"def",
"process_decoded",
"(",
"self",
",",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"if",
"\"@module\"",
"in",
"d",
"and",
"\"@class\"",
"in",
"d",
":",
"modname",
"=",
"d",
"[",
"\"@module\"",
"]",
"classname",
"=",
"d",
"[",
"\"@class\"",
"]",
"else",
":",
"modname",
"=",
"None",
"classname",
"=",
"None",
"if",
"modname",
"and",
"modname",
"not",
"in",
"[",
"\"bson.objectid\"",
",",
"\"numpy\"",
"]",
":",
"if",
"modname",
"==",
"\"datetime\"",
"and",
"classname",
"==",
"\"datetime\"",
":",
"try",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"d",
"[",
"\"string\"",
"]",
",",
"\"%Y-%m-%d %H:%M:%S.%f\"",
")",
"except",
"ValueError",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"d",
"[",
"\"string\"",
"]",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
"return",
"dt",
"mod",
"=",
"__import__",
"(",
"modname",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"[",
"classname",
"]",
",",
"0",
")",
"if",
"hasattr",
"(",
"mod",
",",
"classname",
")",
":",
"cls_",
"=",
"getattr",
"(",
"mod",
",",
"classname",
")",
"data",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
"if",
"not",
"k",
".",
"startswith",
"(",
"\"@\"",
")",
"}",
"if",
"hasattr",
"(",
"cls_",
",",
"\"from_dict\"",
")",
":",
"return",
"cls_",
".",
"from_dict",
"(",
"data",
")",
"elif",
"np",
"is",
"not",
"None",
"and",
"modname",
"==",
"\"numpy\"",
"and",
"classname",
"==",
"\"array\"",
":",
"return",
"np",
".",
"array",
"(",
"d",
"[",
"\"data\"",
"]",
",",
"dtype",
"=",
"d",
"[",
"\"dtype\"",
"]",
")",
"elif",
"(",
"bson",
"is",
"not",
"None",
")",
"and",
"modname",
"==",
"\"bson.objectid\"",
"and",
"classname",
"==",
"\"ObjectId\"",
":",
"return",
"bson",
".",
"objectid",
".",
"ObjectId",
"(",
"d",
"[",
"\"oid\"",
"]",
")",
"return",
"{",
"self",
".",
"process_decoded",
"(",
"k",
")",
":",
"self",
".",
"process_decoded",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"process_decoded",
"(",
"x",
")",
"for",
"x",
"in",
"d",
"]",
"return",
"d"
] | Recursive method to support decoding dicts and lists containing
pymatgen objects. | [
"Recursive",
"method",
"to",
"support",
"decoding",
"dicts",
"and",
"lists",
"containing",
"pymatgen",
"objects",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L210-L252 | train | 236,683 |
materialsvirtuallab/monty | monty/math.py | nCr | def nCr(n, r):
"""
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r)) | python | def nCr(n, r):
"""
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r)) | [
"def",
"nCr",
"(",
"n",
",",
"r",
")",
":",
"f",
"=",
"math",
".",
"factorial",
"return",
"int",
"(",
"f",
"(",
"n",
")",
"/",
"f",
"(",
"r",
")",
"/",
"f",
"(",
"n",
"-",
"r",
")",
")"
] | Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr. | [
"Calculates",
"nCr",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/math.py#L20-L32 | train | 236,684 |
materialsvirtuallab/monty | monty/math.py | nPr | def nPr(n, r):
"""
Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr.
"""
f = math.factorial
return int(f(n) / f(n-r)) | python | def nPr(n, r):
"""
Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr.
"""
f = math.factorial
return int(f(n) / f(n-r)) | [
"def",
"nPr",
"(",
"n",
",",
"r",
")",
":",
"f",
"=",
"math",
".",
"factorial",
"return",
"int",
"(",
"f",
"(",
"n",
")",
"/",
"f",
"(",
"n",
"-",
"r",
")",
")"
] | Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr. | [
"Calculates",
"nPr",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/math.py#L35-L47 | train | 236,685 |
materialsvirtuallab/monty | monty/shutil.py | copy_r | def copy_r(src, dst):
"""
Implements a recursive copy function similar to Unix's "cp -r" command.
Surprisingly, python does not have a real equivalent. shutil.copytree
only works if the destination directory is not present.
Args:
src (str): Source folder to copy.
dst (str): Destination folder.
"""
abssrc = os.path.abspath(src)
absdst = os.path.abspath(dst)
try:
os.makedirs(absdst)
except OSError:
# If absdst exists, an OSError is raised. We ignore this error.
pass
for f in os.listdir(abssrc):
fpath = os.path.join(abssrc, f)
if os.path.isfile(fpath):
shutil.copy(fpath, absdst)
elif not absdst.startswith(fpath):
copy_r(fpath, os.path.join(absdst, f))
else:
warnings.warn("Cannot copy %s to itself" % fpath) | python | def copy_r(src, dst):
"""
Implements a recursive copy function similar to Unix's "cp -r" command.
Surprisingly, python does not have a real equivalent. shutil.copytree
only works if the destination directory is not present.
Args:
src (str): Source folder to copy.
dst (str): Destination folder.
"""
abssrc = os.path.abspath(src)
absdst = os.path.abspath(dst)
try:
os.makedirs(absdst)
except OSError:
# If absdst exists, an OSError is raised. We ignore this error.
pass
for f in os.listdir(abssrc):
fpath = os.path.join(abssrc, f)
if os.path.isfile(fpath):
shutil.copy(fpath, absdst)
elif not absdst.startswith(fpath):
copy_r(fpath, os.path.join(absdst, f))
else:
warnings.warn("Cannot copy %s to itself" % fpath) | [
"def",
"copy_r",
"(",
"src",
",",
"dst",
")",
":",
"abssrc",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"src",
")",
"absdst",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"dst",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"absdst",
")",
"except",
"OSError",
":",
"# If absdst exists, an OSError is raised. We ignore this error.",
"pass",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"abssrc",
")",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"abssrc",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
":",
"shutil",
".",
"copy",
"(",
"fpath",
",",
"absdst",
")",
"elif",
"not",
"absdst",
".",
"startswith",
"(",
"fpath",
")",
":",
"copy_r",
"(",
"fpath",
",",
"os",
".",
"path",
".",
"join",
"(",
"absdst",
",",
"f",
")",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot copy %s to itself\"",
"%",
"fpath",
")"
] | Implements a recursive copy function similar to Unix's "cp -r" command.
Surprisingly, python does not have a real equivalent. shutil.copytree
only works if the destination directory is not present.
Args:
src (str): Source folder to copy.
dst (str): Destination folder. | [
"Implements",
"a",
"recursive",
"copy",
"function",
"similar",
"to",
"Unix",
"s",
"cp",
"-",
"r",
"command",
".",
"Surprisingly",
"python",
"does",
"not",
"have",
"a",
"real",
"equivalent",
".",
"shutil",
".",
"copytree",
"only",
"works",
"if",
"the",
"destination",
"directory",
"is",
"not",
"present",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L15-L40 | train | 236,686 |
materialsvirtuallab/monty | monty/shutil.py | gzip_dir | def gzip_dir(path, compresslevel=6):
"""
Gzips all files in a directory. Note that this is different from
shutil.make_archive, which creates a tar archive. The aim of this method
is to create gzipped files that can still be read using common Unix-style
commands like zless or zcat.
Args:
path (str): Path to directory.
compresslevel (int): Level of compression, 1-9. 9 is default for
GzipFile, 6 is default for gzip.
"""
for f in os.listdir(path):
full_f = os.path.join(path, f)
if not f.lower().endswith("gz"):
with open(full_f, 'rb') as f_in, \
GzipFile('{}.gz'.format(full_f), 'wb',
compresslevel=compresslevel) as f_out:
shutil.copyfileobj(f_in, f_out)
shutil.copystat(full_f,'{}.gz'.format(full_f))
os.remove(full_f) | python | def gzip_dir(path, compresslevel=6):
"""
Gzips all files in a directory. Note that this is different from
shutil.make_archive, which creates a tar archive. The aim of this method
is to create gzipped files that can still be read using common Unix-style
commands like zless or zcat.
Args:
path (str): Path to directory.
compresslevel (int): Level of compression, 1-9. 9 is default for
GzipFile, 6 is default for gzip.
"""
for f in os.listdir(path):
full_f = os.path.join(path, f)
if not f.lower().endswith("gz"):
with open(full_f, 'rb') as f_in, \
GzipFile('{}.gz'.format(full_f), 'wb',
compresslevel=compresslevel) as f_out:
shutil.copyfileobj(f_in, f_out)
shutil.copystat(full_f,'{}.gz'.format(full_f))
os.remove(full_f) | [
"def",
"gzip_dir",
"(",
"path",
",",
"compresslevel",
"=",
"6",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"full_f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"not",
"f",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\"gz\"",
")",
":",
"with",
"open",
"(",
"full_f",
",",
"'rb'",
")",
"as",
"f_in",
",",
"GzipFile",
"(",
"'{}.gz'",
".",
"format",
"(",
"full_f",
")",
",",
"'wb'",
",",
"compresslevel",
"=",
"compresslevel",
")",
"as",
"f_out",
":",
"shutil",
".",
"copyfileobj",
"(",
"f_in",
",",
"f_out",
")",
"shutil",
".",
"copystat",
"(",
"full_f",
",",
"'{}.gz'",
".",
"format",
"(",
"full_f",
")",
")",
"os",
".",
"remove",
"(",
"full_f",
")"
] | Gzips all files in a directory. Note that this is different from
shutil.make_archive, which creates a tar archive. The aim of this method
is to create gzipped files that can still be read using common Unix-style
commands like zless or zcat.
Args:
path (str): Path to directory.
compresslevel (int): Level of compression, 1-9. 9 is default for
GzipFile, 6 is default for gzip. | [
"Gzips",
"all",
"files",
"in",
"a",
"directory",
".",
"Note",
"that",
"this",
"is",
"different",
"from",
"shutil",
".",
"make_archive",
"which",
"creates",
"a",
"tar",
"archive",
".",
"The",
"aim",
"of",
"this",
"method",
"is",
"to",
"create",
"gzipped",
"files",
"that",
"can",
"still",
"be",
"read",
"using",
"common",
"Unix",
"-",
"style",
"commands",
"like",
"zless",
"or",
"zcat",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L43-L63 | train | 236,687 |
materialsvirtuallab/monty | monty/shutil.py | compress_file | def compress_file(filepath, compression="gz"):
"""
Compresses a file with the correct extension. Functions like standard
Unix command line gzip and bzip2 in the sense that the original
uncompressed files are not retained.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
"""
if compression not in ["gz", "bz2"]:
raise ValueError("Supported compression formats are 'gz' and 'bz2'.")
from monty.io import zopen
if not filepath.lower().endswith(".%s" % compression):
with open(filepath, 'rb') as f_in, \
zopen('%s.%s' % (filepath, compression), 'wb') as f_out:
f_out.writelines(f_in)
os.remove(filepath) | python | def compress_file(filepath, compression="gz"):
"""
Compresses a file with the correct extension. Functions like standard
Unix command line gzip and bzip2 in the sense that the original
uncompressed files are not retained.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
"""
if compression not in ["gz", "bz2"]:
raise ValueError("Supported compression formats are 'gz' and 'bz2'.")
from monty.io import zopen
if not filepath.lower().endswith(".%s" % compression):
with open(filepath, 'rb') as f_in, \
zopen('%s.%s' % (filepath, compression), 'wb') as f_out:
f_out.writelines(f_in)
os.remove(filepath) | [
"def",
"compress_file",
"(",
"filepath",
",",
"compression",
"=",
"\"gz\"",
")",
":",
"if",
"compression",
"not",
"in",
"[",
"\"gz\"",
",",
"\"bz2\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"Supported compression formats are 'gz' and 'bz2'.\"",
")",
"from",
"monty",
".",
"io",
"import",
"zopen",
"if",
"not",
"filepath",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".%s\"",
"%",
"compression",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"f_in",
",",
"zopen",
"(",
"'%s.%s'",
"%",
"(",
"filepath",
",",
"compression",
")",
",",
"'wb'",
")",
"as",
"f_out",
":",
"f_out",
".",
"writelines",
"(",
"f_in",
")",
"os",
".",
"remove",
"(",
"filepath",
")"
] | Compresses a file with the correct extension. Functions like standard
Unix command line gzip and bzip2 in the sense that the original
uncompressed files are not retained.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz". | [
"Compresses",
"a",
"file",
"with",
"the",
"correct",
"extension",
".",
"Functions",
"like",
"standard",
"Unix",
"command",
"line",
"gzip",
"and",
"bzip2",
"in",
"the",
"sense",
"that",
"the",
"original",
"uncompressed",
"files",
"are",
"not",
"retained",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L66-L84 | train | 236,688 |
materialsvirtuallab/monty | monty/shutil.py | compress_dir | def compress_dir(path, compression="gz"):
"""
Recursively compresses all files in a directory. Note that this
compresses all files singly, i.e., it does not create a tar archive. For
that, just use Python tarfile class.
Args:
path (str): Path to parent directory.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to gz.
"""
for parent, subdirs, files in os.walk(path):
for f in files:
compress_file(os.path.join(parent, f), compression=compression) | python | def compress_dir(path, compression="gz"):
"""
Recursively compresses all files in a directory. Note that this
compresses all files singly, i.e., it does not create a tar archive. For
that, just use Python tarfile class.
Args:
path (str): Path to parent directory.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to gz.
"""
for parent, subdirs, files in os.walk(path):
for f in files:
compress_file(os.path.join(parent, f), compression=compression) | [
"def",
"compress_dir",
"(",
"path",
",",
"compression",
"=",
"\"gz\"",
")",
":",
"for",
"parent",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"f",
"in",
"files",
":",
"compress_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"parent",
",",
"f",
")",
",",
"compression",
"=",
"compression",
")"
] | Recursively compresses all files in a directory. Note that this
compresses all files singly, i.e., it does not create a tar archive. For
that, just use Python tarfile class.
Args:
path (str): Path to parent directory.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to gz. | [
"Recursively",
"compresses",
"all",
"files",
"in",
"a",
"directory",
".",
"Note",
"that",
"this",
"compresses",
"all",
"files",
"singly",
"i",
".",
"e",
".",
"it",
"does",
"not",
"create",
"a",
"tar",
"archive",
".",
"For",
"that",
"just",
"use",
"Python",
"tarfile",
"class",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L87-L100 | train | 236,689 |
materialsvirtuallab/monty | monty/shutil.py | decompress_file | def decompress_file(filepath):
"""
Decompresses a file with the correct extension. Automatically detects
gz, bz2 or z extension.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
"""
toks = filepath.split(".")
file_ext = toks[-1].upper()
from monty.io import zopen
if file_ext in ["BZ2", "GZ", "Z"]:
with open(".".join(toks[0:-1]), 'wb') as f_out, \
zopen(filepath, 'rb') as f_in:
f_out.writelines(f_in)
os.remove(filepath) | python | def decompress_file(filepath):
"""
Decompresses a file with the correct extension. Automatically detects
gz, bz2 or z extension.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz".
"""
toks = filepath.split(".")
file_ext = toks[-1].upper()
from monty.io import zopen
if file_ext in ["BZ2", "GZ", "Z"]:
with open(".".join(toks[0:-1]), 'wb') as f_out, \
zopen(filepath, 'rb') as f_in:
f_out.writelines(f_in)
os.remove(filepath) | [
"def",
"decompress_file",
"(",
"filepath",
")",
":",
"toks",
"=",
"filepath",
".",
"split",
"(",
"\".\"",
")",
"file_ext",
"=",
"toks",
"[",
"-",
"1",
"]",
".",
"upper",
"(",
")",
"from",
"monty",
".",
"io",
"import",
"zopen",
"if",
"file_ext",
"in",
"[",
"\"BZ2\"",
",",
"\"GZ\"",
",",
"\"Z\"",
"]",
":",
"with",
"open",
"(",
"\".\"",
".",
"join",
"(",
"toks",
"[",
"0",
":",
"-",
"1",
"]",
")",
",",
"'wb'",
")",
"as",
"f_out",
",",
"zopen",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"f_in",
":",
"f_out",
".",
"writelines",
"(",
"f_in",
")",
"os",
".",
"remove",
"(",
"filepath",
")"
] | Decompresses a file with the correct extension. Automatically detects
gz, bz2 or z extension.
Args:
filepath (str): Path to file.
compression (str): A compression mode. Valid options are "gz" or
"bz2". Defaults to "gz". | [
"Decompresses",
"a",
"file",
"with",
"the",
"correct",
"extension",
".",
"Automatically",
"detects",
"gz",
"bz2",
"or",
"z",
"extension",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L103-L120 | train | 236,690 |
materialsvirtuallab/monty | monty/shutil.py | decompress_dir | def decompress_dir(path):
"""
Recursively decompresses all files in a directory.
Args:
path (str): Path to parent directory.
"""
for parent, subdirs, files in os.walk(path):
for f in files:
decompress_file(os.path.join(parent, f)) | python | def decompress_dir(path):
"""
Recursively decompresses all files in a directory.
Args:
path (str): Path to parent directory.
"""
for parent, subdirs, files in os.walk(path):
for f in files:
decompress_file(os.path.join(parent, f)) | [
"def",
"decompress_dir",
"(",
"path",
")",
":",
"for",
"parent",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"f",
"in",
"files",
":",
"decompress_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"parent",
",",
"f",
")",
")"
] | Recursively decompresses all files in a directory.
Args:
path (str): Path to parent directory. | [
"Recursively",
"decompresses",
"all",
"files",
"in",
"a",
"directory",
"."
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L123-L132 | train | 236,691 |
materialsvirtuallab/monty | monty/shutil.py | remove | def remove(path, follow_symlink=False):
"""
Implements an remove function that will delete files, folder trees and symlink trees
1.) Remove a file
2.) Remove a symlink and follow into with a recursive rm if follow_symlink
3.) Remove directory with rmtree
Args:
path (str): path to remove
follow_symlink(bool): follow symlinks and removes whatever is in them
"""
if os.path.isfile(path):
os.remove(path)
elif os.path.islink(path):
if follow_symlink:
remove(os.readlink(path))
os.unlink(path)
else:
shutil.rmtree(path) | python | def remove(path, follow_symlink=False):
"""
Implements an remove function that will delete files, folder trees and symlink trees
1.) Remove a file
2.) Remove a symlink and follow into with a recursive rm if follow_symlink
3.) Remove directory with rmtree
Args:
path (str): path to remove
follow_symlink(bool): follow symlinks and removes whatever is in them
"""
if os.path.isfile(path):
os.remove(path)
elif os.path.islink(path):
if follow_symlink:
remove(os.readlink(path))
os.unlink(path)
else:
shutil.rmtree(path) | [
"def",
"remove",
"(",
"path",
",",
"follow_symlink",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")",
"elif",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":",
"if",
"follow_symlink",
":",
"remove",
"(",
"os",
".",
"readlink",
"(",
"path",
")",
")",
"os",
".",
"unlink",
"(",
"path",
")",
"else",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")"
] | Implements an remove function that will delete files, folder trees and symlink trees
1.) Remove a file
2.) Remove a symlink and follow into with a recursive rm if follow_symlink
3.) Remove directory with rmtree
Args:
path (str): path to remove
follow_symlink(bool): follow symlinks and removes whatever is in them | [
"Implements",
"an",
"remove",
"function",
"that",
"will",
"delete",
"files",
"folder",
"trees",
"and",
"symlink",
"trees"
] | d99d6f3c68372d83489d28ff515566c93cd569e2 | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/shutil.py#L135-L154 | train | 236,692 |
fair-research/bdbag | bdbag/bdbag_utils.py | compute_hashes | def compute_hashes(obj, hashes=frozenset(['md5'])):
"""
Digests input data read from file-like object fd or passed directly as bytes-like object.
Compute hashes for multiple algorithms. Default is MD5.
Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTTP header.
"""
if not (hasattr(obj, 'read') or isinstance(obj, bytes)):
raise ValueError("Cannot compute hash for given input: a file-like object or bytes-like object is required")
hashers = dict()
for alg in hashes:
try:
hashers[alg] = hashlib.new(alg.lower())
except ValueError:
logging.warning("Unable to validate file contents using unknown hash algorithm: %s", alg)
while True:
if hasattr(obj, 'read'):
block = obj.read(1024 ** 2)
else:
block = obj
obj = None
if not block:
break
for i in hashers.values():
i.update(block)
hashes = dict()
for alg, h in hashers.items():
digest = h.hexdigest()
base64digest = base64.b64encode(h.digest())
# base64.b64encode returns str on python 2.7 and bytes on 3.x, so deal with that and always return a str
if not isinstance(base64digest, str) and isinstance(base64digest, bytes):
base64digest = base64digest.decode('ascii')
hashes[alg] = digest
hashes[alg + "_base64"] = base64digest
return hashes | python | def compute_hashes(obj, hashes=frozenset(['md5'])):
"""
Digests input data read from file-like object fd or passed directly as bytes-like object.
Compute hashes for multiple algorithms. Default is MD5.
Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTTP header.
"""
if not (hasattr(obj, 'read') or isinstance(obj, bytes)):
raise ValueError("Cannot compute hash for given input: a file-like object or bytes-like object is required")
hashers = dict()
for alg in hashes:
try:
hashers[alg] = hashlib.new(alg.lower())
except ValueError:
logging.warning("Unable to validate file contents using unknown hash algorithm: %s", alg)
while True:
if hasattr(obj, 'read'):
block = obj.read(1024 ** 2)
else:
block = obj
obj = None
if not block:
break
for i in hashers.values():
i.update(block)
hashes = dict()
for alg, h in hashers.items():
digest = h.hexdigest()
base64digest = base64.b64encode(h.digest())
# base64.b64encode returns str on python 2.7 and bytes on 3.x, so deal with that and always return a str
if not isinstance(base64digest, str) and isinstance(base64digest, bytes):
base64digest = base64digest.decode('ascii')
hashes[alg] = digest
hashes[alg + "_base64"] = base64digest
return hashes | [
"def",
"compute_hashes",
"(",
"obj",
",",
"hashes",
"=",
"frozenset",
"(",
"[",
"'md5'",
"]",
")",
")",
":",
"if",
"not",
"(",
"hasattr",
"(",
"obj",
",",
"'read'",
")",
"or",
"isinstance",
"(",
"obj",
",",
"bytes",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot compute hash for given input: a file-like object or bytes-like object is required\"",
")",
"hashers",
"=",
"dict",
"(",
")",
"for",
"alg",
"in",
"hashes",
":",
"try",
":",
"hashers",
"[",
"alg",
"]",
"=",
"hashlib",
".",
"new",
"(",
"alg",
".",
"lower",
"(",
")",
")",
"except",
"ValueError",
":",
"logging",
".",
"warning",
"(",
"\"Unable to validate file contents using unknown hash algorithm: %s\"",
",",
"alg",
")",
"while",
"True",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'read'",
")",
":",
"block",
"=",
"obj",
".",
"read",
"(",
"1024",
"**",
"2",
")",
"else",
":",
"block",
"=",
"obj",
"obj",
"=",
"None",
"if",
"not",
"block",
":",
"break",
"for",
"i",
"in",
"hashers",
".",
"values",
"(",
")",
":",
"i",
".",
"update",
"(",
"block",
")",
"hashes",
"=",
"dict",
"(",
")",
"for",
"alg",
",",
"h",
"in",
"hashers",
".",
"items",
"(",
")",
":",
"digest",
"=",
"h",
".",
"hexdigest",
"(",
")",
"base64digest",
"=",
"base64",
".",
"b64encode",
"(",
"h",
".",
"digest",
"(",
")",
")",
"# base64.b64encode returns str on python 2.7 and bytes on 3.x, so deal with that and always return a str",
"if",
"not",
"isinstance",
"(",
"base64digest",
",",
"str",
")",
"and",
"isinstance",
"(",
"base64digest",
",",
"bytes",
")",
":",
"base64digest",
"=",
"base64digest",
".",
"decode",
"(",
"'ascii'",
")",
"hashes",
"[",
"alg",
"]",
"=",
"digest",
"hashes",
"[",
"alg",
"+",
"\"_base64\"",
"]",
"=",
"base64digest",
"return",
"hashes"
] | Digests input data read from file-like object fd or passed directly as bytes-like object.
Compute hashes for multiple algorithms. Default is MD5.
Returns a tuple of a hex-encoded digest string and a base64-encoded value suitable for an HTTP header. | [
"Digests",
"input",
"data",
"read",
"from",
"file",
"-",
"like",
"object",
"fd",
"or",
"passed",
"directly",
"as",
"bytes",
"-",
"like",
"object",
".",
"Compute",
"hashes",
"for",
"multiple",
"algorithms",
".",
"Default",
"is",
"MD5",
".",
"Returns",
"a",
"tuple",
"of",
"a",
"hex",
"-",
"encoded",
"digest",
"string",
"and",
"a",
"base64",
"-",
"encoded",
"value",
"suitable",
"for",
"an",
"HTTP",
"header",
"."
] | 795229d1fb77721d0a2d024b34645319d15502cf | https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbag_utils.py#L221-L258 | train | 236,693 |
fair-research/bdbag | bdbag/bdbag_utils.py | compute_file_hashes | def compute_file_hashes(file_path, hashes=frozenset(['md5'])):
"""
Digests data read from file denoted by file_path.
"""
if not os.path.exists(file_path):
logging.warning("%s does not exist" % file_path)
return
else:
logging.debug("Computing [%s] hashes for file [%s]" % (','.join(hashes), file_path))
try:
with open(file_path, 'rb') as fd:
return compute_hashes(fd, hashes)
except (IOError, OSError) as e:
logging.warning("Error while calculating digest(s) for file %s: %s" % (file_path, str(e)))
raise | python | def compute_file_hashes(file_path, hashes=frozenset(['md5'])):
"""
Digests data read from file denoted by file_path.
"""
if not os.path.exists(file_path):
logging.warning("%s does not exist" % file_path)
return
else:
logging.debug("Computing [%s] hashes for file [%s]" % (','.join(hashes), file_path))
try:
with open(file_path, 'rb') as fd:
return compute_hashes(fd, hashes)
except (IOError, OSError) as e:
logging.warning("Error while calculating digest(s) for file %s: %s" % (file_path, str(e)))
raise | [
"def",
"compute_file_hashes",
"(",
"file_path",
",",
"hashes",
"=",
"frozenset",
"(",
"[",
"'md5'",
"]",
")",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"logging",
".",
"warning",
"(",
"\"%s does not exist\"",
"%",
"file_path",
")",
"return",
"else",
":",
"logging",
".",
"debug",
"(",
"\"Computing [%s] hashes for file [%s]\"",
"%",
"(",
"','",
".",
"join",
"(",
"hashes",
")",
",",
"file_path",
")",
")",
"try",
":",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"fd",
":",
"return",
"compute_hashes",
"(",
"fd",
",",
"hashes",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"logging",
".",
"warning",
"(",
"\"Error while calculating digest(s) for file %s: %s\"",
"%",
"(",
"file_path",
",",
"str",
"(",
"e",
")",
")",
")",
"raise"
] | Digests data read from file denoted by file_path. | [
"Digests",
"data",
"read",
"from",
"file",
"denoted",
"by",
"file_path",
"."
] | 795229d1fb77721d0a2d024b34645319d15502cf | https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbag_utils.py#L261-L276 | train | 236,694 |
fair-research/bdbag | bdbag/bdbagit.py | BDBag.validate | def validate(self, processes=1, fast=False, completeness_only=False, callback=None):
"""Checks the structure and contents are valid.
If you supply the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and accounted for,
instead of re-calculating fixities and comparing them against the
manifest. By default validate() will re-calculate fixities (fast=False).
"""
self._validate_structure()
self._validate_bagittxt()
self._validate_fetch()
self._validate_contents(processes=processes, fast=fast, completeness_only=completeness_only, callback=callback)
return True | python | def validate(self, processes=1, fast=False, completeness_only=False, callback=None):
"""Checks the structure and contents are valid.
If you supply the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and accounted for,
instead of re-calculating fixities and comparing them against the
manifest. By default validate() will re-calculate fixities (fast=False).
"""
self._validate_structure()
self._validate_bagittxt()
self._validate_fetch()
self._validate_contents(processes=processes, fast=fast, completeness_only=completeness_only, callback=callback)
return True | [
"def",
"validate",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"fast",
"=",
"False",
",",
"completeness_only",
"=",
"False",
",",
"callback",
"=",
"None",
")",
":",
"self",
".",
"_validate_structure",
"(",
")",
"self",
".",
"_validate_bagittxt",
"(",
")",
"self",
".",
"_validate_fetch",
"(",
")",
"self",
".",
"_validate_contents",
"(",
"processes",
"=",
"processes",
",",
"fast",
"=",
"fast",
",",
"completeness_only",
"=",
"completeness_only",
",",
"callback",
"=",
"callback",
")",
"return",
"True"
] | Checks the structure and contents are valid.
If you supply the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and accounted for,
instead of re-calculating fixities and comparing them against the
manifest. By default validate() will re-calculate fixities (fast=False). | [
"Checks",
"the",
"structure",
"and",
"contents",
"are",
"valid",
"."
] | 795229d1fb77721d0a2d024b34645319d15502cf | https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L473-L489 | train | 236,695 |
fair-research/bdbag | bdbag/bdbagit.py | BDBag._validate_fetch | def _validate_fetch(self):
"""Validate the fetch.txt file
Raises `BagError` for errors and otherwise returns no value
"""
for url, file_size, filename in self.fetch_entries():
# fetch_entries will raise a BagError for unsafe filenames
# so at this point we will check only that the URL is minimally
# well formed:
parsed_url = urlparse(url)
# only check for a scheme component since per the spec the URL field is actually a URI per
# RFC3986 (https://tools.ietf.org/html/rfc3986)
if not all(parsed_url.scheme):
raise BagError(_('Malformed URL in fetch.txt: %s') % url) | python | def _validate_fetch(self):
"""Validate the fetch.txt file
Raises `BagError` for errors and otherwise returns no value
"""
for url, file_size, filename in self.fetch_entries():
# fetch_entries will raise a BagError for unsafe filenames
# so at this point we will check only that the URL is minimally
# well formed:
parsed_url = urlparse(url)
# only check for a scheme component since per the spec the URL field is actually a URI per
# RFC3986 (https://tools.ietf.org/html/rfc3986)
if not all(parsed_url.scheme):
raise BagError(_('Malformed URL in fetch.txt: %s') % url) | [
"def",
"_validate_fetch",
"(",
"self",
")",
":",
"for",
"url",
",",
"file_size",
",",
"filename",
"in",
"self",
".",
"fetch_entries",
"(",
")",
":",
"# fetch_entries will raise a BagError for unsafe filenames",
"# so at this point we will check only that the URL is minimally",
"# well formed:",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"# only check for a scheme component since per the spec the URL field is actually a URI per",
"# RFC3986 (https://tools.ietf.org/html/rfc3986)",
"if",
"not",
"all",
"(",
"parsed_url",
".",
"scheme",
")",
":",
"raise",
"BagError",
"(",
"_",
"(",
"'Malformed URL in fetch.txt: %s'",
")",
"%",
"url",
")"
] | Validate the fetch.txt file
Raises `BagError` for errors and otherwise returns no value | [
"Validate",
"the",
"fetch",
".",
"txt",
"file"
] | 795229d1fb77721d0a2d024b34645319d15502cf | https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L491-L505 | train | 236,696 |
fair-research/bdbag | bdbag/bdbagit.py | BDBag._validate_completeness | def _validate_completeness(self):
"""
Verify that the actual file manifests match the files in the data directory
"""
errors = list()
# First we'll make sure there's no mismatch between the filesystem
# and the list of files in the manifest(s)
only_in_manifests, only_on_fs, only_in_fetch = self.compare_manifests_with_fs_and_fetch()
for path in only_in_manifests:
e = FileMissing(path)
LOGGER.warning(force_unicode(e))
errors.append(e)
for path in only_on_fs:
e = UnexpectedFile(path)
LOGGER.warning(force_unicode(e))
errors.append(e)
for path in only_in_fetch:
e = UnexpectedRemoteFile(path)
# this is non-fatal according to spec but the warning is still reasonable
LOGGER.warning(force_unicode(e))
if errors:
raise BagValidationError(_("Bag validation failed"), errors) | python | def _validate_completeness(self):
"""
Verify that the actual file manifests match the files in the data directory
"""
errors = list()
# First we'll make sure there's no mismatch between the filesystem
# and the list of files in the manifest(s)
only_in_manifests, only_on_fs, only_in_fetch = self.compare_manifests_with_fs_and_fetch()
for path in only_in_manifests:
e = FileMissing(path)
LOGGER.warning(force_unicode(e))
errors.append(e)
for path in only_on_fs:
e = UnexpectedFile(path)
LOGGER.warning(force_unicode(e))
errors.append(e)
for path in only_in_fetch:
e = UnexpectedRemoteFile(path)
# this is non-fatal according to spec but the warning is still reasonable
LOGGER.warning(force_unicode(e))
if errors:
raise BagValidationError(_("Bag validation failed"), errors) | [
"def",
"_validate_completeness",
"(",
"self",
")",
":",
"errors",
"=",
"list",
"(",
")",
"# First we'll make sure there's no mismatch between the filesystem",
"# and the list of files in the manifest(s)",
"only_in_manifests",
",",
"only_on_fs",
",",
"only_in_fetch",
"=",
"self",
".",
"compare_manifests_with_fs_and_fetch",
"(",
")",
"for",
"path",
"in",
"only_in_manifests",
":",
"e",
"=",
"FileMissing",
"(",
"path",
")",
"LOGGER",
".",
"warning",
"(",
"force_unicode",
"(",
"e",
")",
")",
"errors",
".",
"append",
"(",
"e",
")",
"for",
"path",
"in",
"only_on_fs",
":",
"e",
"=",
"UnexpectedFile",
"(",
"path",
")",
"LOGGER",
".",
"warning",
"(",
"force_unicode",
"(",
"e",
")",
")",
"errors",
".",
"append",
"(",
"e",
")",
"for",
"path",
"in",
"only_in_fetch",
":",
"e",
"=",
"UnexpectedRemoteFile",
"(",
"path",
")",
"# this is non-fatal according to spec but the warning is still reasonable",
"LOGGER",
".",
"warning",
"(",
"force_unicode",
"(",
"e",
")",
")",
"if",
"errors",
":",
"raise",
"BagValidationError",
"(",
"_",
"(",
"\"Bag validation failed\"",
")",
",",
"errors",
")"
] | Verify that the actual file manifests match the files in the data directory | [
"Verify",
"that",
"the",
"actual",
"file",
"manifests",
"match",
"the",
"files",
"in",
"the",
"data",
"directory"
] | 795229d1fb77721d0a2d024b34645319d15502cf | https://github.com/fair-research/bdbag/blob/795229d1fb77721d0a2d024b34645319d15502cf/bdbag/bdbagit.py#L523-L546 | train | 236,697 |
alertot/detectem | detectem/cli.py | get_detection_results | def get_detection_results(url, timeout, metadata=False, save_har=False):
""" Return results from detector.
This function prepares the environment loading the plugins,
getting the response and passing it to the detector.
In case of errors, it raises exceptions to be handled externally.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
logger.debug('[+] Starting detection with %(n)d plugins', {'n': len(plugins)})
response = get_response(url, plugins, timeout)
# Save HAR
if save_har:
fd, path = tempfile.mkstemp(suffix='.har')
logger.info(f'Saving HAR file to {path}')
with open(fd, 'w') as f:
json.dump(response['har'], f)
det = Detector(response, plugins, url)
softwares = det.get_results(metadata=metadata)
output = {
'url': url,
'softwares': softwares,
}
return output | python | def get_detection_results(url, timeout, metadata=False, save_har=False):
""" Return results from detector.
This function prepares the environment loading the plugins,
getting the response and passing it to the detector.
In case of errors, it raises exceptions to be handled externally.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
logger.debug('[+] Starting detection with %(n)d plugins', {'n': len(plugins)})
response = get_response(url, plugins, timeout)
# Save HAR
if save_har:
fd, path = tempfile.mkstemp(suffix='.har')
logger.info(f'Saving HAR file to {path}')
with open(fd, 'w') as f:
json.dump(response['har'], f)
det = Detector(response, plugins, url)
softwares = det.get_results(metadata=metadata)
output = {
'url': url,
'softwares': softwares,
}
return output | [
"def",
"get_detection_results",
"(",
"url",
",",
"timeout",
",",
"metadata",
"=",
"False",
",",
"save_har",
"=",
"False",
")",
":",
"plugins",
"=",
"load_plugins",
"(",
")",
"if",
"not",
"plugins",
":",
"raise",
"NoPluginsError",
"(",
"'No plugins found'",
")",
"logger",
".",
"debug",
"(",
"'[+] Starting detection with %(n)d plugins'",
",",
"{",
"'n'",
":",
"len",
"(",
"plugins",
")",
"}",
")",
"response",
"=",
"get_response",
"(",
"url",
",",
"plugins",
",",
"timeout",
")",
"# Save HAR",
"if",
"save_har",
":",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.har'",
")",
"logger",
".",
"info",
"(",
"f'Saving HAR file to {path}'",
")",
"with",
"open",
"(",
"fd",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"response",
"[",
"'har'",
"]",
",",
"f",
")",
"det",
"=",
"Detector",
"(",
"response",
",",
"plugins",
",",
"url",
")",
"softwares",
"=",
"det",
".",
"get_results",
"(",
"metadata",
"=",
"metadata",
")",
"output",
"=",
"{",
"'url'",
":",
"url",
",",
"'softwares'",
":",
"softwares",
",",
"}",
"return",
"output"
] | Return results from detector.
This function prepares the environment loading the plugins,
getting the response and passing it to the detector.
In case of errors, it raises exceptions to be handled externally. | [
"Return",
"results",
"from",
"detector",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L73-L106 | train | 236,698 |
alertot/detectem | detectem/cli.py | get_plugins | def get_plugins(metadata):
""" Return the registered plugins.
Load and return all registered plugins.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
results = []
for p in sorted(plugins.get_all(), key=attrgetter('name')):
if metadata:
data = {'name': p.name, 'homepage': p.homepage}
hints = getattr(p, 'hints', [])
if hints:
data['hints'] = hints
results.append(data)
else:
results.append(p.name)
return results | python | def get_plugins(metadata):
""" Return the registered plugins.
Load and return all registered plugins.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
results = []
for p in sorted(plugins.get_all(), key=attrgetter('name')):
if metadata:
data = {'name': p.name, 'homepage': p.homepage}
hints = getattr(p, 'hints', [])
if hints:
data['hints'] = hints
results.append(data)
else:
results.append(p.name)
return results | [
"def",
"get_plugins",
"(",
"metadata",
")",
":",
"plugins",
"=",
"load_plugins",
"(",
")",
"if",
"not",
"plugins",
":",
"raise",
"NoPluginsError",
"(",
"'No plugins found'",
")",
"results",
"=",
"[",
"]",
"for",
"p",
"in",
"sorted",
"(",
"plugins",
".",
"get_all",
"(",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'name'",
")",
")",
":",
"if",
"metadata",
":",
"data",
"=",
"{",
"'name'",
":",
"p",
".",
"name",
",",
"'homepage'",
":",
"p",
".",
"homepage",
"}",
"hints",
"=",
"getattr",
"(",
"p",
",",
"'hints'",
",",
"[",
"]",
")",
"if",
"hints",
":",
"data",
"[",
"'hints'",
"]",
"=",
"hints",
"results",
".",
"append",
"(",
"data",
")",
"else",
":",
"results",
".",
"append",
"(",
"p",
".",
"name",
")",
"return",
"results"
] | Return the registered plugins.
Load and return all registered plugins. | [
"Return",
"the",
"registered",
"plugins",
"."
] | b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1 | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L109-L128 | train | 236,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.