id
int32
0
252k
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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
3,700
bkabrda/flask-whooshee
flask_whooshee.py
Whooshee.create_index
def create_index(cls, app, wh): """Creates and opens an index for the given whoosheer and app. If the index already exists, it just opens it, otherwise it creates it first. :param app: The application instance. :param wh: The whoosheer instance for which a index should be create...
python
def create_index(cls, app, wh): """Creates and opens an index for the given whoosheer and app. If the index already exists, it just opens it, otherwise it creates it first. :param app: The application instance. :param wh: The whoosheer instance for which a index should be create...
[ "def", "create_index", "(", "cls", ",", "app", ",", "wh", ")", ":", "# TODO: do we really want/need to use camel casing?", "# everywhere else, there is just .lower()", "if", "app", ".", "extensions", "[", "'whooshee'", "]", "[", "'memory_storage'", "]", ":", "storage", ...
Creates and opens an index for the given whoosheer and app. If the index already exists, it just opens it, otherwise it creates it first. :param app: The application instance. :param wh: The whoosheer instance for which a index should be created.
[ "Creates", "and", "opens", "an", "index", "for", "the", "given", "whoosheer", "and", "app", ".", "If", "the", "index", "already", "exists", "it", "just", "opens", "it", "otherwise", "it", "creates", "it", "first", "." ]
773fc51ed53043bd5e92c65eadef5663845ae8c4
https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L375-L399
3,701
bkabrda/flask-whooshee
flask_whooshee.py
Whooshee.get_or_create_index
def get_or_create_index(cls, app, wh): """Gets a previously cached index or creates a new one for the given app and whoosheer. :param app: The application instance. :param wh: The whoosheer instance for which the index should be retrieved or created. """ ...
python
def get_or_create_index(cls, app, wh): """Gets a previously cached index or creates a new one for the given app and whoosheer. :param app: The application instance. :param wh: The whoosheer instance for which the index should be retrieved or created. """ ...
[ "def", "get_or_create_index", "(", "cls", ",", "app", ",", "wh", ")", ":", "if", "wh", "in", "app", ".", "extensions", "[", "'whooshee'", "]", "[", "'whoosheers_indexes'", "]", ":", "return", "app", ".", "extensions", "[", "'whooshee'", "]", "[", "'whoos...
Gets a previously cached index or creates a new one for the given app and whoosheer. :param app: The application instance. :param wh: The whoosheer instance for which the index should be retrieved or created.
[ "Gets", "a", "previously", "cached", "index", "or", "creates", "a", "new", "one", "for", "the", "given", "app", "and", "whoosheer", "." ]
773fc51ed53043bd5e92c65eadef5663845ae8c4
https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L410-L422
3,702
bkabrda/flask-whooshee
flask_whooshee.py
Whooshee.on_commit
def on_commit(self, changes): """Method that gets called when a model is changed. This serves to do the actual index writing. """ if _get_config(self)['enable_indexing'] is False: return None for wh in self.whoosheers: if not wh.auto_update: ...
python
def on_commit(self, changes): """Method that gets called when a model is changed. This serves to do the actual index writing. """ if _get_config(self)['enable_indexing'] is False: return None for wh in self.whoosheers: if not wh.auto_update: ...
[ "def", "on_commit", "(", "self", ",", "changes", ")", ":", "if", "_get_config", "(", "self", ")", "[", "'enable_indexing'", "]", "is", "False", ":", "return", "None", "for", "wh", "in", "self", ".", "whoosheers", ":", "if", "not", "wh", ".", "auto_upda...
Method that gets called when a model is changed. This serves to do the actual index writing.
[ "Method", "that", "gets", "called", "when", "a", "model", "is", "changed", ".", "This", "serves", "to", "do", "the", "actual", "index", "writing", "." ]
773fc51ed53043bd5e92c65eadef5663845ae8c4
https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L433-L454
3,703
bkabrda/flask-whooshee
flask_whooshee.py
Whooshee.reindex
def reindex(self): """Reindex all data This method retrieves all the data from the registered models and calls the ``update_<model>()`` function for every instance of such model. """ for wh in self.whoosheers: index = type(self).get_or_create_index(_get_app(s...
python
def reindex(self): """Reindex all data This method retrieves all the data from the registered models and calls the ``update_<model>()`` function for every instance of such model. """ for wh in self.whoosheers: index = type(self).get_or_create_index(_get_app(s...
[ "def", "reindex", "(", "self", ")", ":", "for", "wh", "in", "self", ".", "whoosheers", ":", "index", "=", "type", "(", "self", ")", ".", "get_or_create_index", "(", "_get_app", "(", "self", ")", ",", "wh", ")", "writer", "=", "index", ".", "writer", ...
Reindex all data This method retrieves all the data from the registered models and calls the ``update_<model>()`` function for every instance of such model.
[ "Reindex", "all", "data" ]
773fc51ed53043bd5e92c65eadef5663845ae8c4
https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L456-L470
3,704
spry-group/python-vultr
examples/basic_list.py
dump_info
def dump_info(): '''Shows various details about the account & servers''' vultr = Vultr(API_KEY) try: logging.info('Listing account info:\n%s', dumps( vultr.account.info(), indent=2 )) logging.info('Listing apps:\n%s', dumps( vultr.app.list(), indent=2 ...
python
def dump_info(): '''Shows various details about the account & servers''' vultr = Vultr(API_KEY) try: logging.info('Listing account info:\n%s', dumps( vultr.account.info(), indent=2 )) logging.info('Listing apps:\n%s', dumps( vultr.app.list(), indent=2 ...
[ "def", "dump_info", "(", ")", ":", "vultr", "=", "Vultr", "(", "API_KEY", ")", "try", ":", "logging", ".", "info", "(", "'Listing account info:\\n%s'", ",", "dumps", "(", "vultr", ".", "account", ".", "info", "(", ")", ",", "indent", "=", "2", ")", "...
Shows various details about the account & servers
[ "Shows", "various", "details", "about", "the", "account", "&", "servers" ]
bad1448f1df7b5dba70fd3d11434f32580f0b850
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/examples/basic_list.py#L19-L72
3,705
spry-group/python-vultr
vultr/utils.py
update_params
def update_params(params, updates): '''Merges updates into params''' params = params.copy() if isinstance(params, dict) else dict() params.update(updates) return params
python
def update_params(params, updates): '''Merges updates into params''' params = params.copy() if isinstance(params, dict) else dict() params.update(updates) return params
[ "def", "update_params", "(", "params", ",", "updates", ")", ":", "params", "=", "params", ".", "copy", "(", ")", "if", "isinstance", "(", "params", ",", "dict", ")", "else", "dict", "(", ")", "params", ".", "update", "(", "updates", ")", "return", "p...
Merges updates into params
[ "Merges", "updates", "into", "params" ]
bad1448f1df7b5dba70fd3d11434f32580f0b850
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/vultr/utils.py#L94-L98
3,706
spry-group/python-vultr
vultr/utils.py
VultrBase._request_get_helper
def _request_get_helper(self, url, params=None): '''API GET request helper''' if not isinstance(params, dict): params = dict() if self.api_key: params['api_key'] = self.api_key return requests.get(url, params=params, timeout=60)
python
def _request_get_helper(self, url, params=None): '''API GET request helper''' if not isinstance(params, dict): params = dict() if self.api_key: params['api_key'] = self.api_key return requests.get(url, params=params, timeout=60)
[ "def", "_request_get_helper", "(", "self", ",", "url", ",", "params", "=", "None", ")", ":", "if", "not", "isinstance", "(", "params", ",", "dict", ")", ":", "params", "=", "dict", "(", ")", "if", "self", ".", "api_key", ":", "params", "[", "'api_key...
API GET request helper
[ "API", "GET", "request", "helper" ]
bad1448f1df7b5dba70fd3d11434f32580f0b850
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/vultr/utils.py#L26-L33
3,707
spry-group/python-vultr
vultr/utils.py
VultrBase._request_post_helper
def _request_post_helper(self, url, params=None): '''API POST helper''' if self.api_key: query = {'api_key': self.api_key} return requests.post(url, params=query, data=params, timeout=60)
python
def _request_post_helper(self, url, params=None): '''API POST helper''' if self.api_key: query = {'api_key': self.api_key} return requests.post(url, params=query, data=params, timeout=60)
[ "def", "_request_post_helper", "(", "self", ",", "url", ",", "params", "=", "None", ")", ":", "if", "self", ".", "api_key", ":", "query", "=", "{", "'api_key'", ":", "self", ".", "api_key", "}", "return", "requests", ".", "post", "(", "url", ",", "pa...
API POST helper
[ "API", "POST", "helper" ]
bad1448f1df7b5dba70fd3d11434f32580f0b850
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/vultr/utils.py#L35-L39
3,708
spry-group/python-vultr
vultr/utils.py
VultrBase._request_helper
def _request_helper(self, url, params, method): '''API request helper method''' try: if method == 'POST': return self._request_post_helper(url, params) elif method == 'GET': return self._request_get_helper(url, params) raise VultrError(...
python
def _request_helper(self, url, params, method): '''API request helper method''' try: if method == 'POST': return self._request_post_helper(url, params) elif method == 'GET': return self._request_get_helper(url, params) raise VultrError(...
[ "def", "_request_helper", "(", "self", ",", "url", ",", "params", ",", "method", ")", ":", "try", ":", "if", "method", "==", "'POST'", ":", "return", "self", ".", "_request_post_helper", "(", "url", ",", "params", ")", "elif", "method", "==", "'GET'", ...
API request helper method
[ "API", "request", "helper", "method" ]
bad1448f1df7b5dba70fd3d11434f32580f0b850
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/vultr/utils.py#L41-L50
3,709
spry-group/python-vultr
examples/basic_haltRunning.py
halt_running
def halt_running(): '''Halts all running servers''' vultr = Vultr(API_KEY) try: serverList = vultr.server.list() #logging.info('Listing servers:\n%s', dumps( #serverList, indent=2 #)) except VultrError as ex: logging.error('VultrError: %s', ex) f...
python
def halt_running(): '''Halts all running servers''' vultr = Vultr(API_KEY) try: serverList = vultr.server.list() #logging.info('Listing servers:\n%s', dumps( #serverList, indent=2 #)) except VultrError as ex: logging.error('VultrError: %s', ex) f...
[ "def", "halt_running", "(", ")", ":", "vultr", "=", "Vultr", "(", "API_KEY", ")", "try", ":", "serverList", "=", "vultr", ".", "server", ".", "list", "(", ")", "#logging.info('Listing servers:\\n%s', dumps(", "#serverList, indent=2", "#))", "except", "VultrError",...
Halts all running servers
[ "Halts", "all", "running", "servers" ]
bad1448f1df7b5dba70fd3d11434f32580f0b850
https://github.com/spry-group/python-vultr/blob/bad1448f1df7b5dba70fd3d11434f32580f0b850/examples/basic_haltRunning.py#L18-L33
3,710
inspirehep/refextract
refextract/references/tag.py
tag_arxiv
def tag_arxiv(line): """Tag arxiv report numbers We handle arXiv in 2 ways: * starting with arXiv:1022.1111 * this format exactly 9999.9999 We also format the output to the standard arxiv notation: * arXiv:2007.12.1111 * arXiv:2007.12.1111v2 """ def tagger(match): groups = m...
python
def tag_arxiv(line): """Tag arxiv report numbers We handle arXiv in 2 ways: * starting with arXiv:1022.1111 * this format exactly 9999.9999 We also format the output to the standard arxiv notation: * arXiv:2007.12.1111 * arXiv:2007.12.1111v2 """ def tagger(match): groups = m...
[ "def", "tag_arxiv", "(", "line", ")", ":", "def", "tagger", "(", "match", ")", ":", "groups", "=", "match", ".", "groupdict", "(", ")", "if", "match", ".", "group", "(", "'suffix'", ")", ":", "groups", "[", "'suffix'", "]", "=", "' '", "+", "groups...
Tag arxiv report numbers We handle arXiv in 2 ways: * starting with arXiv:1022.1111 * this format exactly 9999.9999 We also format the output to the standard arxiv notation: * arXiv:2007.12.1111 * arXiv:2007.12.1111v2
[ "Tag", "arxiv", "report", "numbers" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/tag.py#L360-L384
3,711
inspirehep/refextract
refextract/references/tag.py
tag_arxiv_more
def tag_arxiv_more(line): """Tag old arxiv report numbers Either formats: * hep-th/1234567 * arXiv:1022111 [hep-ph] which transforms to hep-ph/1022111 """ line = RE_ARXIV_CATCHUP.sub(ur"\g<suffix>/\g<year>\g<month>\g<num>", line) for report_re, report_repl in RE_OLD_ARXIV: report_n...
python
def tag_arxiv_more(line): """Tag old arxiv report numbers Either formats: * hep-th/1234567 * arXiv:1022111 [hep-ph] which transforms to hep-ph/1022111 """ line = RE_ARXIV_CATCHUP.sub(ur"\g<suffix>/\g<year>\g<month>\g<num>", line) for report_re, report_repl in RE_OLD_ARXIV: report_n...
[ "def", "tag_arxiv_more", "(", "line", ")", ":", "line", "=", "RE_ARXIV_CATCHUP", ".", "sub", "(", "ur\"\\g<suffix>/\\g<year>\\g<month>\\g<num>\"", ",", "line", ")", "for", "report_re", ",", "report_repl", "in", "RE_OLD_ARXIV", ":", "report_number", "=", "report_repl...
Tag old arxiv report numbers Either formats: * hep-th/1234567 * arXiv:1022111 [hep-ph] which transforms to hep-ph/1022111
[ "Tag", "old", "arxiv", "report", "numbers" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/tag.py#L387-L402
3,712
inspirehep/refextract
refextract/references/tag.py
tag_pos_volume
def tag_pos_volume(line): """Tag POS volume number POS is journal that has special volume numbers e.g. PoS LAT2007 (2007) 369 """ def tagger(match): groups = match.groupdict() try: year = match.group('year') except IndexError: # Extract year from volu...
python
def tag_pos_volume(line): """Tag POS volume number POS is journal that has special volume numbers e.g. PoS LAT2007 (2007) 369 """ def tagger(match): groups = match.groupdict() try: year = match.group('year') except IndexError: # Extract year from volu...
[ "def", "tag_pos_volume", "(", "line", ")", ":", "def", "tagger", "(", "match", ")", ":", "groups", "=", "match", ".", "groupdict", "(", ")", "try", ":", "year", "=", "match", ".", "group", "(", "'year'", ")", "except", "IndexError", ":", "# Extract yea...
Tag POS volume number POS is journal that has special volume numbers e.g. PoS LAT2007 (2007) 369
[ "Tag", "POS", "volume", "number" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/tag.py#L405-L436
3,713
inspirehep/refextract
refextract/references/tag.py
find_numeration_more
def find_numeration_more(line): """Look for other numeration in line.""" # First, attempt to use marked-up titles patterns = ( re_correct_numeration_2nd_try_ptn1, re_correct_numeration_2nd_try_ptn2, re_correct_numeration_2nd_try_ptn3, re_correct_numeration_2nd_try_ptn4, )...
python
def find_numeration_more(line): """Look for other numeration in line.""" # First, attempt to use marked-up titles patterns = ( re_correct_numeration_2nd_try_ptn1, re_correct_numeration_2nd_try_ptn2, re_correct_numeration_2nd_try_ptn3, re_correct_numeration_2nd_try_ptn4, )...
[ "def", "find_numeration_more", "(", "line", ")", ":", "# First, attempt to use marked-up titles", "patterns", "=", "(", "re_correct_numeration_2nd_try_ptn1", ",", "re_correct_numeration_2nd_try_ptn2", ",", "re_correct_numeration_2nd_try_ptn3", ",", "re_correct_numeration_2nd_try_ptn4...
Look for other numeration in line.
[ "Look", "for", "other", "numeration", "in", "line", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/tag.py#L456-L481
3,714
inspirehep/refextract
refextract/references/tag.py
identify_ibids
def identify_ibids(line): """Find IBIDs within the line, record their position and length, and replace them with underscores. @param line: (string) the working reference line @return: (tuple) containing 2 dictionaries and a string: Dictionary: matched IBID text: (Key: position of IBI...
python
def identify_ibids(line): """Find IBIDs within the line, record their position and length, and replace them with underscores. @param line: (string) the working reference line @return: (tuple) containing 2 dictionaries and a string: Dictionary: matched IBID text: (Key: position of IBI...
[ "def", "identify_ibids", "(", "line", ")", ":", "ibid_match_txt", "=", "{", "}", "# Record details of each matched ibid:", "for", "m_ibid", "in", "re_ibid", ".", "finditer", "(", "line", ")", ":", "ibid_match_txt", "[", "m_ibid", ".", "start", "(", ")", "]", ...
Find IBIDs within the line, record their position and length, and replace them with underscores. @param line: (string) the working reference line @return: (tuple) containing 2 dictionaries and a string: Dictionary: matched IBID text: (Key: position of IBID in line;...
[ "Find", "IBIDs", "within", "the", "line", "record", "their", "position", "and", "length", "and", "replace", "them", "with", "underscores", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/tag.py#L1052-L1070
3,715
inspirehep/refextract
refextract/references/tag.py
find_numeration
def find_numeration(line): """Given a reference line, attempt to locate instances of citation 'numeration' in the line. @param line: (string) the reference line. @return: (string) the reference line after numeration has been checked and possibly recognized/marked-up. """ pattern...
python
def find_numeration(line): """Given a reference line, attempt to locate instances of citation 'numeration' in the line. @param line: (string) the reference line. @return: (string) the reference line after numeration has been checked and possibly recognized/marked-up. """ pattern...
[ "def", "find_numeration", "(", "line", ")", ":", "patterns", "=", "(", "# vol,page,year", "re_numeration_vol_page_yr", ",", "re_numeration_vol_nucphys_page_yr", ",", "re_numeration_nucphys_vol_page_yr", ",", "# With sub volume", "re_numeration_vol_subvol_nucphys_yr_page", ",", ...
Given a reference line, attempt to locate instances of citation 'numeration' in the line. @param line: (string) the reference line. @return: (string) the reference line after numeration has been checked and possibly recognized/marked-up.
[ "Given", "a", "reference", "line", "attempt", "to", "locate", "instances", "of", "citation", "numeration", "in", "the", "line", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/tag.py#L1083-L1127
3,716
inspirehep/refextract
refextract/references/engine.py
remove_reference_line_marker
def remove_reference_line_marker(line): """Trim a reference line's 'marker' from the beginning of the line. @param line: (string) - the reference line. @return: (tuple) containing two strings: + The reference line's marker (or if there was not one, a 'space' charact...
python
def remove_reference_line_marker(line): """Trim a reference line's 'marker' from the beginning of the line. @param line: (string) - the reference line. @return: (tuple) containing two strings: + The reference line's marker (or if there was not one, a 'space' charact...
[ "def", "remove_reference_line_marker", "(", "line", ")", ":", "# Get patterns to identify reference-line marker patterns:", "marker_patterns", "=", "get_reference_line_numeration_marker_patterns", "(", ")", "line", "=", "line", ".", "lstrip", "(", ")", "marker_match", "=", ...
Trim a reference line's 'marker' from the beginning of the line. @param line: (string) - the reference line. @return: (tuple) containing two strings: + The reference line's marker (or if there was not one, a 'space' character. + The reference line with ...
[ "Trim", "a", "reference", "line", "s", "marker", "from", "the", "beginning", "of", "the", "line", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L92-L114
3,717
inspirehep/refextract
refextract/references/engine.py
roman2arabic
def roman2arabic(num): """Convert numbers from roman to arabic This function expects a string like XXII and outputs an integer """ t = 0 p = 0 for r in num: n = 10 ** (205558 % ord(r) % 7) % 9995 t += n - 2 * p % n p = n return t
python
def roman2arabic(num): """Convert numbers from roman to arabic This function expects a string like XXII and outputs an integer """ t = 0 p = 0 for r in num: n = 10 ** (205558 % ord(r) % 7) % 9995 t += n - 2 * p % n p = n return t
[ "def", "roman2arabic", "(", "num", ")", ":", "t", "=", "0", "p", "=", "0", "for", "r", "in", "num", ":", "n", "=", "10", "**", "(", "205558", "%", "ord", "(", "r", ")", "%", "7", ")", "%", "9995", "t", "+=", "n", "-", "2", "*", "p", "%"...
Convert numbers from roman to arabic This function expects a string like XXII and outputs an integer
[ "Convert", "numbers", "from", "roman", "to", "arabic" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L117-L129
3,718
inspirehep/refextract
refextract/references/engine.py
format_report_number
def format_report_number(citation_elements): """Format report numbers that are missing a dash e.g. CERN-LCHH2003-01 to CERN-LHCC-2003-01 """ re_report = re.compile(ur'^(?P<name>[A-Z-]+)(?P<nums>[\d-]+)$', re.UNICODE) for el in citation_elements: if el['type'] == 'REPORTNUMBER': ...
python
def format_report_number(citation_elements): """Format report numbers that are missing a dash e.g. CERN-LCHH2003-01 to CERN-LHCC-2003-01 """ re_report = re.compile(ur'^(?P<name>[A-Z-]+)(?P<nums>[\d-]+)$', re.UNICODE) for el in citation_elements: if el['type'] == 'REPORTNUMBER': ...
[ "def", "format_report_number", "(", "citation_elements", ")", ":", "re_report", "=", "re", ".", "compile", "(", "ur'^(?P<name>[A-Z-]+)(?P<nums>[\\d-]+)$'", ",", "re", ".", "UNICODE", ")", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]...
Format report numbers that are missing a dash e.g. CERN-LCHH2003-01 to CERN-LHCC-2003-01
[ "Format", "report", "numbers", "that", "are", "missing", "a", "dash" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L171-L184
3,719
inspirehep/refextract
refextract/references/engine.py
format_hep
def format_hep(citation_elements): """Format hep-th report numbers with a dash e.g. replaces hep-th-9711200 with hep-th/9711200 """ prefixes = ('astro-ph-', 'hep-th-', 'hep-ph-', 'hep-ex-', 'hep-lat-', 'math-ph-') for el in citation_elements: if el['type'] == 'REPORTNUMBER':...
python
def format_hep(citation_elements): """Format hep-th report numbers with a dash e.g. replaces hep-th-9711200 with hep-th/9711200 """ prefixes = ('astro-ph-', 'hep-th-', 'hep-ph-', 'hep-ex-', 'hep-lat-', 'math-ph-') for el in citation_elements: if el['type'] == 'REPORTNUMBER':...
[ "def", "format_hep", "(", "citation_elements", ")", ":", "prefixes", "=", "(", "'astro-ph-'", ",", "'hep-th-'", ",", "'hep-ph-'", ",", "'hep-ex-'", ",", "'hep-lat-'", ",", "'math-ph-'", ")", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'typ...
Format hep-th report numbers with a dash e.g. replaces hep-th-9711200 with hep-th/9711200
[ "Format", "hep", "-", "th", "report", "numbers", "with", "a", "dash" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L187-L200
3,720
inspirehep/refextract
refextract/references/engine.py
look_for_books
def look_for_books(citation_elements, kbs): """Look for books in our kb Create book tags by using the authors and the title to find books in our knowledge base """ title = None for el in citation_elements: if el['type'] == 'QUOTED': title = el break if title...
python
def look_for_books(citation_elements, kbs): """Look for books in our kb Create book tags by using the authors and the title to find books in our knowledge base """ title = None for el in citation_elements: if el['type'] == 'QUOTED': title = el break if title...
[ "def", "look_for_books", "(", "citation_elements", ",", "kbs", ")", ":", "title", "=", "None", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", "==", "'QUOTED'", ":", "title", "=", "el", "break", "if", "title", ":", "normalize...
Look for books in our kb Create book tags by using the authors and the title to find books in our knowledge base
[ "Look", "for", "books", "in", "our", "kb" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L215-L239
3,721
inspirehep/refextract
refextract/references/engine.py
split_volume_from_journal
def split_volume_from_journal(citation_elements): """Split volume from journal title We need this because sometimes the volume is attached to the journal title instead of the volume. In those cases we move it here from the title to the volume """ for el in citation_elements: if el['type...
python
def split_volume_from_journal(citation_elements): """Split volume from journal title We need this because sometimes the volume is attached to the journal title instead of the volume. In those cases we move it here from the title to the volume """ for el in citation_elements: if el['type...
[ "def", "split_volume_from_journal", "(", "citation_elements", ")", ":", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", "==", "'JOURNAL'", "and", "';'", "in", "el", "[", "'title'", "]", ":", "el", "[", "'title'", "]", ",", "s...
Split volume from journal title We need this because sometimes the volume is attached to the journal title instead of the volume. In those cases we move it here from the title to the volume
[ "Split", "volume", "from", "journal", "title" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L242-L253
3,722
inspirehep/refextract
refextract/references/engine.py
remove_b_for_nucl_phys
def remove_b_for_nucl_phys(citation_elements): """Removes b from the volume of some journals Removes the B from the volume for Nucl.Phys.Proc.Suppl. because in INSPIRE that journal is handled differently. """ for el in citation_elements: if el['type'] == 'JOURNAL' and el['title'] == 'Nucl.P...
python
def remove_b_for_nucl_phys(citation_elements): """Removes b from the volume of some journals Removes the B from the volume for Nucl.Phys.Proc.Suppl. because in INSPIRE that journal is handled differently. """ for el in citation_elements: if el['type'] == 'JOURNAL' and el['title'] == 'Nucl.P...
[ "def", "remove_b_for_nucl_phys", "(", "citation_elements", ")", ":", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", "==", "'JOURNAL'", "and", "el", "[", "'title'", "]", "==", "'Nucl.Phys.Proc.Suppl.'", "and", "'volume'", "in", "el...
Removes b from the volume of some journals Removes the B from the volume for Nucl.Phys.Proc.Suppl. because in INSPIRE that journal is handled differently.
[ "Removes", "b", "from", "the", "volume", "of", "some", "journals" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L256-L267
3,723
inspirehep/refextract
refextract/references/engine.py
mangle_volume
def mangle_volume(citation_elements): """Make sure the volume letter is before the volume number e.g. transforms 100B to B100 """ volume_re = re.compile(ur"(\d+)([A-Z])", re.U | re.I) for el in citation_elements: if el['type'] == 'JOURNAL': matches = volume_re.match(el['volume']...
python
def mangle_volume(citation_elements): """Make sure the volume letter is before the volume number e.g. transforms 100B to B100 """ volume_re = re.compile(ur"(\d+)([A-Z])", re.U | re.I) for el in citation_elements: if el['type'] == 'JOURNAL': matches = volume_re.match(el['volume']...
[ "def", "mangle_volume", "(", "citation_elements", ")", ":", "volume_re", "=", "re", ".", "compile", "(", "ur\"(\\d+)([A-Z])\"", ",", "re", ".", "U", "|", "re", ".", "I", ")", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", ...
Make sure the volume letter is before the volume number e.g. transforms 100B to B100
[ "Make", "sure", "the", "volume", "letter", "is", "before", "the", "volume", "number" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L270-L282
3,724
inspirehep/refextract
refextract/references/engine.py
split_citations
def split_citations(citation_elements): """Split a citation line in multiple citations We handle the case where the author has put 2 citations in the same line but split with ; or some other method. """ splitted_citations = [] new_elements = [] current_recid = None current_doi = None ...
python
def split_citations(citation_elements): """Split a citation line in multiple citations We handle the case where the author has put 2 citations in the same line but split with ; or some other method. """ splitted_citations = [] new_elements = [] current_recid = None current_doi = None ...
[ "def", "split_citations", "(", "citation_elements", ")", ":", "splitted_citations", "=", "[", "]", "new_elements", "=", "[", "]", "current_recid", "=", "None", "current_doi", "=", "None", "def", "check_ibid", "(", "current_elements", ",", "trigger_el", ")", ":",...
Split a citation line in multiple citations We handle the case where the author has put 2 citations in the same line but split with ; or some other method.
[ "Split", "a", "citation", "line", "in", "multiple", "citations" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L307-L383
3,725
inspirehep/refextract
refextract/references/engine.py
look_for_hdl
def look_for_hdl(citation_elements): """Looks for handle identifiers in the misc txt of the citation elements When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process """ for el in list(citation_elements): matched_hdl = re_hdl.finditer(el['m...
python
def look_for_hdl(citation_elements): """Looks for handle identifiers in the misc txt of the citation elements When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process """ for el in list(citation_elements): matched_hdl = re_hdl.finditer(el['m...
[ "def", "look_for_hdl", "(", "citation_elements", ")", ":", "for", "el", "in", "list", "(", "citation_elements", ")", ":", "matched_hdl", "=", "re_hdl", ".", "finditer", "(", "el", "[", "'misc_txt'", "]", ")", "for", "match", "in", "reversed", "(", "list", ...
Looks for handle identifiers in the misc txt of the citation elements When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process
[ "Looks", "for", "handle", "identifiers", "in", "the", "misc", "txt", "of", "the", "citation", "elements" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L596-L609
3,726
inspirehep/refextract
refextract/references/engine.py
look_for_hdl_urls
def look_for_hdl_urls(citation_elements): """Looks for handle identifiers that have already been identified as urls When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process """ for el in citation_elements: if el['type'] == 'URL': ...
python
def look_for_hdl_urls(citation_elements): """Looks for handle identifiers that have already been identified as urls When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process """ for el in citation_elements: if el['type'] == 'URL': ...
[ "def", "look_for_hdl_urls", "(", "citation_elements", ")", ":", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", "==", "'URL'", ":", "match", "=", "re_hdl", ".", "match", "(", "el", "[", "'url_string'", "]", ")", "if", "match"...
Looks for handle identifiers that have already been identified as urls When finding an hdl, creates a new HDL element. @param citation_elements: (list) elements to process
[ "Looks", "for", "handle", "identifiers", "that", "have", "already", "been", "identified", "as", "urls" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L612-L625
3,727
inspirehep/refextract
refextract/references/engine.py
parse_reference_line
def parse_reference_line(ref_line, kbs, bad_titles_count={}, linker_callback=None): """Parse one reference line @input a string representing a single reference bullet @output parsed references (a list of elements objects) """ # Strip the 'marker' (e.g. [1]) from this reference line: line_marker...
python
def parse_reference_line(ref_line, kbs, bad_titles_count={}, linker_callback=None): """Parse one reference line @input a string representing a single reference bullet @output parsed references (a list of elements objects) """ # Strip the 'marker' (e.g. [1]) from this reference line: line_marker...
[ "def", "parse_reference_line", "(", "ref_line", ",", "kbs", ",", "bad_titles_count", "=", "{", "}", ",", "linker_callback", "=", "None", ")", ":", "# Strip the 'marker' (e.g. [1]) from this reference line:", "line_marker", ",", "ref_line", "=", "remove_reference_line_mark...
Parse one reference line @input a string representing a single reference bullet @output parsed references (a list of elements objects)
[ "Parse", "one", "reference", "line" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L639-L716
3,728
inspirehep/refextract
refextract/references/engine.py
search_for_book_in_misc
def search_for_book_in_misc(citation, kbs): """Searches for books in the misc_txt field if the citation is not recognized as anything like a journal, book, etc. """ citation_year = year_from_citation(citation) for citation_element in citation: LOGGER.debug(u"Searching for book title in: %s", cit...
python
def search_for_book_in_misc(citation, kbs): """Searches for books in the misc_txt field if the citation is not recognized as anything like a journal, book, etc. """ citation_year = year_from_citation(citation) for citation_element in citation: LOGGER.debug(u"Searching for book title in: %s", cit...
[ "def", "search_for_book_in_misc", "(", "citation", ",", "kbs", ")", ":", "citation_year", "=", "year_from_citation", "(", "citation", ")", "for", "citation_element", "in", "citation", ":", "LOGGER", ".", "debug", "(", "u\"Searching for book title in: %s\"", ",", "ci...
Searches for books in the misc_txt field if the citation is not recognized as anything like a journal, book, etc.
[ "Searches", "for", "books", "in", "the", "misc_txt", "field", "if", "the", "citation", "is", "not", "recognized", "as", "anything", "like", "a", "journal", "book", "etc", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L736-L779
3,729
inspirehep/refextract
refextract/references/engine.py
map_tag_to_subfield
def map_tag_to_subfield(tag_type, line, cur_misc_txt, dest): """Create a new reference element""" closing_tag = '</cds.%s>' % tag_type # extract the institutional report-number from the line: idx_closing_tag = line.find(closing_tag) # Sanity check - did we find a closing tag? if idx_closing_tag ...
python
def map_tag_to_subfield(tag_type, line, cur_misc_txt, dest): """Create a new reference element""" closing_tag = '</cds.%s>' % tag_type # extract the institutional report-number from the line: idx_closing_tag = line.find(closing_tag) # Sanity check - did we find a closing tag? if idx_closing_tag ...
[ "def", "map_tag_to_subfield", "(", "tag_type", ",", "line", ",", "cur_misc_txt", ",", "dest", ")", ":", "closing_tag", "=", "'</cds.%s>'", "%", "tag_type", "# extract the institutional report-number from the line:", "idx_closing_tag", "=", "line", ".", "find", "(", "c...
Create a new reference element
[ "Create", "a", "new", "reference", "element" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L1292-L1312
3,730
inspirehep/refextract
refextract/references/engine.py
remove_leading_garbage_lines_from_reference_section
def remove_leading_garbage_lines_from_reference_section(ref_sectn): """Sometimes, the first lines of the extracted references are completely blank or email addresses. These must be removed as they are not references. @param ref_sectn: (list) of strings - the reference section lines @retu...
python
def remove_leading_garbage_lines_from_reference_section(ref_sectn): """Sometimes, the first lines of the extracted references are completely blank or email addresses. These must be removed as they are not references. @param ref_sectn: (list) of strings - the reference section lines @retu...
[ "def", "remove_leading_garbage_lines_from_reference_section", "(", "ref_sectn", ")", ":", "p_email", "=", "re", ".", "compile", "(", "ur'^\\s*e\\-?mail'", ",", "re", ".", "UNICODE", ")", "while", "ref_sectn", "and", "(", "ref_sectn", "[", "0", "]", ".", "isspace...
Sometimes, the first lines of the extracted references are completely blank or email addresses. These must be removed as they are not references. @param ref_sectn: (list) of strings - the reference section lines @return: (list) of strings - the reference section without leading blank...
[ "Sometimes", "the", "first", "lines", "of", "the", "extracted", "references", "are", "completely", "blank", "or", "email", "addresses", ".", "These", "must", "be", "removed", "as", "they", "are", "not", "references", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L1364-L1375
3,731
inspirehep/refextract
refextract/references/engine.py
get_plaintext_document_body
def get_plaintext_document_body(fpath, keep_layout=False): """Given a file-path to a full-text, return a list of unicode strings whereby each string is a line of the fulltext. In the case of a plain-text document, this simply means reading the contents in from the file. In the case of a PDF how...
python
def get_plaintext_document_body(fpath, keep_layout=False): """Given a file-path to a full-text, return a list of unicode strings whereby each string is a line of the fulltext. In the case of a plain-text document, this simply means reading the contents in from the file. In the case of a PDF how...
[ "def", "get_plaintext_document_body", "(", "fpath", ",", "keep_layout", "=", "False", ")", ":", "textbody", "=", "[", "]", "mime_type", "=", "magic", ".", "from_file", "(", "fpath", ",", "mime", "=", "True", ")", "if", "mime_type", "==", "\"text/plain\"", ...
Given a file-path to a full-text, return a list of unicode strings whereby each string is a line of the fulltext. In the case of a plain-text document, this simply means reading the contents in from the file. In the case of a PDF however, this means converting the document to plaintext. ...
[ "Given", "a", "file", "-", "path", "to", "a", "full", "-", "text", "return", "a", "list", "of", "unicode", "strings", "whereby", "each", "string", "is", "a", "line", "of", "the", "fulltext", ".", "In", "the", "case", "of", "a", "plain", "-", "text", ...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L1384-L1408
3,732
inspirehep/refextract
refextract/references/engine.py
parse_references
def parse_references(reference_lines, recid=None, override_kbs_files=None, reference_format=u"{title} {volume} ({year}) {page}", linker_callback=None): """Parse a list of references Given a list of raw reference lines (list of ...
python
def parse_references(reference_lines, recid=None, override_kbs_files=None, reference_format=u"{title} {volume} ({year}) {page}", linker_callback=None): """Parse a list of references Given a list of raw reference lines (list of ...
[ "def", "parse_references", "(", "reference_lines", ",", "recid", "=", "None", ",", "override_kbs_files", "=", "None", ",", "reference_format", "=", "u\"{title} {volume} ({year}) {page}\"", ",", "linker_callback", "=", "None", ")", ":", "# RefExtract knowledge bases", "k...
Parse a list of references Given a list of raw reference lines (list of strings), output a list of dictionaries containing the parsed references
[ "Parse", "a", "list", "of", "references" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L1411-L1428
3,733
inspirehep/refextract
refextract/references/engine.py
build_stats
def build_stats(counts): """Return stats information from counts structure.""" stats = { 'status': 0, 'reportnum': counts['reportnum'], 'title': counts['title'], 'author': counts['auth_group'], 'url': counts['url'], 'doi': counts['doi'], 'misc': counts['mi...
python
def build_stats(counts): """Return stats information from counts structure.""" stats = { 'status': 0, 'reportnum': counts['reportnum'], 'title': counts['title'], 'author': counts['auth_group'], 'url': counts['url'], 'doi': counts['doi'], 'misc': counts['mi...
[ "def", "build_stats", "(", "counts", ")", ":", "stats", "=", "{", "'status'", ":", "0", ",", "'reportnum'", ":", "counts", "[", "'reportnum'", "]", ",", "'title'", ":", "counts", "[", "'title'", "]", ",", "'author'", ":", "counts", "[", "'auth_group'", ...
Return stats information from counts structure.
[ "Return", "stats", "information", "from", "counts", "structure", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L1431-L1446
3,734
inspirehep/refextract
refextract/documents/pdf.py
replace_undesirable_characters
def replace_undesirable_characters(line): """ Replace certain bad characters in a text line. @param line: (string) the text line in which bad characters are to be replaced. @return: (string) the text line after the bad characters have been replaced. """ # T...
python
def replace_undesirable_characters(line): """ Replace certain bad characters in a text line. @param line: (string) the text line in which bad characters are to be replaced. @return: (string) the text line after the bad characters have been replaced. """ # T...
[ "def", "replace_undesirable_characters", "(", "line", ")", ":", "# These are separate because we want a particular order", "for", "bad_string", ",", "replacement", "in", "UNDESIRABLE_STRING_REPLACEMENTS", ":", "line", "=", "line", ".", "replace", "(", "bad_string", ",", "...
Replace certain bad characters in a text line. @param line: (string) the text line in which bad characters are to be replaced. @return: (string) the text line after the bad characters have been replaced.
[ "Replace", "certain", "bad", "characters", "in", "a", "text", "line", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/pdf.py#L434-L449
3,735
inspirehep/refextract
refextract/documents/pdf.py
convert_PDF_to_plaintext
def convert_PDF_to_plaintext(fpath, keep_layout=False): """ Convert PDF to txt using pdftotext Take the path to a PDF file and run pdftotext for this file, capturing the output. @param fpath: (string) path to the PDF file @return: (list) of unicode strings (contents of the PDF file translated i...
python
def convert_PDF_to_plaintext(fpath, keep_layout=False): """ Convert PDF to txt using pdftotext Take the path to a PDF file and run pdftotext for this file, capturing the output. @param fpath: (string) path to the PDF file @return: (list) of unicode strings (contents of the PDF file translated i...
[ "def", "convert_PDF_to_plaintext", "(", "fpath", ",", "keep_layout", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "CFG_PATH_PDFTOTEXT", ")", ":", "raise", "IOError", "(", "'Missing pdftotext executable'", ")", "if", "keep_layout", ...
Convert PDF to txt using pdftotext Take the path to a PDF file and run pdftotext for this file, capturing the output. @param fpath: (string) path to the PDF file @return: (list) of unicode strings (contents of the PDF file translated into plaintext; each string is a line in the document.)
[ "Convert", "PDF", "to", "txt", "using", "pdftotext" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/pdf.py#L452-L499
3,736
inspirehep/refextract
refextract/authors/regexs.py
get_author_affiliation_numeration_str
def get_author_affiliation_numeration_str(punct=None): """The numeration which can be applied to author names. Numeration is sometimes found next to authors of papers. @return: (string), which can be compiled into a regex; identifies numeration next to an author name. """ # FIXME cater for star...
python
def get_author_affiliation_numeration_str(punct=None): """The numeration which can be applied to author names. Numeration is sometimes found next to authors of papers. @return: (string), which can be compiled into a regex; identifies numeration next to an author name. """ # FIXME cater for star...
[ "def", "get_author_affiliation_numeration_str", "(", "punct", "=", "None", ")", ":", "# FIXME cater for start or end numeration (ie two puncs)", "# Number to look for, either general or specific", "re_number", "=", "r'(?:\\d\\d?)'", "re_chained_numbers", "=", "r\"(?:(?:[,;]\\s*%s\\.?\\...
The numeration which can be applied to author names. Numeration is sometimes found next to authors of papers. @return: (string), which can be compiled into a regex; identifies numeration next to an author name.
[ "The", "numeration", "which", "can", "be", "applied", "to", "author", "names", ".", "Numeration", "is", "sometimes", "found", "next", "to", "authors", "of", "papers", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/authors/regexs.py#L36-L64
3,737
inspirehep/refextract
refextract/authors/regexs.py
make_auth_regex_str
def make_auth_regex_str(etal, initial_surname_author=None, surname_initial_author=None): """ Returns a regular expression to be used to identify groups of author names in a citation. This method contains patterns for default authors, so no arguments are needed for the most reliable form of m...
python
def make_auth_regex_str(etal, initial_surname_author=None, surname_initial_author=None): """ Returns a regular expression to be used to identify groups of author names in a citation. This method contains patterns for default authors, so no arguments are needed for the most reliable form of m...
[ "def", "make_auth_regex_str", "(", "etal", ",", "initial_surname_author", "=", "None", ",", "surname_initial_author", "=", "None", ")", ":", "if", "not", "initial_surname_author", ":", "# Standard author, with a maximum of 6 initials, and a surname.", "# The Initials MUST be up...
Returns a regular expression to be used to identify groups of author names in a citation. This method contains patterns for default authors, so no arguments are needed for the most reliable form of matching. The returned author pattern is capable of: 1. Identifying single authors, with ...
[ "Returns", "a", "regular", "expression", "to", "be", "used", "to", "identify", "groups", "of", "author", "names", "in", "a", "citation", ".", "This", "method", "contains", "patterns", "for", "default", "authors", "so", "no", "arguments", "are", "needed", "fo...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/authors/regexs.py#L192-L350
3,738
inspirehep/refextract
refextract/references/find.py
find_reference_section
def find_reference_section(docbody): """Search in document body for its reference section. More precisely, find the first line of the reference section. Effectively, the function starts at the end of a document and works backwards, line-by-line, looking for the title of a reference section. It stop...
python
def find_reference_section(docbody): """Search in document body for its reference section. More precisely, find the first line of the reference section. Effectively, the function starts at the end of a document and works backwards, line-by-line, looking for the title of a reference section. It stop...
[ "def", "find_reference_section", "(", "docbody", ")", ":", "ref_details", "=", "None", "title_patterns", "=", "get_reference_section_title_patterns", "(", ")", "# Try to find refs section title:", "for", "title_pattern", "in", "title_patterns", ":", "# Look for title pattern ...
Search in document body for its reference section. More precisely, find the first line of the reference section. Effectively, the function starts at the end of a document and works backwards, line-by-line, looking for the title of a reference section. It stops when (if) it finds something that it c...
[ "Search", "in", "document", "body", "for", "its", "reference", "section", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/find.py#L45-L97
3,739
inspirehep/refextract
refextract/references/find.py
find_numeration
def find_numeration(docbody, title): """Find numeration pattern 1st try to find numeration in the title e.g. References [4] Riotto... 2nd find the numeration alone in the line after the title e.g. References 1 Riotto 3rnd find the numeration in the following line e.g. ...
python
def find_numeration(docbody, title): """Find numeration pattern 1st try to find numeration in the title e.g. References [4] Riotto... 2nd find the numeration alone in the line after the title e.g. References 1 Riotto 3rnd find the numeration in the following line e.g. ...
[ "def", "find_numeration", "(", "docbody", ",", "title", ")", ":", "ref_details", ",", "found_title", "=", "find_numeration_in_title", "(", "docbody", ",", "title", ")", "if", "not", "ref_details", ":", "ref_details", ",", "found_title", "=", "find_numeration_in_bo...
Find numeration pattern 1st try to find numeration in the title e.g. References [4] Riotto... 2nd find the numeration alone in the line after the title e.g. References 1 Riotto 3rnd find the numeration in the following line e.g. References [1] Riotto
[ "Find", "numeration", "pattern" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/find.py#L181-L203
3,740
inspirehep/refextract
refextract/references/text.py
get_reference_lines
def get_reference_lines(docbody, ref_sect_start_line, ref_sect_end_line, ref_sect_title, ref_line_marker_ptn, title_marker_same_line): """After the reference section of a document has been identif...
python
def get_reference_lines(docbody, ref_sect_start_line, ref_sect_end_line, ref_sect_title, ref_line_marker_ptn, title_marker_same_line): """After the reference section of a document has been identif...
[ "def", "get_reference_lines", "(", "docbody", ",", "ref_sect_start_line", ",", "ref_sect_end_line", ",", "ref_sect_title", ",", "ref_line_marker_ptn", ",", "title_marker_same_line", ")", ":", "start_idx", "=", "ref_sect_start_line", "if", "title_marker_same_line", ":", "#...
After the reference section of a document has been identified, and the first and last lines of the reference section have been recorded, this function is called to take the reference lines out of the document body. The document's reference lines are returned in a list of strings whereby each...
[ "After", "the", "reference", "section", "of", "a", "document", "has", "been", "identified", "and", "the", "first", "and", "last", "lines", "of", "the", "reference", "section", "have", "been", "recorded", "this", "function", "is", "called", "to", "take", "the...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L91-L142
3,741
inspirehep/refextract
refextract/references/text.py
match_pagination
def match_pagination(ref_line): """Remove footer pagination from references lines""" pattern = ur'\(?\[?(\d{1,4})\]?\)?\.?\s*$' re_footer = re.compile(pattern, re.UNICODE) match = re_footer.match(ref_line) if match: return int(match.group(1)) return None
python
def match_pagination(ref_line): """Remove footer pagination from references lines""" pattern = ur'\(?\[?(\d{1,4})\]?\)?\.?\s*$' re_footer = re.compile(pattern, re.UNICODE) match = re_footer.match(ref_line) if match: return int(match.group(1)) return None
[ "def", "match_pagination", "(", "ref_line", ")", ":", "pattern", "=", "ur'\\(?\\[?(\\d{1,4})\\]?\\)?\\.?\\s*$'", "re_footer", "=", "re", ".", "compile", "(", "pattern", ",", "re", ".", "UNICODE", ")", "match", "=", "re_footer", ".", "match", "(", "ref_line", "...
Remove footer pagination from references lines
[ "Remove", "footer", "pagination", "from", "references", "lines" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L145-L152
3,742
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", ".", ...
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
3,743
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, UnknownDocumentTyp...
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, UnknownDocumentTyp...
[ "def", "extract_references_from_url", "(", "url", ",", "headers", "=", "None", ",", "chunk_size", "=", "1024", ",", "*", "*", "kwargs", ")", ":", "# Get temporary filepath to download to", "filename", ",", "filepath", "=", "mkstemp", "(", "suffix", "=", "u\"_{0}...
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...
[ "Extract", "references", "from", "the", "pdf", "specified", "in", "the", "url", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L54-L99
3,744
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 lo...
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 lo...
[ "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", ".", "pa...
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} {volum...
[ "Extract", "references", "from", "a", "local", "pdf", "file", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L102-L151
3,745
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, ...
python
def extract_references_from_string(source, is_only_references=True, recid=None, reference_format="{title} {volume} ({year}) {page}", linker_callback=None, ...
[ "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}...
[ "Extract", "references", "from", "a", "raw", "string", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L154-L201
3,746
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 = par...
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 = par...
[ "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_...
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
3,747
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 c...
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 c...
[ "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.", "#...
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
3,748
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 correspondi...
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 correspondi...
[ "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'", "...
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) ...
[ "Create", "the", "final", "representation", "of", "the", "reference", "information", "." ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L71-L161
3,749
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: ...
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: ...
[ "def", "extract_texkeys_from_pdf", "(", "pdf_file", ")", ":", "with", "open", "(", "pdf_file", ",", "'rb'", ")", "as", "pdf_stream", ":", "try", ":", "pdf", "=", "PdfFileReader", "(", "pdf_stream", ",", "strict", "=", "False", ")", "destinations", "=", "pd...
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
3,750
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. "...
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. "...
[ "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"...
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
3,751
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...
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...
[ "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})[\\.\\,...
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
3,752
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. """ ...
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. """ ...
[ "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...
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", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L874-L894
3,753
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...
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...
[ "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. ...
[ "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", "o...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L897-L913
3,754
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....
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....
[ "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", ...
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", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L45-L95
3,755
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 ...
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 ...
[ "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", "=", ...
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
3,756
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 _c...
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 _c...
[ "def", "repair_broken_urls", "(", "line", ")", ":", "def", "_chop_spaces_in_url_match", "(", "m", ")", ":", "\"\"\"Suppresses spaces in a matched URL.\"\"\"", "return", "m", ".", "group", "(", "1", ")", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "for", "p...
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
3,757
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 ...
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 ...
[ "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", ".", "findite...
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 diction...
[ "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
3,758
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 docu...
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 docu...
[ "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 - c...
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, ...
[ "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
3,759
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 represe...
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 represe...
[ "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",...
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...
[ "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
3,760
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 t...
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 t...
[ "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", "="...
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 i...
[ "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", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L254-L320
3,761
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 t...
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 t...
[ "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...
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 i...
[ "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", "...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L323-L377
3,762
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: ...
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: ...
[ "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", ...
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-...
[ "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
3,763
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)): ...
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)): ...
[ "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", ")", "!=...
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
3,764
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=/...
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=/...
[ "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", "=", "';'", ".", "j...
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...
[ "Create", "cache", "key", "for", "kbs", "caches", "instances" ]
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L112-L130
3,765
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. ...
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. ...
[ "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)\"", ...
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 ...
[ "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...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L161-L174
3,766
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 ...
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 ...
[ "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",...
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-s...
[ "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", "s...
d70e3787be3c495a3a07d1517b53f81d51c788c7
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L222-L415
3,767
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 ...
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 ...
[ "def", "_cmp_bystrlen_reverse", "(", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", ">", "len", "(", "b", ")", ":", "return", "-", "1", "elif", "len", "(", "a", ")", "<", "len", "(", "b", ")", ":", "return", "1", "else", ":", "return", ...
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)...
[ "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
3,768
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) a...
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) a...
[ "def", "build_special_journals_kb", "(", "fpath", ")", ":", "journals", "=", "set", "(", ")", "with", "file_resolving", "(", "fpath", ")", "as", "fh", ":", "for", "line", "in", "fh", ":", "# Skip commented lines", "if", "line", ".", "startswith", "(", "'#'...
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
3,769
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: ...
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: ...
[ "def", "build_journals_re_kb", "(", "fpath", ")", ":", "def", "make_tuple", "(", "match", ")", ":", "regexp", "=", "match", ".", "group", "(", "'seek'", ")", "repl", "=", "match", ".", "group", "(", "'repl'", ")", "return", "regexp", ",", "repl", "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
3,770
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_ty...
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_ty...
[ "def", "_parse_content_type", "(", "content_type", ":", "Optional", "[", "str", "]", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "str", "]", ":", "if", "not", "content_type", ":", "return", "None", ",", "\"utf-8\"", "else", ":", "type_", ...
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
3,771
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 stri...
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 stri...
[ "def", "_decode_body", "(", "content_type", ":", "Optional", "[", "str", "]", ",", "body", ":", "bytes", ",", "*", ",", "strict", ":", "bool", "=", "False", ")", "->", "Any", ":", "type_", ",", "encoding", "=", "_parse_content_type", "(", "content_type",...
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
3,772
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 Validatio...
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 Validatio...
[ "def", "validate_event", "(", "payload", ":", "bytes", ",", "*", ",", "signature", ":", "str", ",", "secret", ":", "str", ")", "->", "None", ":", "# https://developer.github.com/webhooks/securing/#validating-payloads-from-github", "signature_prefix", "=", "\"sha1=\"", ...
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
3,773
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 wi...
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 wi...
[ "def", "accept_format", "(", "*", ",", "version", ":", "str", "=", "\"v3\"", ",", "media", ":", "Optional", "[", "str", "]", "=", "None", ",", "json", ":", "bool", "=", "True", ")", "->", "str", ":", "# https://developer.github.com/v3/media/", "# https://d...
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 ...
[ "Construct", "the", "specification", "of", "the", "format", "that", "a", "request", "should", "return", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L125-L145
3,774
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. GitHu...
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. GitHu...
[ "def", "create_headers", "(", "requester", ":", "str", ",", "*", ",", "accept", ":", "str", "=", "accept_format", "(", ")", ",", "oauth_token", ":", "Optional", "[", "str", "]", "=", "None", ",", "jwt", ":", "Optional", "[", "str", "]", "=", "None", ...
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...
[ "Create", "a", "dict", "representing", "GitHub", "-", "specific", "header", "fields", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L148-L186
3,775
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 f...
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 f...
[ "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 r...
[ "Decipher", "an", "HTTP", "response", "for", "a", "GitHub", "API", "request", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L269-L326
3,776
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 dic...
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 dic...
[ "def", "format_url", "(", "url", ":", "str", ",", "url_vars", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "DOMAIN", ",", "url", ")", "# Works even if 'url' is fully-qualifie...
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
3,777
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 ...
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 ...
[ "def", "from_http", "(", "cls", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", ",", "*", ",", "secret", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "\"Event\"", ":", "if", "\"x-hub-signature\"", ...
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 con...
[ "Construct", "an", "event", "from", "HTTP", "headers", "and", "JSON", "body", "data", "." ]
24feb6c35bba3966c6cc9ec2896729578f6d7ccc
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L90-L122
3,778
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: ...
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: ...
[ "def", "from_http", "(", "cls", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ")", "->", "Optional", "[", "\"RateLimit\"", "]", ":", "try", ":", "limit", "=", "int", "(", "headers", "[", "\"x-ratelimit-limit\"", "]", ")", "remaining", "=...
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
3,779
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 ...
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 ...
[ "def", "add", "(", "self", ",", "func", ":", "AsyncCallback", ",", "event_type", ":", "str", ",", "*", "*", "data_detail", ":", "Any", ")", "->", "None", ":", "if", "len", "(", "data_detail", ")", ">", "1", ":", "msg", "=", "(", ")", "raise", "Ty...
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
3,780
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...
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...
[ "async", "def", "_make_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", ",", "data", ":", "Any", ",", "accept", ":", "str", ",", "jwt", ":", "Opt", "[", "str", ...
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
3,781
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 ...
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 ...
[ "async", "def", "getitem", "(", "self", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", ",", "*", ",", "accept", ":", "str", "=", "sansio", ".", "accept_format", "(", ")", ",", "jwt", ":", "Opt"...
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
3,782
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...
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...
[ "async", "def", "getiter", "(", "self", ",", "url", ":", "str", ",", "url_vars", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", ",", "*", ",", "accept", ":", "str", "=", "sansio", ".", "accept_format", "(", ")", ",", "jwt", ":", "Opt"...
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
3,783
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_...
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_...
[ "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...
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
3,784
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"...
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
3,785
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 = gethost...
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 = gethost...
[ "def", "gen_filename", "(", "endpoint", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y%m%d_%H%M%S%f'", ")", "[", ":", "-", "4", "]", "base", "=", "endpoint", ".", "split", "(", "'://'", ",", "1", ")", "[", "1", ...
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
3,786
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", ")"...
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
3,787
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: di...
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: di...
[ "def", "hdf5_to_dict", "(", "filepath", ",", "group", "=", "'/'", ")", ":", "if", "not", "h5py", ".", "is_hdf5", "(", "filepath", ")", ":", "raise", "RuntimeError", "(", "filepath", ",", "'is not a valid HDF5 file.'", ")", "with", "h5py", ".", "File", "(",...
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
3,788
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: ...
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: ...
[ "def", "print_one_train", "(", "client", ",", "verbosity", "=", "0", ")", ":", "ts_before", "=", "time", "(", ")", "data", ",", "meta", "=", "client", ".", "next", "(", ")", "ts_after", "=", "time", "(", ")", "if", "not", "data", ":", "print", "(",...
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
3,789
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('-', '+'...
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('-', '+'...
[ "def", "pretty_print", "(", "d", ",", "ind", "=", "''", ",", "verbosity", "=", "0", ")", ":", "assert", "isinstance", "(", "d", ",", "dict", ")", "for", "k", ",", "v", "in", "sorted", "(", "d", ".", "items", "(", ")", ")", ":", "str_base", "=",...
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
3,790
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 ------...
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 ------...
[ "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:...
[ "Karabo", "bridge", "server", "simulation", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/simulation.py#L262-L328
3,791
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...
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...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_pattern", "==", "zmq", ".", "REQ", "and", "not", "self", ".", "_recv_ready", ":", "self", ".", "_socket", ".", "send", "(", "b'next'", ")", "self", ".", "_recv_ready", "=", "True", "try", "...
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 ...
[ "Request", "next", "data", "container", "." ]
ca20d72b8beb0039649d10cb01d027db42efd91c
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/client.py#L90-L122
3,792
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(..). ...
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(..). ...
[ "def", "zopen", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "Path", "is", "not", "None", "and", "isinstance", "(", "filename", ",", "Path", ")", ":", "filename", "=", "str", "(", "filename", ")", "name", ",", "ext", ...
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. ...
[ "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
3,793
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....
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....
[ "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", ":", ...
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...
[ "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
3,794
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....
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....
[ "def", "get_open_fds", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "procs", "=", "subprocess", ".", "check_output", "(", "[", "\"lsof\"", ",", "'-w'", ",", "'-Ff'", ",", "\"-p\"", ",", "str", "(", "pid", ")", "]", ")", "procs", "=", ...
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
3,795
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()...
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()...
[ "def", "acquire", "(", "self", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "try", ":", "self", ".", "fd", "=", "os", ".", "open", "(", "self", ".", "lockfile", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_...
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",...
d99d6f3c68372d83489d28ff515566c93cd569e2
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L229-L250
3,796
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
3,797
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...
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...
[ "def", "filter", "(", "self", ",", "names", ")", ":", "names", "=", "list_strings", "(", "names", ")", "fnames", "=", "[", "]", "for", "f", "in", "names", ":", "for", "pat", "in", "self", ".", "pats", ":", "if", "fnmatch", ".", "fnmatch", "(", "f...
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
3,798
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
3,799
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, ...
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, ...
[ "def", "deprecated", "(", "replacement", "=", "None", ",", "message", "=", "None", ")", ":", "def", "wrap", "(", "old", ")", ":", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "\"%s is deprecated\"", "%", "old", ...
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