repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
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...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L91-L142
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L145-L152
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L155-L159
inspirehep/refextract
refextract/references/text.py
rebuild_reference_lines
def rebuild_reference_lines(ref_sectn, ref_line_marker_ptn): """Given a reference section, rebuild the reference lines. After translation from PDF to text, reference lines are often broken. This is because pdftotext doesn't know what is a wrapped-line and what is a genuine new line. As a result...
python
def rebuild_reference_lines(ref_sectn, ref_line_marker_ptn): """Given a reference section, rebuild the reference lines. After translation from PDF to text, reference lines are often broken. This is because pdftotext doesn't know what is a wrapped-line and what is a genuine new line. As a result...
[ "def", "rebuild_reference_lines", "(", "ref_sectn", ",", "ref_line_marker_ptn", ")", ":", "indentation_splitting", "=", "False", "# This should be moved the function detecting the pattern!", "if", "not", "ref_line_marker_ptn", ":", "if", "test_for_blank_lines_separating_reference_l...
Given a reference section, rebuild the reference lines. After translation from PDF to text, reference lines are often broken. This is because pdftotext doesn't know what is a wrapped-line and what is a genuine new line. As a result, the following 2 reference lines: [1] See http://invenio-so...
[ "Given", "a", "reference", "section", "rebuild", "the", "reference", "lines", ".", "After", "translation", "from", "PDF", "to", "text", "reference", "lines", "are", "often", "broken", ".", "This", "is", "because", "pdftotext", "doesn", "t", "know", "what", "...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L162-L296
inspirehep/refextract
refextract/references/text.py
wash_and_repair_reference_line
def wash_and_repair_reference_line(line): """Wash a reference line of undesirable characters (such as poorly-encoded letters, etc), and repair any errors (such as broken URLs) if possible. @param line: (string) the reference line to be washed/repaired. @return: (string) the washed reference lin...
python
def wash_and_repair_reference_line(line): """Wash a reference line of undesirable characters (such as poorly-encoded letters, etc), and repair any errors (such as broken URLs) if possible. @param line: (string) the reference line to be washed/repaired. @return: (string) the washed reference lin...
[ "def", "wash_and_repair_reference_line", "(", "line", ")", ":", "# repair URLs in line:", "line", "=", "repair_broken_urls", "(", "line", ")", "# Replace various undesirable characters with their alternatives:", "line", "=", "replace_undesirable_characters", "(", "line", ")", ...
Wash a reference line of undesirable characters (such as poorly-encoded letters, etc), and repair any errors (such as broken URLs) if possible. @param line: (string) the reference line to be washed/repaired. @return: (string) the washed reference line.
[ "Wash", "a", "reference", "line", "of", "undesirable", "characters", "(", "such", "as", "poorly", "-", "encoded", "letters", "etc", ")", "and", "repair", "any", "errors", "(", "such", "as", "broken", "URLs", ")", "if", "possible", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/text.py#L299-L316
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L54-L99
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L102-L151
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L154-L201
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/api.py#L204-L216
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L31-L47
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L71-L161
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/pdf.py#L43-L84
inspirehep/refextract
refextract/references/pdf.py
_destinations_in_two_columns
def _destinations_in_two_columns(pdf, destinations, cutoff=3): """ Check if the named destinations are organized along two columns (heuristic) @param pdf: a PdfFileReader object @param destinations: 'cutoff' is used to tune the heuristic: if 'cutoff' destinations in the would-be second column ...
python
def _destinations_in_two_columns(pdf, destinations, cutoff=3): """ Check if the named destinations are organized along two columns (heuristic) @param pdf: a PdfFileReader object @param destinations: 'cutoff' is used to tune the heuristic: if 'cutoff' destinations in the would-be second column ...
[ "def", "_destinations_in_two_columns", "(", "pdf", ",", "destinations", ",", "cutoff", "=", "3", ")", ":", "# iterator for the x coordinates of refs in the would-be second column", "xpositions", "=", "(", "_destination_position", "(", "pdf", ",", "dest", ")", "[", "3", ...
Check if the named destinations are organized along two columns (heuristic) @param pdf: a PdfFileReader object @param destinations: 'cutoff' is used to tune the heuristic: if 'cutoff' destinations in the would-be second column start at the same position, return True
[ "Check", "if", "the", "named", "destinations", "are", "organized", "along", "two", "columns", "(", "heuristic", ")" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/pdf.py#L87-L106
inspirehep/refextract
refextract/references/pdf.py
_destination_position
def _destination_position(pdf, destination): """ Gives a tuple (page, column, -y, x) representing the position of the NamedDestination This representation is useful for sorting named destinations and assumes the text has at most 2 columns """ pagewidth = pdf.getPage( pdf.getDestinat...
python
def _destination_position(pdf, destination): """ Gives a tuple (page, column, -y, x) representing the position of the NamedDestination This representation is useful for sorting named destinations and assumes the text has at most 2 columns """ pagewidth = pdf.getPage( pdf.getDestinat...
[ "def", "_destination_position", "(", "pdf", ",", "destination", ")", ":", "pagewidth", "=", "pdf", ".", "getPage", "(", "pdf", ".", "getDestinationPageNumber", "(", "destination", ")", ")", ".", "cropBox", ".", "lowerRight", "[", "0", "]", "if", "not", "de...
Gives a tuple (page, column, -y, x) representing the position of the NamedDestination This representation is useful for sorting named destinations and assumes the text has at most 2 columns
[ "Gives", "a", "tuple", "(", "page", "column", "-", "y", "x", ")", "representing", "the", "position", "of", "the", "NamedDestination" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/pdf.py#L109-L125
inspirehep/refextract
refextract/references/regexs.py
_create_regex_pattern_add_optional_spaces_to_word_characters
def _create_regex_pattern_add_optional_spaces_to_word_characters(word): """Add the regex special characters (\s*) to allow optional spaces between the characters in a word. @param word: (string) the word to be inserted into a regex pattern. @return: string: the regex pattern for that word with ...
python
def _create_regex_pattern_add_optional_spaces_to_word_characters(word): """Add the regex special characters (\s*) to allow optional spaces between the characters in a word. @param word: (string) the word to be inserted into a regex pattern. @return: string: the regex pattern for that word with ...
[ "def", "_create_regex_pattern_add_optional_spaces_to_word_characters", "(", "word", ")", ":", "new_word", "=", "u\"\"", "for", "ch", "in", "word", ":", "if", "ch", ".", "isspace", "(", ")", ":", "new_word", "+=", "ch", "else", ":", "new_word", "+=", "ch", "+...
Add the regex special characters (\s*) to allow optional spaces between the characters in a word. @param word: (string) the word to be inserted into a regex pattern. @return: string: the regex pattern for that word with optional spaces between all of its characters.
[ "Add", "the", "regex", "special", "characters", "(", "\\", "s", "*", ")", "to", "allow", "optional", "spaces", "between", "the", "characters", "in", "a", "word", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L674-L687
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L733-L772
inspirehep/refextract
refextract/references/regexs.py
get_reference_line_marker_pattern
def get_reference_line_marker_pattern(pattern): """Return a list of compiled regex patterns used to search for the first reference line in a full-text document. The line is considered to start with either: [1] or {1} The line is considered to start with : 1. or 2. or 3. etc The line is c...
python
def get_reference_line_marker_pattern(pattern): """Return a list of compiled regex patterns used to search for the first reference line in a full-text document. The line is considered to start with either: [1] or {1} The line is considered to start with : 1. or 2. or 3. etc The line is c...
[ "def", "get_reference_line_marker_pattern", "(", "pattern", ")", ":", "return", "re", ".", "compile", "(", "u'(?P<mark>'", "+", "pattern", "+", "u')'", ",", "re", ".", "I", "|", "re", ".", "UNICODE", ")" ]
Return a list of compiled regex patterns used to search for the first reference line in a full-text document. The line is considered to start with either: [1] or {1} The line is considered to start with : 1. or 2. or 3. etc The line is considered to start with : 1 or 2 etc (just a number) ...
[ "Return", "a", "list", "of", "compiled", "regex", "patterns", "used", "to", "search", "for", "the", "first", "reference", "line", "in", "a", "full", "-", "text", "document", ".", "The", "line", "is", "considered", "to", "start", "with", "either", ":", "[...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L775-L783
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L800-L871
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", "...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L874-L894
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...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/regexs.py#L897-L913
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", "...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L45-L95
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L102-L120
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L123-L136
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",...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L139-L164
inspirehep/refextract
refextract/documents/text.py
wash_line
def wash_line(line): """Wash a text line of certain punctuation errors, replacing them with more correct alternatives. E.g.: the string 'Yes , I like python.' will be transformed into 'Yes, I like python.' @param line: (string) the line to be washed. @return: (string) the washed line. ...
python
def wash_line(line): """Wash a text line of certain punctuation errors, replacing them with more correct alternatives. E.g.: the string 'Yes , I like python.' will be transformed into 'Yes, I like python.' @param line: (string) the line to be washed. @return: (string) the washed line. ...
[ "def", "wash_line", "(", "line", ")", ":", "line", "=", "re_space_comma", ".", "sub", "(", "','", ",", "line", ")", "line", "=", "re_space_semicolon", ".", "sub", "(", "';'", ",", "line", ")", "line", "=", "re_space_period", ".", "sub", "(", "'.'", "...
Wash a text line of certain punctuation errors, replacing them with more correct alternatives. E.g.: the string 'Yes , I like python.' will be transformed into 'Yes, I like python.' @param line: (string) the line to be washed. @return: (string) the washed line.
[ "Wash", "a", "text", "line", "of", "certain", "punctuation", "errors", "replacing", "them", "with", "more", "correct", "alternatives", ".", "E", ".", "g", ".", ":", "the", "string", "Yes", "I", "like", "python", ".", "will", "be", "transformed", "into", ...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L167-L183
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L186-L217
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L237-L251
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", "...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L254-L320
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", "...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L323-L377
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L380-L424
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", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/documents/text.py#L427-L452
inspirehep/refextract
refextract/references/kbs.py
get_kbs
def get_kbs(custom_kbs_files=None, cache={}): # noqa """Load kbs (with caching). This function stores the loaded kbs into the cache variable For the caching to work, it needs to receive an empty dictionary as "cache" paramater. """ cache_key = make_cache_key(custom_kbs_files) if cache_key...
python
def get_kbs(custom_kbs_files=None, cache={}): # noqa """Load kbs (with caching). This function stores the loaded kbs into the cache variable For the caching to work, it needs to receive an empty dictionary as "cache" paramater. """ cache_key = make_cache_key(custom_kbs_files) if cache_key...
[ "def", "get_kbs", "(", "custom_kbs_files", "=", "None", ",", "cache", "=", "{", "}", ")", ":", "# noqa", "cache_key", "=", "make_cache_key", "(", "custom_kbs_files", ")", "if", "cache_key", "not", "in", "cache", ":", "# Build paths from defaults and specified ones...
Load kbs (with caching). This function stores the loaded kbs into the cache variable For the caching to work, it needs to receive an empty dictionary as "cache" paramater.
[ "Load", "kbs", "(", "with", "caching", ")", "." ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L61-L79
inspirehep/refextract
refextract/references/kbs.py
load_kbs
def load_kbs(kbs_files): """Load kbs (without caching) Args: - kb_files: list of custom paths you can specify to override the default values If path starts with "kb:", the kb will be loaded from the database """ return { 'journals_re': build_journals_re_kb(kbs_files['j...
python
def load_kbs(kbs_files): """Load kbs (without caching) Args: - kb_files: list of custom paths you can specify to override the default values If path starts with "kb:", the kb will be loaded from the database """ return { 'journals_re': build_journals_re_kb(kbs_files['j...
[ "def", "load_kbs", "(", "kbs_files", ")", ":", "return", "{", "'journals_re'", ":", "build_journals_re_kb", "(", "kbs_files", "[", "'journals-re'", "]", ")", ",", "'journals'", ":", "load_kb", "(", "kbs_files", "[", "'journals'", "]", ",", "build_journals_kb", ...
Load kbs (without caching) Args: - kb_files: list of custom paths you can specify to override the default values If path starts with "kb:", the kb will be loaded from the database
[ "Load", "kbs", "(", "without", "caching", ")" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L82-L100
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L112-L130
inspirehep/refextract
refextract/references/kbs.py
order_reportnum_patterns_bylen
def order_reportnum_patterns_bylen(numeration_patterns): """Given a list of user-defined patterns for recognising the numeration styles of an institute's preprint references, for each pattern, strip out character classes and record the length of the pattern. Then add the length and the original...
python
def order_reportnum_patterns_bylen(numeration_patterns): """Given a list of user-defined patterns for recognising the numeration styles of an institute's preprint references, for each pattern, strip out character classes and record the length of the pattern. Then add the length and the original...
[ "def", "order_reportnum_patterns_bylen", "(", "numeration_patterns", ")", ":", "def", "_compfunc_bylen", "(", "a", ",", "b", ")", ":", "\"\"\"Compares regexp patterns by the length of the pattern-text.\n \"\"\"", "if", "a", "[", "0", "]", "<", "b", "[", "0", "]...
Given a list of user-defined patterns for recognising the numeration styles of an institute's preprint references, for each pattern, strip out character classes and record the length of the pattern. Then add the length and the original pattern (in a tuple) into a new list for these patterns ...
[ "Given", "a", "list", "of", "user", "-", "defined", "patterns", "for", "recognising", "the", "numeration", "styles", "of", "an", "institute", "s", "preprint", "references", "for", "each", "pattern", "strip", "out", "character", "classes", "and", "record", "the...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L133-L158
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...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L161-L174
inspirehep/refextract
refextract/references/kbs.py
institute_num_pattern_to_regex
def institute_num_pattern_to_regex(pattern): """Given a numeration pattern from the institutes preprint report numbers KB, convert it to turn it into a regexp string for recognising such patterns in a reference line. Change: \ -> \\ 9 -> \d a -> [A-Z...
python
def institute_num_pattern_to_regex(pattern): """Given a numeration pattern from the institutes preprint report numbers KB, convert it to turn it into a regexp string for recognising such patterns in a reference line. Change: \ -> \\ 9 -> \d a -> [A-Z...
[ "def", "institute_num_pattern_to_regex", "(", "pattern", ")", ":", "simple_replacements", "=", "[", "(", "'9'", ",", "r'\\d'", ")", ",", "(", "'w+'", ",", "r'\\w+'", ")", ",", "(", "'a'", ",", "r'[A-Za-z]'", ")", ",", "(", "'v'", ",", "r'[Vv]'", ")", "...
Given a numeration pattern from the institutes preprint report numbers KB, convert it to turn it into a regexp string for recognising such patterns in a reference line. Change: \ -> \\ 9 -> \d a -> [A-Za-z] v -> [Vv] # Tony for arXiv vN ...
[ "Given", "a", "numeration", "pattern", "from", "the", "institutes", "preprint", "report", "numbers", "KB", "convert", "it", "to", "turn", "it", "into", "a", "regexp", "string", "for", "recognising", "such", "patterns", "in", "a", "reference", "line", ".", "C...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L177-L219
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...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L222-L415
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", ...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L418-L432
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L435-L453
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" ]
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L492-L512
inspirehep/refextract
refextract/references/kbs.py
build_journals_kb
def build_journals_kb(knowledgebase): """Given the path to a knowledge base file, read in the contents of that file into a dictionary of search->replace word phrases. The search phrases are compiled into a regex pattern object. The knowledge base file should consist only of lines that take ...
python
def build_journals_kb(knowledgebase): """Given the path to a knowledge base file, read in the contents of that file into a dictionary of search->replace word phrases. The search phrases are compiled into a regex pattern object. The knowledge base file should consist only of lines that take ...
[ "def", "build_journals_kb", "(", "knowledgebase", ")", ":", "# Initialise vars:", "# dictionary of search and replace phrases from KB:", "kb", "=", "{", "}", "standardised_titles", "=", "{", "}", "seek_phrases", "=", "[", "]", "# A dictionary of \"replacement terms\" (RHS) to...
Given the path to a knowledge base file, read in the contents of that file into a dictionary of search->replace word phrases. The search phrases are compiled into a regex pattern object. The knowledge base file should consist only of lines that take the following format: seek-term ...
[ "Given", "the", "path", "to", "a", "knowledge", "base", "file", "read", "in", "the", "contents", "of", "that", "file", "into", "a", "dictionary", "of", "search", "-", ">", "replace", "word", "phrases", ".", "The", "search", "phrases", "are", "compiled", ...
train
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/kbs.py#L540-L618
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L24-L36
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L39-L57
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L60-L71
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L125-L145
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L148-L186
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L269-L326
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L331-L342
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L90-L122
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/sansio.py#L237-L250
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L29-L50
brettcannon/gidgethub
gidgethub/routing.py
Router.register
def register(self, event_type: str, **data_detail: Any) -> Callable[[AsyncCallback], AsyncCallback]: """Decorator to apply the add() method to a function.""" def decorator(func: AsyncCallback) -> AsyncCallback: self.add(func, event_type, **data_detail) return fun...
python
def register(self, event_type: str, **data_detail: Any) -> Callable[[AsyncCallback], AsyncCallback]: """Decorator to apply the add() method to a function.""" def decorator(func: AsyncCallback) -> AsyncCallback: self.add(func, event_type, **data_detail) return fun...
[ "def", "register", "(", "self", ",", "event_type", ":", "str", ",", "*", "*", "data_detail", ":", "Any", ")", "->", "Callable", "[", "[", "AsyncCallback", "]", ",", "AsyncCallback", "]", ":", "def", "decorator", "(", "func", ":", "AsyncCallback", ")", ...
Decorator to apply the add() method to a function.
[ "Decorator", "to", "apply", "the", "add", "()", "method", "to", "a", "function", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L52-L58
brettcannon/gidgethub
gidgethub/routing.py
Router.dispatch
async def dispatch(self, event: sansio.Event, *args: Any, **kwargs: Any) -> None: """Dispatch an event to all registered function(s).""" found_callbacks = [] try: found_callbacks.extend(self._shallow_routes[event.event]) except KeyError: pa...
python
async def dispatch(self, event: sansio.Event, *args: Any, **kwargs: Any) -> None: """Dispatch an event to all registered function(s).""" found_callbacks = [] try: found_callbacks.extend(self._shallow_routes[event.event]) except KeyError: pa...
[ "async", "def", "dispatch", "(", "self", ",", "event", ":", "sansio", ".", "Event", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "found_callbacks", "=", "[", "]", "try", ":", "found_callbacks", ".", "ex...
Dispatch an event to all registered function(s).
[ "Dispatch", "an", "event", "to", "all", "registered", "function", "(", "s", ")", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/routing.py#L60-L80
brettcannon/gidgethub
gidgethub/abc.py
GitHubAPI._request
async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: """Make an HTTP request."""
python
async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: """Make an HTTP request."""
[ "async", "def", "_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", "=", "b''", ")", "->", "Tuple", "[", "int", ",", "Mapping", "[", ...
Make an HTTP request.
[ "Make", "an", "HTTP", "request", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L26-L28
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L34-L89
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L91-L100
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", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/abc.py#L102-L120
brettcannon/gidgethub
gidgethub/tornado.py
GitHubAPI._request
async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: """Make an HTTP request.""" if method == "GET" and not body: real_body = None else: real_body = body requ...
python
async def _request(self, method: str, url: str, headers: Mapping[str, str], body: bytes = b'') -> Tuple[int, Mapping[str, str], bytes]: """Make an HTTP request.""" if method == "GET" and not body: real_body = None else: real_body = body requ...
[ "async", "def", "_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "headers", ":", "Mapping", "[", "str", ",", "str", "]", ",", "body", ":", "bytes", "=", "b''", ")", "->", "Tuple", "[", "int", ",", "Mapping", "[", ...
Make an HTTP request.
[ "Make", "an", "HTTP", "request", "." ]
train
https://github.com/brettcannon/gidgethub/blob/24feb6c35bba3966c6cc9ec2896729578f6d7ccc/gidgethub/tornado.py#L11-L23
rkargon/pixelsorter
pixelsorter/keys.py
hue
def hue(p): """ Returns the saturation of a pixel. Gray pixels have saturation 0. :param p: A tuple of (R,G,B) values :return: A saturation value between 0 and 360 """ min_c = min(p) max_c = max(p) d = float(max_c - min_c) if d == 0: return 0 if max_c == p[0]: ...
python
def hue(p): """ Returns the saturation of a pixel. Gray pixels have saturation 0. :param p: A tuple of (R,G,B) values :return: A saturation value between 0 and 360 """ min_c = min(p) max_c = max(p) d = float(max_c - min_c) if d == 0: return 0 if max_c == p[0]: ...
[ "def", "hue", "(", "p", ")", ":", "min_c", "=", "min", "(", "p", ")", "max_c", "=", "max", "(", "p", ")", "d", "=", "float", "(", "max_c", "-", "min_c", ")", "if", "d", "==", "0", ":", "return", "0", "if", "max_c", "==", "p", "[", "0", "]...
Returns the saturation of a pixel. Gray pixels have saturation 0. :param p: A tuple of (R,G,B) values :return: A saturation value between 0 and 360
[ "Returns", "the", "saturation", "of", "a", "pixel", ".", "Gray", "pixels", "have", "saturation", "0", ".", ":", "param", "p", ":", "A", "tuple", "of", "(", "R", "G", "B", ")", "values", ":", "return", ":", "A", "saturation", "value", "between", "0", ...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/keys.py#L58-L80
rkargon/pixelsorter
pixelsorter/keys.py
saturation
def saturation(p): """ Returns the saturation of a pixel, defined as the ratio of chroma to value. :param p: A tuple of (R,G,B) values :return: The saturation of a pixel, from 0 to 1 """ max_c = max(p) min_c = min(p) if max_c == 0: return 0 return (max_c - min_c) / float(max_...
python
def saturation(p): """ Returns the saturation of a pixel, defined as the ratio of chroma to value. :param p: A tuple of (R,G,B) values :return: The saturation of a pixel, from 0 to 1 """ max_c = max(p) min_c = min(p) if max_c == 0: return 0 return (max_c - min_c) / float(max_...
[ "def", "saturation", "(", "p", ")", ":", "max_c", "=", "max", "(", "p", ")", "min_c", "=", "min", "(", "p", ")", "if", "max_c", "==", "0", ":", "return", "0", "return", "(", "max_c", "-", "min_c", ")", "/", "float", "(", "max_c", ")" ]
Returns the saturation of a pixel, defined as the ratio of chroma to value. :param p: A tuple of (R,G,B) values :return: The saturation of a pixel, from 0 to 1
[ "Returns", "the", "saturation", "of", "a", "pixel", "defined", "as", "the", "ratio", "of", "chroma", "to", "value", ".", ":", "param", "p", ":", "A", "tuple", "of", "(", "R", "G", "B", ")", "values", ":", "return", ":", "The", "saturation", "of", "...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/keys.py#L83-L93
rkargon/pixelsorter
pixelsorter/util.py
weighted_random_choice
def weighted_random_choice(items): """ Returns a weighted random choice from a list of items. :param items: A list of tuples (object, weight) :return: A random object, whose likelihood is proportional to its weight. """ l = list(items) r = random.random() * sum([i[1] for i in l]) for x, ...
python
def weighted_random_choice(items): """ Returns a weighted random choice from a list of items. :param items: A list of tuples (object, weight) :return: A random object, whose likelihood is proportional to its weight. """ l = list(items) r = random.random() * sum([i[1] for i in l]) for x, ...
[ "def", "weighted_random_choice", "(", "items", ")", ":", "l", "=", "list", "(", "items", ")", "r", "=", "random", ".", "random", "(", ")", "*", "sum", "(", "[", "i", "[", "1", "]", "for", "i", "in", "l", "]", ")", "for", "x", ",", "p", "in", ...
Returns a weighted random choice from a list of items. :param items: A list of tuples (object, weight) :return: A random object, whose likelihood is proportional to its weight.
[ "Returns", "a", "weighted", "random", "choice", "from", "a", "list", "of", "items", ".", ":", "param", "items", ":", "A", "list", "of", "tuples", "(", "object", "weight", ")", ":", "return", ":", "A", "random", "object", "whose", "likelihood", "is", "p...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/util.py#L72-L84
rkargon/pixelsorter
pixelsorter/sort.py
sort_image
def sort_image(image, size, vertical=False, path=None, path_kwargs=None, max_interval=0, progressive_amount=0, randomize=False, edge_threshold=0, edge_data=None, image_threshold=None, image_mask=None, key=None, discretize=0, reverse=False, mirror=False, splice...
python
def sort_image(image, size, vertical=False, path=None, path_kwargs=None, max_interval=0, progressive_amount=0, randomize=False, edge_threshold=0, edge_data=None, image_threshold=None, image_mask=None, key=None, discretize=0, reverse=False, mirror=False, splice...
[ "def", "sort_image", "(", "image", ",", "size", ",", "vertical", "=", "False", ",", "path", "=", "None", ",", "path_kwargs", "=", "None", ",", "max_interval", "=", "0", ",", "progressive_amount", "=", "0", ",", "randomize", "=", "False", ",", "edge_thres...
Applies pixel sorting to an image. This is done by first creating a sort mask that describes the sorting intervals, and then calling apply_sort_mask to the image using the generated mask. :param discretize: Amount by which to "discretize" pixel values. This is done by dividing each pixel's value (after appl...
[ "Applies", "pixel", "sorting", "to", "an", "image", ".", "This", "is", "done", "by", "first", "creating", "a", "sort", "mask", "that", "describes", "the", "sorting", "intervals", "and", "then", "calling", "apply_sort_mask", "to", "the", "image", "using", "th...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L109-L240
rkargon/pixelsorter
pixelsorter/sort.py
sort_filter
def sort_filter(l, mirror=False, splice=0, splice_random=False): """ Rearranges an interval of pixels. :param l: The interval, as a list of pixels :param mirror: Whether to put each element in the list alternatively at the start or end of the list, effectively mirroring a sorted list. This is pa...
python
def sort_filter(l, mirror=False, splice=0, splice_random=False): """ Rearranges an interval of pixels. :param l: The interval, as a list of pixels :param mirror: Whether to put each element in the list alternatively at the start or end of the list, effectively mirroring a sorted list. This is pa...
[ "def", "sort_filter", "(", "l", ",", "mirror", "=", "False", ",", "splice", "=", "0", ",", "splice_random", "=", "False", ")", ":", "if", "len", "(", "l", ")", "==", "0", ":", "return", "l", "nl", "=", "list", "(", "l", ")", "if", "mirror", ":"...
Rearranges an interval of pixels. :param l: The interval, as a list of pixels :param mirror: Whether to put each element in the list alternatively at the start or end of the list, effectively mirroring a sorted list. This is particularly useful with pixel paths that are looped, so that the beginning and...
[ "Rearranges", "an", "interval", "of", "pixels", ".", ":", "param", "l", ":", "The", "interval", "as", "a", "list", "of", "pixels", ":", "param", "mirror", ":", "Whether", "to", "put", "each", "element", "in", "the", "list", "alternatively", "at", "the", ...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L243-L280
rkargon/pixelsorter
pixelsorter/sort.py
get_tile_from_image
def get_tile_from_image(image, size, top_left_corner, tile_size): """ Returns a rectangular region of the given image as a separate image If the tile goes off the edge of the image, it will be truncated. The new size is also returned. :param image: The given image, as a list of (R,G,B) tuples :param...
python
def get_tile_from_image(image, size, top_left_corner, tile_size): """ Returns a rectangular region of the given image as a separate image If the tile goes off the edge of the image, it will be truncated. The new size is also returned. :param image: The given image, as a list of (R,G,B) tuples :param...
[ "def", "get_tile_from_image", "(", "image", ",", "size", ",", "top_left_corner", ",", "tile_size", ")", ":", "tile_pixels", "=", "[", "]", "# crop tile if necessary", "tile_x", "=", "min", "(", "size", "[", "0", "]", "-", "top_left_corner", "[", "0", "]", ...
Returns a rectangular region of the given image as a separate image If the tile goes off the edge of the image, it will be truncated. The new size is also returned. :param image: The given image, as a list of (R,G,B) tuples :param size: The size of the image, as (width, height) :param top_left_corner: T...
[ "Returns", "a", "rectangular", "region", "of", "the", "given", "image", "as", "a", "separate", "image", "If", "the", "tile", "goes", "off", "the", "edge", "of", "the", "image", "it", "will", "be", "truncated", ".", "The", "new", "size", "is", "also", "...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L283-L302
rkargon/pixelsorter
pixelsorter/sort.py
apply_tile_to_image
def apply_tile_to_image(image, size, tile, tile_size, tile_corner): """ Copies a tile with a given offset onto an image :param image: The image the file is to be copied onto (as a list of (R,G,B) tuples) :param size: The size of the image as a tuple (width, height) :param tile: The tile to be copied...
python
def apply_tile_to_image(image, size, tile, tile_size, tile_corner): """ Copies a tile with a given offset onto an image :param image: The image the file is to be copied onto (as a list of (R,G,B) tuples) :param size: The size of the image as a tuple (width, height) :param tile: The tile to be copied...
[ "def", "apply_tile_to_image", "(", "image", ",", "size", ",", "tile", ",", "tile_size", ",", "tile_corner", ")", ":", "for", "y", "in", "range", "(", "tile_size", "[", "1", "]", ")", ":", "for", "x", "in", "range", "(", "tile_size", "[", "0", "]", ...
Copies a tile with a given offset onto an image :param image: The image the file is to be copied onto (as a list of (R,G,B) tuples) :param size: The size of the image as a tuple (width, height) :param tile: The tile to be copied over (as a list of (R,G,B) tuples) :param tile_size: The size of the tile a...
[ "Copies", "a", "tile", "with", "a", "given", "offset", "onto", "an", "image", ":", "param", "image", ":", "The", "image", "the", "file", "is", "to", "be", "copied", "onto", "(", "as", "a", "list", "of", "(", "R", "G", "B", ")", "tuples", ")", ":"...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L305-L317
rkargon/pixelsorter
pixelsorter/sort.py
sort_image_tiles
def sort_image_tiles(image, size, sorting_args, tile_size, tile_density=1.0, randomize_tiles=False): """ Sorts an image by taking various tiles and sorting them individually. :param image: The image to be modified :param size: The size of the image, as (width, height) :param sorting_args: Arguments ...
python
def sort_image_tiles(image, size, sorting_args, tile_size, tile_density=1.0, randomize_tiles=False): """ Sorts an image by taking various tiles and sorting them individually. :param image: The image to be modified :param size: The size of the image, as (width, height) :param sorting_args: Arguments ...
[ "def", "sort_image_tiles", "(", "image", ",", "size", ",", "sorting_args", ",", "tile_size", ",", "tile_density", "=", "1.0", ",", "randomize_tiles", "=", "False", ")", ":", "out_image", "=", "list", "(", "image", ")", "width", ",", "height", "=", "size", ...
Sorts an image by taking various tiles and sorting them individually. :param image: The image to be modified :param size: The size of the image, as (width, height) :param sorting_args: Arguments that would be passed to sort_pixels for each tile :param tile_size: The size of each tile as (width, height) ...
[ "Sorts", "an", "image", "by", "taking", "various", "tiles", "and", "sorting", "them", "individually", ".", ":", "param", "image", ":", "The", "image", "to", "be", "modified", ":", "param", "size", ":", "The", "size", "of", "the", "image", "as", "(", "w...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L320-L364
rkargon/pixelsorter
pixelsorter/paths.py
horizontal_path
def horizontal_path(size): """ Creates a generator for progressing horizontally through an image. :param size: A tuple (width, height) of the image size :return: A generator that yields a set of rows through the image. Each row is a generator that yields pixel coordinates. """ width, height ...
python
def horizontal_path(size): """ Creates a generator for progressing horizontally through an image. :param size: A tuple (width, height) of the image size :return: A generator that yields a set of rows through the image. Each row is a generator that yields pixel coordinates. """ width, height ...
[ "def", "horizontal_path", "(", "size", ")", ":", "width", ",", "height", "=", "size", "return", "(", "(", "(", "x", ",", "y", ")", "for", "x", "in", "range", "(", "width", ")", ")", "for", "y", "in", "range", "(", "height", ")", ")" ]
Creates a generator for progressing horizontally through an image. :param size: A tuple (width, height) of the image size :return: A generator that yields a set of rows through the image. Each row is a generator that yields pixel coordinates.
[ "Creates", "a", "generator", "for", "progressing", "horizontally", "through", "an", "image", ".", ":", "param", "size", ":", "A", "tuple", "(", "width", "height", ")", "of", "the", "image", "size", ":", "return", ":", "A", "generator", "that", "yields", ...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L28-L36
rkargon/pixelsorter
pixelsorter/paths.py
vertical_path
def vertical_path(size): """ Creates a generator for progressing vertically through an image. :param size: A tuple (width, height) of the image size :return: A generator that yields a set of columns through the image. Each column is a generator that yields pixel coordinates. """ width, heigh...
python
def vertical_path(size): """ Creates a generator for progressing vertically through an image. :param size: A tuple (width, height) of the image size :return: A generator that yields a set of columns through the image. Each column is a generator that yields pixel coordinates. """ width, heigh...
[ "def", "vertical_path", "(", "size", ")", ":", "width", ",", "height", "=", "size", "return", "(", "(", "(", "x", ",", "y", ")", "for", "y", "in", "range", "(", "height", ")", ")", "for", "x", "in", "range", "(", "width", ")", ")" ]
Creates a generator for progressing vertically through an image. :param size: A tuple (width, height) of the image size :return: A generator that yields a set of columns through the image. Each column is a generator that yields pixel coordinates.
[ "Creates", "a", "generator", "for", "progressing", "vertically", "through", "an", "image", ".", ":", "param", "size", ":", "A", "tuple", "(", "width", "height", ")", "of", "the", "image", "size", ":", "return", ":", "A", "generator", "that", "yields", "a...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L39-L47
rkargon/pixelsorter
pixelsorter/paths.py
draw_line
def draw_line(start, size, slope): """ Draws a line from the starting point with the given slope, until the line goes out of the given bounds. :param start: The starting point (x, y) for the line :param size: The size of the image as (width, height). This determined the bounds for the image. :param ...
python
def draw_line(start, size, slope): """ Draws a line from the starting point with the given slope, until the line goes out of the given bounds. :param start: The starting point (x, y) for the line :param size: The size of the image as (width, height). This determined the bounds for the image. :param ...
[ "def", "draw_line", "(", "start", ",", "size", ",", "slope", ")", ":", "error", "=", "-", "1.0", "if", "abs", "(", "slope", ")", ">", "1", ":", "slope", "=", "1", "/", "slope", "switch_xy", "=", "True", "else", ":", "switch_xy", "=", "False", "sl...
Draws a line from the starting point with the given slope, until the line goes out of the given bounds. :param start: The starting point (x, y) for the line :param size: The size of the image as (width, height). This determined the bounds for the image. :param slope: The slope of the line :return: Yield...
[ "Draws", "a", "line", "from", "the", "starting", "point", "with", "the", "given", "slope", "until", "the", "line", "goes", "out", "of", "the", "given", "bounds", ".", ":", "param", "start", ":", "The", "starting", "point", "(", "x", "y", ")", "for", ...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L50-L77
rkargon/pixelsorter
pixelsorter/paths.py
angled_path
def angled_path(size, angle=0): """ Generates a set of lines across an image, with the given angle. :param size: The size of the image :param angle: The angle of the lines. :return: A set of generators, each generator represents a line and yields a set of (x,y) coordinates. All the lines go left...
python
def angled_path(size, angle=0): """ Generates a set of lines across an image, with the given angle. :param size: The size of the image :param angle: The angle of the lines. :return: A set of generators, each generator represents a line and yields a set of (x,y) coordinates. All the lines go left...
[ "def", "angled_path", "(", "size", ",", "angle", "=", "0", ")", ":", "# y coordinates are inverted in images, so this allows for users to input more intuitive angle values.", "angle", "=", "-", "angle", "if", "angle", "%", "180", "==", "0", ":", "yield", "from", "hori...
Generates a set of lines across an image, with the given angle. :param size: The size of the image :param angle: The angle of the lines. :return: A set of generators, each generator represents a line and yields a set of (x,y) coordinates. All the lines go left to right.
[ "Generates", "a", "set", "of", "lines", "across", "an", "image", "with", "the", "given", "angle", ".", ":", "param", "size", ":", "The", "size", "of", "the", "image", ":", "param", "angle", ":", "The", "angle", "of", "the", "lines", ".", ":", "return...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L80-L102
rkargon/pixelsorter
pixelsorter/paths.py
diagonal_path
def diagonal_path(size): """ Creates a set of diagonal paths moving from the top left to the bottom right of the image. Successive rows start at the bottom-left corner and move up until the top-right corner. :param size: The dimensions of the image (width, height) :return: A generator that yields a ...
python
def diagonal_path(size): """ Creates a set of diagonal paths moving from the top left to the bottom right of the image. Successive rows start at the bottom-left corner and move up until the top-right corner. :param size: The dimensions of the image (width, height) :return: A generator that yields a ...
[ "def", "diagonal_path", "(", "size", ")", ":", "width", ",", "height", "=", "size", "return", "(", "(", "(", "x", ",", "x", "+", "offset", ")", "for", "x", "in", "range", "(", "max", "(", "0", ",", "-", "offset", ")", ",", "min", "(", "width", ...
Creates a set of diagonal paths moving from the top left to the bottom right of the image. Successive rows start at the bottom-left corner and move up until the top-right corner. :param size: The dimensions of the image (width, height) :return: A generator that yields a set of paths, each path is a set of (...
[ "Creates", "a", "set", "of", "diagonal", "paths", "moving", "from", "the", "top", "left", "to", "the", "bottom", "right", "of", "the", "image", ".", "Successive", "rows", "start", "at", "the", "bottom", "-", "left", "corner", "and", "move", "up", "until"...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L105-L114
rkargon/pixelsorter
pixelsorter/paths.py
diagonal_single_path
def diagonal_single_path(size): """ Creates a set of diagonal paths moving from the top left to the bottom right of the image. Successive rows start at the bottom-left corner and move up until the top-right corner. :param size: The dimensions of the image (width, height) :return: A generator that yi...
python
def diagonal_single_path(size): """ Creates a set of diagonal paths moving from the top left to the bottom right of the image. Successive rows start at the bottom-left corner and move up until the top-right corner. :param size: The dimensions of the image (width, height) :return: A generator that yi...
[ "def", "diagonal_single_path", "(", "size", ")", ":", "width", ",", "height", "=", "size", "def", "diagonal_path_iter", "(", ")", ":", "for", "offset", "in", "range", "(", "height", "-", "1", ",", "-", "width", ",", "-", "1", ")", ":", "for", "x", ...
Creates a set of diagonal paths moving from the top left to the bottom right of the image. Successive rows start at the bottom-left corner and move up until the top-right corner. :param size: The dimensions of the image (width, height) :return: A generator that yields a set of paths, each path is a set of (...
[ "Creates", "a", "set", "of", "diagonal", "paths", "moving", "from", "the", "top", "left", "to", "the", "bottom", "right", "of", "the", "image", ".", "Successive", "rows", "start", "at", "the", "bottom", "-", "left", "corner", "and", "move", "up", "until"...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L117-L131
rkargon/pixelsorter
pixelsorter/paths.py
concentric_rectangle_path
def concentric_rectangle_path(size): """ Creates a generator for progressing through an image :param size: A tuple (width, height) of the image size :return: A generator that yields a set of rows through the image. Each row is a generator that yields pixel coordinates. """ def conc_rect_ite...
python
def concentric_rectangle_path(size): """ Creates a generator for progressing through an image :param size: A tuple (width, height) of the image size :return: A generator that yields a set of rows through the image. Each row is a generator that yields pixel coordinates. """ def conc_rect_ite...
[ "def", "concentric_rectangle_path", "(", "size", ")", ":", "def", "conc_rect_iter", "(", ")", ":", "for", "x", "in", "range", "(", "min_x", ",", "max_x", ")", ":", "yield", "(", "x", ",", "min_y", ")", "# if rectangle only has height of 1, prevent path from doub...
Creates a generator for progressing through an image :param size: A tuple (width, height) of the image size :return: A generator that yields a set of rows through the image. Each row is a generator that yields pixel coordinates.
[ "Creates", "a", "generator", "for", "progressing", "through", "an", "image", ":", "param", "size", ":", "A", "tuple", "(", "width", "height", ")", "of", "the", "image", "size", ":", "return", ":", "A", "generator", "that", "yields", "a", "set", "of", "...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L134-L165
rkargon/pixelsorter
pixelsorter/paths.py
random_walk_path
def random_walk_path(size, distribution=None, start_points=None): """ Performs random walks as a markov chain with an arbitrary distribution and start points :param size: The size of the image as (width, height) :param distribution: A hash of {(dx, dy): probability} the distribution that describes h...
python
def random_walk_path(size, distribution=None, start_points=None): """ Performs random walks as a markov chain with an arbitrary distribution and start points :param size: The size of the image as (width, height) :param distribution: A hash of {(dx, dy): probability} the distribution that describes h...
[ "def", "random_walk_path", "(", "size", ",", "distribution", "=", "None", ",", "start_points", "=", "None", ")", ":", "# TODO allow non-adjacent neighbors also?", "def", "random_walk_iter", "(", "start_pt", ")", ":", "x", ",", "y", "=", "start_pt", "while", "Tru...
Performs random walks as a markov chain with an arbitrary distribution and start points :param size: The size of the image as (width, height) :param distribution: A hash of {(dx, dy): probability} the distribution that describes how the random walk moves to neighboring states. This does not need to be norma...
[ "Performs", "random", "walks", "as", "a", "markov", "chain", "with", "an", "arbitrary", "distribution", "and", "start", "points", ":", "param", "size", ":", "The", "size", "of", "the", "image", "as", "(", "width", "height", ")", ":", "param", "distribution...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L168-L213
rkargon/pixelsorter
pixelsorter/paths.py
horizontal_random_walk
def horizontal_random_walk(size): """ Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates """ _, height = size distribution = {(1, dy): 1 / 3.0 for d...
python
def horizontal_random_walk(size): """ Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates """ _, height = size distribution = {(1, dy): 1 / 3.0 for d...
[ "def", "horizontal_random_walk", "(", "size", ")", ":", "_", ",", "height", "=", "size", "distribution", "=", "{", "(", "1", ",", "dy", ")", ":", "1", "/", "3.0", "for", "dy", "in", "[", "-", "1", ",", "0", ",", "1", "]", "}", "start_points", "...
Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates
[ "Generates", "random", "walks", "that", "start", "at", "the", "left", "side", "of", "the", "image", "and", "move", "towards", "the", "right", ":", "param", "size", ":", "The", "size", "of", "the", "image", ":", "return", ":", "An", "iterator", "of", "p...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L216-L225
rkargon/pixelsorter
pixelsorter/paths.py
vertical_random_walk
def vertical_random_walk(size): """ Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates """ width, _ = size distribution = {(dx, 1): 1 / 3.0 for dx i...
python
def vertical_random_walk(size): """ Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates """ width, _ = size distribution = {(dx, 1): 1 / 3.0 for dx i...
[ "def", "vertical_random_walk", "(", "size", ")", ":", "width", ",", "_", "=", "size", "distribution", "=", "{", "(", "dx", ",", "1", ")", ":", "1", "/", "3.0", "for", "dx", "in", "[", "-", "1", ",", "0", ",", "1", "]", "}", "start_points", "=",...
Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates
[ "Generates", "random", "walks", "that", "start", "at", "the", "left", "side", "of", "the", "image", "and", "move", "towards", "the", "right", ":", "param", "size", ":", "The", "size", "of", "the", "image", ":", "return", ":", "An", "iterator", "of", "p...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L228-L237
rkargon/pixelsorter
pixelsorter/paths.py
bresenham_circle_octant
def bresenham_circle_octant(radius): """ Uses Bresenham's algorithm to draw a single octant of a circle with thickness 1, centered on the origin and with the given radius. :param radius: The radius of the circle to draw :return: A list of integer coordinates representing pixels. Starts at (radiu...
python
def bresenham_circle_octant(radius): """ Uses Bresenham's algorithm to draw a single octant of a circle with thickness 1, centered on the origin and with the given radius. :param radius: The radius of the circle to draw :return: A list of integer coordinates representing pixels. Starts at (radiu...
[ "def", "bresenham_circle_octant", "(", "radius", ")", ":", "x", ",", "y", "=", "radius", ",", "0", "r2", "=", "radius", "*", "radius", "coords", "=", "[", "]", "while", "x", ">=", "y", ":", "coords", ".", "append", "(", "(", "x", ",", "y", ")", ...
Uses Bresenham's algorithm to draw a single octant of a circle with thickness 1, centered on the origin and with the given radius. :param radius: The radius of the circle to draw :return: A list of integer coordinates representing pixels. Starts at (radius, 0) and end with a pixel (x, y) where x == y.
[ "Uses", "Bresenham", "s", "algorithm", "to", "draw", "a", "single", "octant", "of", "a", "circle", "with", "thickness", "1", "centered", "on", "the", "origin", "and", "with", "the", "given", "radius", ".", ":", "param", "radius", ":", "The", "radius", "o...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L240-L259
rkargon/pixelsorter
pixelsorter/paths.py
concentric_circle
def concentric_circle(center, radius, size=None): """ Draws a circle with the given center and radius. This is designed to ensure that concentric circles with integer radii are "airtight", i.e. there are not unfilled pixels between them. :param center: The (x, y) coordinates of the center of the cir...
python
def concentric_circle(center, radius, size=None): """ Draws a circle with the given center and radius. This is designed to ensure that concentric circles with integer radii are "airtight", i.e. there are not unfilled pixels between them. :param center: The (x, y) coordinates of the center of the cir...
[ "def", "concentric_circle", "(", "center", ",", "radius", ",", "size", "=", "None", ")", ":", "c_out", "=", "bresenham_circle_octant", "(", "radius", "+", "1", ")", "c_in", "=", "bresenham_circle_octant", "(", "radius", ")", "coords", "=", "[", "]", "# not...
Draws a circle with the given center and radius. This is designed to ensure that concentric circles with integer radii are "airtight", i.e. there are not unfilled pixels between them. :param center: The (x, y) coordinates of the center of the circle :param radius: :param size: If not None, the size ...
[ "Draws", "a", "circle", "with", "the", "given", "center", "and", "radius", ".", "This", "is", "designed", "to", "ensure", "that", "concentric", "circles", "with", "integer", "radii", "are", "airtight", "i", ".", "e", ".", "there", "are", "not", "unfilled",...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L262-L295
rkargon/pixelsorter
pixelsorter/paths.py
fill_concentric_circles
def fill_concentric_circles(size, center, radius): """ Returns a path that fills a concentric circle with the given radius and center. :param radius: :param center: :param size: The size of the image, used to skip points that are out of bounds. :return: Yields iterators, where each iterator yiel...
python
def fill_concentric_circles(size, center, radius): """ Returns a path that fills a concentric circle with the given radius and center. :param radius: :param center: :param size: The size of the image, used to skip points that are out of bounds. :return: Yields iterators, where each iterator yiel...
[ "def", "fill_concentric_circles", "(", "size", ",", "center", ",", "radius", ")", ":", "for", "r", "in", "range", "(", "radius", ")", ":", "yield", "concentric_circle", "(", "center", ",", "r", ",", "size", "=", "size", ")" ]
Returns a path that fills a concentric circle with the given radius and center. :param radius: :param center: :param size: The size of the image, used to skip points that are out of bounds. :return: Yields iterators, where each iterator yields (x,y) coordinates of points about the circle. The path m...
[ "Returns", "a", "path", "that", "fills", "a", "concentric", "circle", "with", "the", "given", "radius", "and", "center", ".", ":", "param", "radius", ":", ":", "param", "center", ":", ":", "param", "size", ":", "The", "size", "of", "the", "image", "use...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L298-L309
rkargon/pixelsorter
pixelsorter/paths.py
concentric_circles_path
def concentric_circles_path(size): """ Yields a set of paths that are concentric circles, moving outwards, about the center of the image. :param size: The (width, height) of the image :return: Yields individual circles, where each circle is a generator that yields pixel coordinates. """ width, ...
python
def concentric_circles_path(size): """ Yields a set of paths that are concentric circles, moving outwards, about the center of the image. :param size: The (width, height) of the image :return: Yields individual circles, where each circle is a generator that yields pixel coordinates. """ width, ...
[ "def", "concentric_circles_path", "(", "size", ")", ":", "width", ",", "height", "=", "size", "x0", ",", "y0", "=", "width", "//", "2", ",", "height", "//", "2", "max_radius", "=", "int", "(", "sqrt", "(", "2", ")", "*", "max", "(", "height", ",", ...
Yields a set of paths that are concentric circles, moving outwards, about the center of the image. :param size: The (width, height) of the image :return: Yields individual circles, where each circle is a generator that yields pixel coordinates.
[ "Yields", "a", "set", "of", "paths", "that", "are", "concentric", "circles", "moving", "outwards", "about", "the", "center", "of", "the", "image", ".", ":", "param", "size", ":", "The", "(", "width", "height", ")", "of", "the", "image", ":", "return", ...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L312-L321
rkargon/pixelsorter
pixelsorter/paths.py
fill_with_circles_path
def fill_with_circles_path(size, radius=100): """ Covers an image with a set of overlapping circles of the given radius. :param size: The size of the image :param radius: The radius of the circles in question :return: Yields a set of filled circles that cover the whole image. Each circle is made...
python
def fill_with_circles_path(size, radius=100): """ Covers an image with a set of overlapping circles of the given radius. :param size: The size of the image :param radius: The radius of the circles in question :return: Yields a set of filled circles that cover the whole image. Each circle is made...
[ "def", "fill_with_circles_path", "(", "size", ",", "radius", "=", "100", ")", ":", "width", ",", "height", "=", "size", "radius", "=", "int", "(", "radius", ")", "dx", "=", "dy", "=", "int", "(", "2", "*", "radius", "/", "sqrt", "(", "2", ")", ")...
Covers an image with a set of overlapping circles of the given radius. :param size: The size of the image :param radius: The radius of the circles in question :return: Yields a set of filled circles that cover the whole image. Each circle is made up of individual concentric circles.
[ "Covers", "an", "image", "with", "a", "set", "of", "overlapping", "circles", "of", "the", "given", "radius", ".", ":", "param", "size", ":", "The", "size", "of", "the", "image", ":", "param", "radius", ":", "The", "radius", "of", "the", "circles", "in"...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/paths.py#L324-L337
rkargon/pixelsorter
pixelsorter/images2gif.py
intToBin
def intToBin(i): """ Integer to two bytes """ # divide in two parts (bytes) i1 = i % 256 i2 = int(i / 256) # make string (little endian) return i.to_bytes(2, byteorder='little')
python
def intToBin(i): """ Integer to two bytes """ # divide in two parts (bytes) i1 = i % 256 i2 = int(i / 256) # make string (little endian) return i.to_bytes(2, byteorder='little')
[ "def", "intToBin", "(", "i", ")", ":", "# divide in two parts (bytes)", "i1", "=", "i", "%", "256", "i2", "=", "int", "(", "i", "/", "256", ")", "# make string (little endian)", "return", "i", ".", "to_bytes", "(", "2", ",", "byteorder", "=", "'little'", ...
Integer to two bytes
[ "Integer", "to", "two", "bytes" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L140-L146
rkargon/pixelsorter
pixelsorter/images2gif.py
get_gif_frames
def get_gif_frames(img): """ Extracts the frames from an animated gif. :param img: A PIL Image object :return: An array of PIL image objects, each corresponding to a frame in the animation. """ gif_frames = [] n = 0 while img: if img.mode != "RGB": image = img.convert...
python
def get_gif_frames(img): """ Extracts the frames from an animated gif. :param img: A PIL Image object :return: An array of PIL image objects, each corresponding to a frame in the animation. """ gif_frames = [] n = 0 while img: if img.mode != "RGB": image = img.convert...
[ "def", "get_gif_frames", "(", "img", ")", ":", "gif_frames", "=", "[", "]", "n", "=", "0", "while", "img", ":", "if", "img", ".", "mode", "!=", "\"RGB\"", ":", "image", "=", "img", ".", "convert", "(", "mode", "=", "\"RGB\"", ")", "else", ":", "i...
Extracts the frames from an animated gif. :param img: A PIL Image object :return: An array of PIL image objects, each corresponding to a frame in the animation.
[ "Extracts", "the", "frames", "from", "an", "animated", "gif", ".", ":", "param", "img", ":", "A", "PIL", "Image", "object", ":", "return", ":", "An", "array", "of", "PIL", "image", "objects", "each", "corresponding", "to", "a", "frame", "in", "the", "a...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1068-L1087
rkargon/pixelsorter
pixelsorter/images2gif.py
GifWriter.getheaderAnim
def getheaderAnim(self, im): """ getheaderAnim(im) Get animation header. To replace PILs getheader()[0] """ bb = b'GIF89a' bb += intToBin(im.size[0]) bb += intToBin(im.size[1]) bb += b'\x87\x00\x00' return bb
python
def getheaderAnim(self, im): """ getheaderAnim(im) Get animation header. To replace PILs getheader()[0] """ bb = b'GIF89a' bb += intToBin(im.size[0]) bb += intToBin(im.size[1]) bb += b'\x87\x00\x00' return bb
[ "def", "getheaderAnim", "(", "self", ",", "im", ")", ":", "bb", "=", "b'GIF89a'", "bb", "+=", "intToBin", "(", "im", ".", "size", "[", "0", "]", ")", "bb", "+=", "intToBin", "(", "im", ".", "size", "[", "1", "]", ")", "bb", "+=", "b'\\x87\\x00\\x...
getheaderAnim(im) Get animation header. To replace PILs getheader()[0]
[ "getheaderAnim", "(", "im", ")" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L156-L166
rkargon/pixelsorter
pixelsorter/images2gif.py
GifWriter.getImageDescriptor
def getImageDescriptor(self, im, xy=None): """ getImageDescriptor(im, xy=None) Used for the local color table properties per image. Otherwise global color table applies to all frames irrespective of whether additional colors comes in play that require a redefined palette. Still ...
python
def getImageDescriptor(self, im, xy=None): """ getImageDescriptor(im, xy=None) Used for the local color table properties per image. Otherwise global color table applies to all frames irrespective of whether additional colors comes in play that require a redefined palette. Still ...
[ "def", "getImageDescriptor", "(", "self", ",", "im", ",", "xy", "=", "None", ")", ":", "# Default use full image and place at upper left", "if", "xy", "is", "None", ":", "xy", "=", "(", "0", ",", "0", ")", "# Image separator,", "bb", "=", "b'\\x2C'", "# Imag...
getImageDescriptor(im, xy=None) Used for the local color table properties per image. Otherwise global color table applies to all frames irrespective of whether additional colors comes in play that require a redefined palette. Still a maximum of 256 color per frame, obviously. W...
[ "getImageDescriptor", "(", "im", "xy", "=", "None", ")" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L168-L199
rkargon/pixelsorter
pixelsorter/images2gif.py
GifWriter.getAppExt
def getAppExt(self, loops=float('inf')): """ getAppExt(loops=float('inf')) Application extension. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely. """ if loops == 0 or loops == float('inf'): loops = 2 ** 16 - 1 bb = b"" ...
python
def getAppExt(self, loops=float('inf')): """ getAppExt(loops=float('inf')) Application extension. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely. """ if loops == 0 or loops == float('inf'): loops = 2 ** 16 - 1 bb = b"" ...
[ "def", "getAppExt", "(", "self", ",", "loops", "=", "float", "(", "'inf'", ")", ")", ":", "if", "loops", "==", "0", "or", "loops", "==", "float", "(", "'inf'", ")", ":", "loops", "=", "2", "**", "16", "-", "1", "bb", "=", "b\"\"", "if", "loops"...
getAppExt(loops=float('inf')) Application extension. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely.
[ "getAppExt", "(", "loops", "=", "float", "(", "inf", "))" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L201-L218
rkargon/pixelsorter
pixelsorter/images2gif.py
GifWriter.getGraphicsControlExt
def getGraphicsControlExt(self, duration=0.1, dispose=2, transparent_flag=0, transparency_index=0): """ getGraphicsControlExt(duration=0.1, dispose=2) Graphics Control Extension. A sort of header at the start of each image. Specifies duration and transparancy. Dispose ------- ...
python
def getGraphicsControlExt(self, duration=0.1, dispose=2, transparent_flag=0, transparency_index=0): """ getGraphicsControlExt(duration=0.1, dispose=2) Graphics Control Extension. A sort of header at the start of each image. Specifies duration and transparancy. Dispose ------- ...
[ "def", "getGraphicsControlExt", "(", "self", ",", "duration", "=", "0.1", ",", "dispose", "=", "2", ",", "transparent_flag", "=", "0", ",", "transparency_index", "=", "0", ")", ":", "bb", "=", "b'\\x21\\xF9\\x04'", "bb", "+=", "bytes", "(", "[", "(", "("...
getGraphicsControlExt(duration=0.1, dispose=2) Graphics Control Extension. A sort of header at the start of each image. Specifies duration and transparancy. Dispose ------- * 0 - No disposal specified. * 1 - Do not dispose. The graphic is to be left in place. ...
[ "getGraphicsControlExt", "(", "duration", "=", "0", ".", "1", "dispose", "=", "2", ")" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L220-L246
rkargon/pixelsorter
pixelsorter/images2gif.py
NeuQuant.altersingle
def altersingle(self, alpha, i, b, g, r): """Move neuron i towards biased (b,g,r) by factor alpha""" n = self.network[i] # Alter hit neuron n[0] -= (alpha * (n[0] - b)) n[1] -= (alpha * (n[1] - g)) n[2] -= (alpha * (n[2] - r))
python
def altersingle(self, alpha, i, b, g, r): """Move neuron i towards biased (b,g,r) by factor alpha""" n = self.network[i] # Alter hit neuron n[0] -= (alpha * (n[0] - b)) n[1] -= (alpha * (n[1] - g)) n[2] -= (alpha * (n[2] - r))
[ "def", "altersingle", "(", "self", ",", "alpha", ",", "i", ",", "b", ",", "g", ",", "r", ")", ":", "n", "=", "self", ".", "network", "[", "i", "]", "# Alter hit neuron", "n", "[", "0", "]", "-=", "(", "alpha", "*", "(", "n", "[", "0", "]", ...
Move neuron i towards biased (b,g,r) by factor alpha
[ "Move", "neuron", "i", "towards", "biased", "(", "b", "g", "r", ")", "by", "factor", "alpha" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L817-L822
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" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1017-L1023
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" ]
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L1061-L1065
rkargon/pixelsorter
pixelsorter/edge_detection.py
edge_detect
def edge_detect(image, size): """ Applies a Sobel filter to the given image. :param image: An image as a list of (R,G,B) values :param size: The size of the image as a tuple (width, height) :return: An array of the Sobel gradient value of each image pixel This value roughly corresponds to how mu...
python
def edge_detect(image, size): """ Applies a Sobel filter to the given image. :param image: An image as a list of (R,G,B) values :param size: The size of the image as a tuple (width, height) :return: An array of the Sobel gradient value of each image pixel This value roughly corresponds to how mu...
[ "def", "edge_detect", "(", "image", ",", "size", ")", ":", "# TODO get edge data for boundaries", "width", ",", "height", "=", "size", "edge_data", "=", "[", "0", "]", "*", "len", "(", "image", ")", "gray_scale_img", "=", "list", "(", "map", "(", "luma", ...
Applies a Sobel filter to the given image. :param image: An image as a list of (R,G,B) values :param size: The size of the image as a tuple (width, height) :return: An array of the Sobel gradient value of each image pixel This value roughly corresponds to how much of an "edge" a pixel is.
[ "Applies", "a", "Sobel", "filter", "to", "the", "given", "image", ".", ":", "param", "image", ":", "An", "image", "as", "a", "list", "of", "(", "R", "G", "B", ")", "values", ":", "param", "size", ":", "The", "size", "of", "the", "image", "as", "a...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/edge_detection.py#L29-L58
rkargon/pixelsorter
pixelsorter/edge_detection.py
highlight_threshold
def highlight_threshold(image, img_data, threshold, color=(255, 0, 0)): """ Given an array of values for an image, highlights pixels whose value is greater than the given threshold. :param image: The image to highlight :param img_data: The values to use :param threshold: The threshold above which pi...
python
def highlight_threshold(image, img_data, threshold, color=(255, 0, 0)): """ Given an array of values for an image, highlights pixels whose value is greater than the given threshold. :param image: The image to highlight :param img_data: The values to use :param threshold: The threshold above which pi...
[ "def", "highlight_threshold", "(", "image", ",", "img_data", ",", "threshold", ",", "color", "=", "(", "255", ",", "0", ",", "0", ")", ")", ":", "out_pixels", "=", "list", "(", "image", ")", "for", "i", "in", "range", "(", "len", "(", "image", ")",...
Given an array of values for an image, highlights pixels whose value is greater than the given threshold. :param image: The image to highlight :param img_data: The values to use :param threshold: The threshold above which pixels should the highlighted :param color: The color to highlight pixels with ...
[ "Given", "an", "array", "of", "values", "for", "an", "image", "highlights", "pixels", "whose", "value", "is", "greater", "than", "the", "given", "threshold", ".", ":", "param", "image", ":", "The", "image", "to", "highlight", ":", "param", "img_data", ":",...
train
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/edge_detection.py#L61-L75
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", "." ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L15-L26
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", "." ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L29-L35
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", "." ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L38-L48
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", "." ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L92-L140
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" ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/cli/glimpse.py#L143-L168
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", "." ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/simulation.py#L262-L328
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", "." ]
train
https://github.com/European-XFEL/karabo-bridge-py/blob/ca20d72b8beb0039649d10cb01d027db42efd91c/karabo_bridge/client.py#L90-L122