id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
238,800
shoeffner/pandoc-source-exec
pandoc_source_exec.py
filter_lines
def filter_lines(code, line_spec): """Removes all lines not matching the line_spec. Args: code The code to filter line_spec The line specification. This should be a comma-separated string of lines or line ranges, e.g. 1,2,5-12,15 If a line range starts with -, all lines up to this line are included. If a line range ends with -, all lines from this line on are included. All lines mentioned (ranges are inclusive) are used. Returns: Only the specified lines. """ code_lines = code.splitlines() line_specs = [line_denom.strip() for line_denom in line_spec.split(',')] single_lines = set(map(int, filter(lambda line: '-' not in line, line_specs))) line_ranges = set(filter(lambda line: '-' in line, line_specs)) for line_range in line_ranges: begin, end = line_range.split('-') if not begin: begin = 1 if not end: end = len(code_lines) single_lines.update(range(int(begin), int(end) + 1)) keep_lines = [] for line_number, line in enumerate(code_lines, 1): if line_number in single_lines: keep_lines.append(line) return '\n'.join(keep_lines)
python
def filter_lines(code, line_spec): """Removes all lines not matching the line_spec. Args: code The code to filter line_spec The line specification. This should be a comma-separated string of lines or line ranges, e.g. 1,2,5-12,15 If a line range starts with -, all lines up to this line are included. If a line range ends with -, all lines from this line on are included. All lines mentioned (ranges are inclusive) are used. Returns: Only the specified lines. """ code_lines = code.splitlines() line_specs = [line_denom.strip() for line_denom in line_spec.split(',')] single_lines = set(map(int, filter(lambda line: '-' not in line, line_specs))) line_ranges = set(filter(lambda line: '-' in line, line_specs)) for line_range in line_ranges: begin, end = line_range.split('-') if not begin: begin = 1 if not end: end = len(code_lines) single_lines.update(range(int(begin), int(end) + 1)) keep_lines = [] for line_number, line in enumerate(code_lines, 1): if line_number in single_lines: keep_lines.append(line) return '\n'.join(keep_lines)
[ "def", "filter_lines", "(", "code", ",", "line_spec", ")", ":", "code_lines", "=", "code", ".", "splitlines", "(", ")", "line_specs", "=", "[", "line_denom", ".", "strip", "(", ")", "for", "line_denom", "in", "line_spec", ".", "split", "(", "','", ")", "]", "single_lines", "=", "set", "(", "map", "(", "int", ",", "filter", "(", "lambda", "line", ":", "'-'", "not", "in", "line", ",", "line_specs", ")", ")", ")", "line_ranges", "=", "set", "(", "filter", "(", "lambda", "line", ":", "'-'", "in", "line", ",", "line_specs", ")", ")", "for", "line_range", "in", "line_ranges", ":", "begin", ",", "end", "=", "line_range", ".", "split", "(", "'-'", ")", "if", "not", "begin", ":", "begin", "=", "1", "if", "not", "end", ":", "end", "=", "len", "(", "code_lines", ")", "single_lines", ".", "update", "(", "range", "(", "int", "(", "begin", ")", ",", "int", "(", "end", ")", "+", "1", ")", ")", "keep_lines", "=", "[", "]", "for", "line_number", ",", "line", "in", "enumerate", "(", "code_lines", ",", "1", ")", ":", "if", "line_number", "in", "single_lines", ":", "keep_lines", ".", "append", "(", "line", ")", "return", "'\\n'", ".", "join", "(", "keep_lines", ")" ]
Removes all lines not matching the line_spec. Args: code The code to filter line_spec The line specification. This should be a comma-separated string of lines or line ranges, e.g. 1,2,5-12,15 If a line range starts with -, all lines up to this line are included. If a line range ends with -, all lines from this line on are included. All lines mentioned (ranges are inclusive) are used. Returns: Only the specified lines.
[ "Removes", "all", "lines", "not", "matching", "the", "line_spec", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L149-L184
238,801
shoeffner/pandoc-source-exec
pandoc_source_exec.py
remove_import_statements
def remove_import_statements(code): """Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements. """ new_code = [] for line in code.splitlines(): if not line.lstrip().startswith('import ') and \ not line.lstrip().startswith('from '): new_code.append(line) while new_code and new_code[0] == '': new_code.pop(0) while new_code and new_code[-1] == '': new_code.pop() return '\n'.join(new_code)
python
def remove_import_statements(code): """Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements. """ new_code = [] for line in code.splitlines(): if not line.lstrip().startswith('import ') and \ not line.lstrip().startswith('from '): new_code.append(line) while new_code and new_code[0] == '': new_code.pop(0) while new_code and new_code[-1] == '': new_code.pop() return '\n'.join(new_code)
[ "def", "remove_import_statements", "(", "code", ")", ":", "new_code", "=", "[", "]", "for", "line", "in", "code", ".", "splitlines", "(", ")", ":", "if", "not", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "'import '", ")", "and", "not", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "'from '", ")", ":", "new_code", ".", "append", "(", "line", ")", "while", "new_code", "and", "new_code", "[", "0", "]", "==", "''", ":", "new_code", ".", "pop", "(", "0", ")", "while", "new_code", "and", "new_code", "[", "-", "1", "]", "==", "''", ":", "new_code", ".", "pop", "(", ")", "return", "'\\n'", ".", "join", "(", "new_code", ")" ]
Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements.
[ "Removes", "lines", "with", "import", "statements", "from", "the", "code", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L189-L209
238,802
shoeffner/pandoc-source-exec
pandoc_source_exec.py
save_plot
def save_plot(code, elem): """Converts matplotlib plots to tikz code. If elem has either the plt attribute (format: plt=width,height) or the attributes width=width and/or height=height, the figurewidth and -height are set accordingly. If none are given, a height of 4cm and a width of 6cm is used as default. Args: code: The matplotlib code. elem: The element. Returns: The code and some code to invoke matplotlib2tikz. """ if 'plt' in elem.attributes: figurewidth, figureheight = elem.attributes['plt'].split(',') else: try: figureheight = elem.attributes['height'] except KeyError: figureheight = '4cm' try: figurewidth = elem.attributes['width'] except KeyError: figurewidth = '6cm' return f"""import matplotlib matplotlib.use('TkAgg') {code} from matplotlib2tikz import get_tikz_code tikz = get_tikz_code(figureheight='{figureheight}', figurewidth='{figurewidth}') # noqa print(tikz)"""
python
def save_plot(code, elem): """Converts matplotlib plots to tikz code. If elem has either the plt attribute (format: plt=width,height) or the attributes width=width and/or height=height, the figurewidth and -height are set accordingly. If none are given, a height of 4cm and a width of 6cm is used as default. Args: code: The matplotlib code. elem: The element. Returns: The code and some code to invoke matplotlib2tikz. """ if 'plt' in elem.attributes: figurewidth, figureheight = elem.attributes['plt'].split(',') else: try: figureheight = elem.attributes['height'] except KeyError: figureheight = '4cm' try: figurewidth = elem.attributes['width'] except KeyError: figurewidth = '6cm' return f"""import matplotlib matplotlib.use('TkAgg') {code} from matplotlib2tikz import get_tikz_code tikz = get_tikz_code(figureheight='{figureheight}', figurewidth='{figurewidth}') # noqa print(tikz)"""
[ "def", "save_plot", "(", "code", ",", "elem", ")", ":", "if", "'plt'", "in", "elem", ".", "attributes", ":", "figurewidth", ",", "figureheight", "=", "elem", ".", "attributes", "[", "'plt'", "]", ".", "split", "(", "','", ")", "else", ":", "try", ":", "figureheight", "=", "elem", ".", "attributes", "[", "'height'", "]", "except", "KeyError", ":", "figureheight", "=", "'4cm'", "try", ":", "figurewidth", "=", "elem", ".", "attributes", "[", "'width'", "]", "except", "KeyError", ":", "figurewidth", "=", "'6cm'", "return", "f\"\"\"import matplotlib\nmatplotlib.use('TkAgg')\n{code}\nfrom matplotlib2tikz import get_tikz_code\ntikz = get_tikz_code(figureheight='{figureheight}', figurewidth='{figurewidth}') # noqa\nprint(tikz)\"\"\"" ]
Converts matplotlib plots to tikz code. If elem has either the plt attribute (format: plt=width,height) or the attributes width=width and/or height=height, the figurewidth and -height are set accordingly. If none are given, a height of 4cm and a width of 6cm is used as default. Args: code: The matplotlib code. elem: The element. Returns: The code and some code to invoke matplotlib2tikz.
[ "Converts", "matplotlib", "plots", "to", "tikz", "code", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L212-L245
238,803
shoeffner/pandoc-source-exec
pandoc_source_exec.py
trimpath
def trimpath(attributes): """Simplifies the given path. If pathdepth is in attributes, the last pathdepth elements will be returned. If pathdepth is "full", the full path will be returned. Otherwise the filename only will be returned. Args: attributes: The element attributes. Returns: The trimmed path. """ if 'pathdepth' in attributes: if attributes['pathdepth'] != 'full': pathelements = [] remainder = attributes['file'] limit = int(attributes['pathdepth']) while len(pathelements) < limit and remainder: remainder, pe = os.path.split(remainder) pathelements.insert(0, pe) return os.path.join(*pathelements) return attributes['file'] return os.path.basename(attributes['file'])
python
def trimpath(attributes): """Simplifies the given path. If pathdepth is in attributes, the last pathdepth elements will be returned. If pathdepth is "full", the full path will be returned. Otherwise the filename only will be returned. Args: attributes: The element attributes. Returns: The trimmed path. """ if 'pathdepth' in attributes: if attributes['pathdepth'] != 'full': pathelements = [] remainder = attributes['file'] limit = int(attributes['pathdepth']) while len(pathelements) < limit and remainder: remainder, pe = os.path.split(remainder) pathelements.insert(0, pe) return os.path.join(*pathelements) return attributes['file'] return os.path.basename(attributes['file'])
[ "def", "trimpath", "(", "attributes", ")", ":", "if", "'pathdepth'", "in", "attributes", ":", "if", "attributes", "[", "'pathdepth'", "]", "!=", "'full'", ":", "pathelements", "=", "[", "]", "remainder", "=", "attributes", "[", "'file'", "]", "limit", "=", "int", "(", "attributes", "[", "'pathdepth'", "]", ")", "while", "len", "(", "pathelements", ")", "<", "limit", "and", "remainder", ":", "remainder", ",", "pe", "=", "os", ".", "path", ".", "split", "(", "remainder", ")", "pathelements", ".", "insert", "(", "0", ",", "pe", ")", "return", "os", ".", "path", ".", "join", "(", "*", "pathelements", ")", "return", "attributes", "[", "'file'", "]", "return", "os", ".", "path", ".", "basename", "(", "attributes", "[", "'file'", "]", ")" ]
Simplifies the given path. If pathdepth is in attributes, the last pathdepth elements will be returned. If pathdepth is "full", the full path will be returned. Otherwise the filename only will be returned. Args: attributes: The element attributes. Returns: The trimmed path.
[ "Simplifies", "the", "given", "path", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L248-L271
238,804
shoeffner/pandoc-source-exec
pandoc_source_exec.py
prepare
def prepare(doc): """Sets the caption_found and plot_found variables to False.""" doc.caption_found = False doc.plot_found = False doc.listings_counter = 0
python
def prepare(doc): """Sets the caption_found and plot_found variables to False.""" doc.caption_found = False doc.plot_found = False doc.listings_counter = 0
[ "def", "prepare", "(", "doc", ")", ":", "doc", ".", "caption_found", "=", "False", "doc", ".", "plot_found", "=", "False", "doc", ".", "listings_counter", "=", "0" ]
Sets the caption_found and plot_found variables to False.
[ "Sets", "the", "caption_found", "and", "plot_found", "variables", "to", "False", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L311-L315
238,805
shoeffner/pandoc-source-exec
pandoc_source_exec.py
maybe_center_plot
def maybe_center_plot(result): """Embeds a possible tikz image inside a center environment. Searches for matplotlib2tikz last commend line to detect tikz images. Args: result: The code execution result Returns: The input result if no tikzpicture was found, otherwise a centered version. """ begin = re.search('(% .* matplotlib2tikz v.*)', result) if begin: result = ('\\begin{center}\n' + result[begin.end():] + '\n\\end{center}') return result
python
def maybe_center_plot(result): """Embeds a possible tikz image inside a center environment. Searches for matplotlib2tikz last commend line to detect tikz images. Args: result: The code execution result Returns: The input result if no tikzpicture was found, otherwise a centered version. """ begin = re.search('(% .* matplotlib2tikz v.*)', result) if begin: result = ('\\begin{center}\n' + result[begin.end():] + '\n\\end{center}') return result
[ "def", "maybe_center_plot", "(", "result", ")", ":", "begin", "=", "re", ".", "search", "(", "'(% .* matplotlib2tikz v.*)'", ",", "result", ")", "if", "begin", ":", "result", "=", "(", "'\\\\begin{center}\\n'", "+", "result", "[", "begin", ".", "end", "(", ")", ":", "]", "+", "'\\n\\\\end{center}'", ")", "return", "result" ]
Embeds a possible tikz image inside a center environment. Searches for matplotlib2tikz last commend line to detect tikz images. Args: result: The code execution result Returns: The input result if no tikzpicture was found, otherwise a centered version.
[ "Embeds", "a", "possible", "tikz", "image", "inside", "a", "center", "environment", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L318-L334
238,806
shoeffner/pandoc-source-exec
pandoc_source_exec.py
action
def action(elem, doc): # noqa """Processes pf.CodeBlocks. For details and a specification of how each command should behave, check the example files (especially the md and pdf)! Args: elem: The element to process. doc: The document. Returns: A changed element or None. """ if isinstance(elem, pf.CodeBlock): doc.listings_counter += 1 elems = [elem] if 'hide' not in elem.classes else [] if 'file' in elem.attributes: elem.text = read_file(elem.attributes['file']) filename = trimpath(elem.attributes) prefix = pf.Emph(pf.Str('File:')) if 'exec' in elem.classes: if 'interactive' in elem.classes or elem.text[:4] == '>>> ': elem.text = execute_interactive_code(elem, doc) else: result = execute_code_block(elem, doc) if 'hideimports' in elem.classes: elem.text = remove_import_statements(elem.text) if 'plt' in elem.attributes or 'plt' in elem.classes: doc.plot_found = True result = maybe_center_plot(result) block = pf.RawBlock(result, format='latex') else: block = pf.CodeBlock(result, classes=['changelog']) elems += [pf.Para(pf.Emph(pf.Str('Output:'))), block] if 'lines' in elem.attributes: elem.text = filter_lines(elem.text, elem.attributes['lines']) label = elem.attributes.get('label', f'cl:{doc.listings_counter}') if 'caption' in elem.attributes.keys(): doc.caption_found = True cap = pf.convert_text(elem.attributes['caption'], output_format='latex') # noqa if 'shortcaption' in elem.attributes.keys(): shortcap = pf.convert_text(elem.attributes['shortcaption'], output_format='latex') # noqa else: shortcap = cap if 'file' in elem.attributes.keys(): cap += pf.convert_text(f'&nbsp;(`{filename}`)', output_format='latex') # noqa elems = make_codelisting(elems, cap, label, shortcaption=shortcap, above='capbelow' not in elem.classes) elif 'caption' in elem.classes: doc.caption_found = True cap = '' if 'file' in elem.attributes.keys(): cap = pf.convert_text(f'`{filename}`', output_format='latex') elems = make_codelisting(elems, cap, label, above='capbelow' not in elem.classes) else: if 'file' in elem.attributes.keys(): elems.insert(0, pf.Para(prefix, pf.Space, pf.Code(filename))) return elems
python
def action(elem, doc): # noqa """Processes pf.CodeBlocks. For details and a specification of how each command should behave, check the example files (especially the md and pdf)! Args: elem: The element to process. doc: The document. Returns: A changed element or None. """ if isinstance(elem, pf.CodeBlock): doc.listings_counter += 1 elems = [elem] if 'hide' not in elem.classes else [] if 'file' in elem.attributes: elem.text = read_file(elem.attributes['file']) filename = trimpath(elem.attributes) prefix = pf.Emph(pf.Str('File:')) if 'exec' in elem.classes: if 'interactive' in elem.classes or elem.text[:4] == '>>> ': elem.text = execute_interactive_code(elem, doc) else: result = execute_code_block(elem, doc) if 'hideimports' in elem.classes: elem.text = remove_import_statements(elem.text) if 'plt' in elem.attributes or 'plt' in elem.classes: doc.plot_found = True result = maybe_center_plot(result) block = pf.RawBlock(result, format='latex') else: block = pf.CodeBlock(result, classes=['changelog']) elems += [pf.Para(pf.Emph(pf.Str('Output:'))), block] if 'lines' in elem.attributes: elem.text = filter_lines(elem.text, elem.attributes['lines']) label = elem.attributes.get('label', f'cl:{doc.listings_counter}') if 'caption' in elem.attributes.keys(): doc.caption_found = True cap = pf.convert_text(elem.attributes['caption'], output_format='latex') # noqa if 'shortcaption' in elem.attributes.keys(): shortcap = pf.convert_text(elem.attributes['shortcaption'], output_format='latex') # noqa else: shortcap = cap if 'file' in elem.attributes.keys(): cap += pf.convert_text(f'&nbsp;(`{filename}`)', output_format='latex') # noqa elems = make_codelisting(elems, cap, label, shortcaption=shortcap, above='capbelow' not in elem.classes) elif 'caption' in elem.classes: doc.caption_found = True cap = '' if 'file' in elem.attributes.keys(): cap = pf.convert_text(f'`{filename}`', output_format='latex') elems = make_codelisting(elems, cap, label, above='capbelow' not in elem.classes) else: if 'file' in elem.attributes.keys(): elems.insert(0, pf.Para(prefix, pf.Space, pf.Code(filename))) return elems
[ "def", "action", "(", "elem", ",", "doc", ")", ":", "# noqa", "if", "isinstance", "(", "elem", ",", "pf", ".", "CodeBlock", ")", ":", "doc", ".", "listings_counter", "+=", "1", "elems", "=", "[", "elem", "]", "if", "'hide'", "not", "in", "elem", ".", "classes", "else", "[", "]", "if", "'file'", "in", "elem", ".", "attributes", ":", "elem", ".", "text", "=", "read_file", "(", "elem", ".", "attributes", "[", "'file'", "]", ")", "filename", "=", "trimpath", "(", "elem", ".", "attributes", ")", "prefix", "=", "pf", ".", "Emph", "(", "pf", ".", "Str", "(", "'File:'", ")", ")", "if", "'exec'", "in", "elem", ".", "classes", ":", "if", "'interactive'", "in", "elem", ".", "classes", "or", "elem", ".", "text", "[", ":", "4", "]", "==", "'>>> '", ":", "elem", ".", "text", "=", "execute_interactive_code", "(", "elem", ",", "doc", ")", "else", ":", "result", "=", "execute_code_block", "(", "elem", ",", "doc", ")", "if", "'hideimports'", "in", "elem", ".", "classes", ":", "elem", ".", "text", "=", "remove_import_statements", "(", "elem", ".", "text", ")", "if", "'plt'", "in", "elem", ".", "attributes", "or", "'plt'", "in", "elem", ".", "classes", ":", "doc", ".", "plot_found", "=", "True", "result", "=", "maybe_center_plot", "(", "result", ")", "block", "=", "pf", ".", "RawBlock", "(", "result", ",", "format", "=", "'latex'", ")", "else", ":", "block", "=", "pf", ".", "CodeBlock", "(", "result", ",", "classes", "=", "[", "'changelog'", "]", ")", "elems", "+=", "[", "pf", ".", "Para", "(", "pf", ".", "Emph", "(", "pf", ".", "Str", "(", "'Output:'", ")", ")", ")", ",", "block", "]", "if", "'lines'", "in", "elem", ".", "attributes", ":", "elem", ".", "text", "=", "filter_lines", "(", "elem", ".", "text", ",", "elem", ".", "attributes", "[", "'lines'", "]", ")", "label", "=", "elem", ".", "attributes", ".", "get", "(", "'label'", ",", "f'cl:{doc.listings_counter}'", ")", "if", "'caption'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "doc", ".", "caption_found", "=", "True", "cap", "=", "pf", ".", "convert_text", "(", "elem", ".", "attributes", "[", "'caption'", "]", ",", "output_format", "=", "'latex'", ")", "# noqa", "if", "'shortcaption'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "shortcap", "=", "pf", ".", "convert_text", "(", "elem", ".", "attributes", "[", "'shortcaption'", "]", ",", "output_format", "=", "'latex'", ")", "# noqa", "else", ":", "shortcap", "=", "cap", "if", "'file'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "cap", "+=", "pf", ".", "convert_text", "(", "f'&nbsp;(`{filename}`)'", ",", "output_format", "=", "'latex'", ")", "# noqa", "elems", "=", "make_codelisting", "(", "elems", ",", "cap", ",", "label", ",", "shortcaption", "=", "shortcap", ",", "above", "=", "'capbelow'", "not", "in", "elem", ".", "classes", ")", "elif", "'caption'", "in", "elem", ".", "classes", ":", "doc", ".", "caption_found", "=", "True", "cap", "=", "''", "if", "'file'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "cap", "=", "pf", ".", "convert_text", "(", "f'`{filename}`'", ",", "output_format", "=", "'latex'", ")", "elems", "=", "make_codelisting", "(", "elems", ",", "cap", ",", "label", ",", "above", "=", "'capbelow'", "not", "in", "elem", ".", "classes", ")", "else", ":", "if", "'file'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "elems", ".", "insert", "(", "0", ",", "pf", ".", "Para", "(", "prefix", ",", "pf", ".", "Space", ",", "pf", ".", "Code", "(", "filename", ")", ")", ")", "return", "elems" ]
Processes pf.CodeBlocks. For details and a specification of how each command should behave, check the example files (especially the md and pdf)! Args: elem: The element to process. doc: The document. Returns: A changed element or None.
[ "Processes", "pf", ".", "CodeBlocks", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L337-L406
238,807
shoeffner/pandoc-source-exec
pandoc_source_exec.py
finalize
def finalize(doc): """Adds the pgfplots and caption packages to the header-includes if needed. """ if doc.plot_found: pgfplots_inline = pf.MetaInlines(pf.RawInline( r'''% \makeatletter \@ifpackageloaded{pgfplots}{}{\usepackage{pgfplots}} \makeatother \usepgfplotslibrary{groupplots} ''', format='tex')) try: doc.metadata['header-includes'].append(pgfplots_inline) except KeyError: doc.metadata['header-includes'] = pf.MetaList(pgfplots_inline) if doc.caption_found: caption_inline = pf.MetaInlines(pf.RawInline( r'''% \makeatletter \@ifpackageloaded{caption}{}{\usepackage{caption}} \@ifpackageloaded{cleveref}{}{\usepackage{cleveref}} \@ifundefined{codelisting}{% \DeclareCaptionType{codelisting}[Code Listing][List of Code Listings] \crefname{codelisting}{code listing}{code listings} \Crefname{codelisting}{Code Listing}{Code Listings} \captionsetup[codelisting]{position=bottom} }{} \makeatother ''', format='tex')) try: doc.metadata['header-includes'].append(caption_inline) except KeyError: doc.metadata['header-includes'] = pf.MetaList(caption_inline)
python
def finalize(doc): """Adds the pgfplots and caption packages to the header-includes if needed. """ if doc.plot_found: pgfplots_inline = pf.MetaInlines(pf.RawInline( r'''% \makeatletter \@ifpackageloaded{pgfplots}{}{\usepackage{pgfplots}} \makeatother \usepgfplotslibrary{groupplots} ''', format='tex')) try: doc.metadata['header-includes'].append(pgfplots_inline) except KeyError: doc.metadata['header-includes'] = pf.MetaList(pgfplots_inline) if doc.caption_found: caption_inline = pf.MetaInlines(pf.RawInline( r'''% \makeatletter \@ifpackageloaded{caption}{}{\usepackage{caption}} \@ifpackageloaded{cleveref}{}{\usepackage{cleveref}} \@ifundefined{codelisting}{% \DeclareCaptionType{codelisting}[Code Listing][List of Code Listings] \crefname{codelisting}{code listing}{code listings} \Crefname{codelisting}{Code Listing}{Code Listings} \captionsetup[codelisting]{position=bottom} }{} \makeatother ''', format='tex')) try: doc.metadata['header-includes'].append(caption_inline) except KeyError: doc.metadata['header-includes'] = pf.MetaList(caption_inline)
[ "def", "finalize", "(", "doc", ")", ":", "if", "doc", ".", "plot_found", ":", "pgfplots_inline", "=", "pf", ".", "MetaInlines", "(", "pf", ".", "RawInline", "(", "r'''%\n\\makeatletter\n\\@ifpackageloaded{pgfplots}{}{\\usepackage{pgfplots}}\n\\makeatother\n\\usepgfplotslibrary{groupplots}\n'''", ",", "format", "=", "'tex'", ")", ")", "try", ":", "doc", ".", "metadata", "[", "'header-includes'", "]", ".", "append", "(", "pgfplots_inline", ")", "except", "KeyError", ":", "doc", ".", "metadata", "[", "'header-includes'", "]", "=", "pf", ".", "MetaList", "(", "pgfplots_inline", ")", "if", "doc", ".", "caption_found", ":", "caption_inline", "=", "pf", ".", "MetaInlines", "(", "pf", ".", "RawInline", "(", "r'''%\n\\makeatletter\n\\@ifpackageloaded{caption}{}{\\usepackage{caption}}\n\\@ifpackageloaded{cleveref}{}{\\usepackage{cleveref}}\n\\@ifundefined{codelisting}{%\n \\DeclareCaptionType{codelisting}[Code Listing][List of Code Listings]\n \\crefname{codelisting}{code listing}{code listings}\n \\Crefname{codelisting}{Code Listing}{Code Listings}\n \\captionsetup[codelisting]{position=bottom}\n}{}\n\\makeatother\n'''", ",", "format", "=", "'tex'", ")", ")", "try", ":", "doc", ".", "metadata", "[", "'header-includes'", "]", ".", "append", "(", "caption_inline", ")", "except", "KeyError", ":", "doc", ".", "metadata", "[", "'header-includes'", "]", "=", "pf", ".", "MetaList", "(", "caption_inline", ")" ]
Adds the pgfplots and caption packages to the header-includes if needed.
[ "Adds", "the", "pgfplots", "and", "caption", "packages", "to", "the", "header", "-", "includes", "if", "needed", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L409-L442
238,808
s-m-i-t-a/railroad
railroad/rescue.py
rescue
def rescue(f, on_success, on_error=reraise, on_complete=nop): ''' Functional try-except-finally :param function f: guarded function :param function on_succes: called when f is executed without error :param function on_error: called with `error` parameter when f failed :param function on_complete: called as finally block :returns function: call signature is equal f signature ''' def _rescue(*args, **kwargs): try: return on_success(f(*args, **kwargs)) except Exception as e: return on_error(e) finally: on_complete() return _rescue
python
def rescue(f, on_success, on_error=reraise, on_complete=nop): ''' Functional try-except-finally :param function f: guarded function :param function on_succes: called when f is executed without error :param function on_error: called with `error` parameter when f failed :param function on_complete: called as finally block :returns function: call signature is equal f signature ''' def _rescue(*args, **kwargs): try: return on_success(f(*args, **kwargs)) except Exception as e: return on_error(e) finally: on_complete() return _rescue
[ "def", "rescue", "(", "f", ",", "on_success", ",", "on_error", "=", "reraise", ",", "on_complete", "=", "nop", ")", ":", "def", "_rescue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "on_success", "(", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "except", "Exception", "as", "e", ":", "return", "on_error", "(", "e", ")", "finally", ":", "on_complete", "(", ")", "return", "_rescue" ]
Functional try-except-finally :param function f: guarded function :param function on_succes: called when f is executed without error :param function on_error: called with `error` parameter when f failed :param function on_complete: called as finally block :returns function: call signature is equal f signature
[ "Functional", "try", "-", "except", "-", "finally" ]
ddb4afa018b8523b5d8c3a86e55388d1ea0ab37c
https://github.com/s-m-i-t-a/railroad/blob/ddb4afa018b8523b5d8c3a86e55388d1ea0ab37c/railroad/rescue.py#L12-L30
238,809
realestate-com-au/dashmat
dashmat/collector.py
Collector.read_file
def read_file(self, location): """Read in a yaml file and return as a python object""" try: return yaml.load(open(location)) except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error: raise self.BadFileErrorKls("Failed to read yaml", location=location, error_type=error.__class__.__name__, error="{0}{1}".format(error.problem, error.problem_mark))
python
def read_file(self, location): """Read in a yaml file and return as a python object""" try: return yaml.load(open(location)) except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error: raise self.BadFileErrorKls("Failed to read yaml", location=location, error_type=error.__class__.__name__, error="{0}{1}".format(error.problem, error.problem_mark))
[ "def", "read_file", "(", "self", ",", "location", ")", ":", "try", ":", "return", "yaml", ".", "load", "(", "open", "(", "location", ")", ")", "except", "(", "yaml", ".", "parser", ".", "ParserError", ",", "yaml", ".", "scanner", ".", "ScannerError", ")", "as", "error", ":", "raise", "self", ".", "BadFileErrorKls", "(", "\"Failed to read yaml\"", ",", "location", "=", "location", ",", "error_type", "=", "error", ".", "__class__", ".", "__name__", ",", "error", "=", "\"{0}{1}\"", ".", "format", "(", "error", ".", "problem", ",", "error", ".", "problem_mark", ")", ")" ]
Read in a yaml file and return as a python object
[ "Read", "in", "a", "yaml", "file", "and", "return", "as", "a", "python", "object" ]
433886e52698f0ddb9956f087b76041966c3bcd1
https://github.com/realestate-com-au/dashmat/blob/433886e52698f0ddb9956f087b76041966c3bcd1/dashmat/collector.py#L54-L59
238,810
toumorokoshi/jenks
jenks/subcommand/trigger.py
_trigger_job
def _trigger_job(job): """ trigger a job """ if job.api_instance().is_running(): return "{0}, {1} is already running".format(job.host, job.name) else: requests.get(job.api_instance().get_build_triggerurl()) return "triggering {0}, {1}...".format(job.host, job.name)
python
def _trigger_job(job): """ trigger a job """ if job.api_instance().is_running(): return "{0}, {1} is already running".format(job.host, job.name) else: requests.get(job.api_instance().get_build_triggerurl()) return "triggering {0}, {1}...".format(job.host, job.name)
[ "def", "_trigger_job", "(", "job", ")", ":", "if", "job", ".", "api_instance", "(", ")", ".", "is_running", "(", ")", ":", "return", "\"{0}, {1} is already running\"", ".", "format", "(", "job", ".", "host", ",", "job", ".", "name", ")", "else", ":", "requests", ".", "get", "(", "job", ".", "api_instance", "(", ")", ".", "get_build_triggerurl", "(", ")", ")", "return", "\"triggering {0}, {1}...\"", ".", "format", "(", "job", ".", "host", ",", "job", ".", "name", ")" ]
trigger a job
[ "trigger", "a", "job" ]
d3333a7b86ba290b7185aa5b8da75e76a28124f5
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/subcommand/trigger.py#L24-L30
238,811
roboogle/gtkmvc3
gtkmvco/gtkmvc3/observable.py
Observable.observed
def observed(cls, _func): """ Decorate methods to be observable. If they are called on an instance stored in a property, the model will emit before and after notifications. """ def wrapper(*args, **kwargs): self = args[0] assert(isinstance(self, Observable)) self._notify_method_before(self, _func.__name__, args, kwargs) res = _func(*args, **kwargs) self._notify_method_after(self, _func.__name__, res, args, kwargs) return res return wrapper
python
def observed(cls, _func): """ Decorate methods to be observable. If they are called on an instance stored in a property, the model will emit before and after notifications. """ def wrapper(*args, **kwargs): self = args[0] assert(isinstance(self, Observable)) self._notify_method_before(self, _func.__name__, args, kwargs) res = _func(*args, **kwargs) self._notify_method_after(self, _func.__name__, res, args, kwargs) return res return wrapper
[ "def", "observed", "(", "cls", ",", "_func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "assert", "(", "isinstance", "(", "self", ",", "Observable", ")", ")", "self", ".", "_notify_method_before", "(", "self", ",", "_func", ".", "__name__", ",", "args", ",", "kwargs", ")", "res", "=", "_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_notify_method_after", "(", "self", ",", "_func", ".", "__name__", ",", "res", ",", "args", ",", "kwargs", ")", "return", "res", "return", "wrapper" ]
Decorate methods to be observable. If they are called on an instance stored in a property, the model will emit before and after notifications.
[ "Decorate", "methods", "to", "be", "observable", ".", "If", "they", "are", "called", "on", "an", "instance", "stored", "in", "a", "property", "the", "model", "will", "emit", "before", "and", "after", "notifications", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/observable.py#L34-L50
238,812
roboogle/gtkmvc3
gtkmvco/gtkmvc3/observable.py
Signal.emit
def emit(self, arg=None): """Emits the signal, passing the optional argument""" for model,name in self.__get_models__(): model.notify_signal_emit(name, arg)
python
def emit(self, arg=None): """Emits the signal, passing the optional argument""" for model,name in self.__get_models__(): model.notify_signal_emit(name, arg)
[ "def", "emit", "(", "self", ",", "arg", "=", "None", ")", ":", "for", "model", ",", "name", "in", "self", ".", "__get_models__", "(", ")", ":", "model", ".", "notify_signal_emit", "(", "name", ",", "arg", ")" ]
Emits the signal, passing the optional argument
[ "Emits", "the", "signal", "passing", "the", "optional", "argument" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/observable.py#L87-L90
238,813
klmitch/policies
policies/instructions.py
Instructions._linearize
def _linearize(cls, inst_list): """ A generator function which performs linearization of the list of instructions; that is, each instruction which should be executed will be yielded in turn, recursing into ``Instructions`` instances that appear in the list. :param inst_list: A list (or other sequence) of instructions. :returns: An iterator which returns all instructions. """ for inst in inst_list: # Check if we need to recurse if isinstance(inst, Instructions): for sub_inst in cls._linearize(inst.instructions): yield sub_inst else: yield inst
python
def _linearize(cls, inst_list): """ A generator function which performs linearization of the list of instructions; that is, each instruction which should be executed will be yielded in turn, recursing into ``Instructions`` instances that appear in the list. :param inst_list: A list (or other sequence) of instructions. :returns: An iterator which returns all instructions. """ for inst in inst_list: # Check if we need to recurse if isinstance(inst, Instructions): for sub_inst in cls._linearize(inst.instructions): yield sub_inst else: yield inst
[ "def", "_linearize", "(", "cls", ",", "inst_list", ")", ":", "for", "inst", "in", "inst_list", ":", "# Check if we need to recurse", "if", "isinstance", "(", "inst", ",", "Instructions", ")", ":", "for", "sub_inst", "in", "cls", ".", "_linearize", "(", "inst", ".", "instructions", ")", ":", "yield", "sub_inst", "else", ":", "yield", "inst" ]
A generator function which performs linearization of the list of instructions; that is, each instruction which should be executed will be yielded in turn, recursing into ``Instructions`` instances that appear in the list. :param inst_list: A list (or other sequence) of instructions. :returns: An iterator which returns all instructions.
[ "A", "generator", "function", "which", "performs", "linearization", "of", "the", "list", "of", "instructions", ";", "that", "is", "each", "instruction", "which", "should", "be", "executed", "will", "be", "yielded", "in", "turn", "recursing", "into", "Instructions", "instances", "that", "appear", "in", "the", "list", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/instructions.py#L206-L224
238,814
samuel-phan/mssh-copy-id
msshcopyid/__init__.py
SSHCopyId.add_to_known_hosts
def add_to_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Add the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. """ to_add = [] with open(known_hosts) as fh: known_hosts_set = set(line.strip() for line in fh.readlines()) cmd = ['ssh-keyscan'] + [host.hostname for host in hosts] logger.debug('Call: %s', ' '.join(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() for line in stdout.splitlines(): line = line.strip() logger.info('[%s] Add the remote host SSH public key to [%s]...', line.split(' ', 1)[0], known_hosts) if line not in known_hosts_set: known_hosts_set.add(line) to_add.append('{0}\n'.format(line)) if not dry: with open(known_hosts, 'a') as fh: fh.writelines(to_add)
python
def add_to_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Add the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. """ to_add = [] with open(known_hosts) as fh: known_hosts_set = set(line.strip() for line in fh.readlines()) cmd = ['ssh-keyscan'] + [host.hostname for host in hosts] logger.debug('Call: %s', ' '.join(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() for line in stdout.splitlines(): line = line.strip() logger.info('[%s] Add the remote host SSH public key to [%s]...', line.split(' ', 1)[0], known_hosts) if line not in known_hosts_set: known_hosts_set.add(line) to_add.append('{0}\n'.format(line)) if not dry: with open(known_hosts, 'a') as fh: fh.writelines(to_add)
[ "def", "add_to_known_hosts", "(", "self", ",", "hosts", ",", "known_hosts", "=", "DEFAULT_KNOWN_HOSTS", ",", "dry", "=", "False", ")", ":", "to_add", "=", "[", "]", "with", "open", "(", "known_hosts", ")", "as", "fh", ":", "known_hosts_set", "=", "set", "(", "line", ".", "strip", "(", ")", "for", "line", "in", "fh", ".", "readlines", "(", ")", ")", "cmd", "=", "[", "'ssh-keyscan'", "]", "+", "[", "host", ".", "hostname", "for", "host", "in", "hosts", "]", "logger", ".", "debug", "(", "'Call: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "for", "line", "in", "stdout", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "logger", ".", "info", "(", "'[%s] Add the remote host SSH public key to [%s]...'", ",", "line", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", ",", "known_hosts", ")", "if", "line", "not", "in", "known_hosts_set", ":", "known_hosts_set", ".", "add", "(", "line", ")", "to_add", ".", "append", "(", "'{0}\\n'", ".", "format", "(", "line", ")", ")", "if", "not", "dry", ":", "with", "open", "(", "known_hosts", ",", "'a'", ")", "as", "fh", ":", "fh", ".", "writelines", "(", "to_add", ")" ]
Add the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run.
[ "Add", "the", "remote", "host", "SSH", "public", "key", "to", "the", "known_hosts", "file", "." ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/msshcopyid/__init__.py#L46-L71
238,815
samuel-phan/mssh-copy-id
msshcopyid/__init__.py
SSHCopyId.remove_from_known_hosts
def remove_from_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Remove the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. """ for host in hosts: logger.info('[%s] Removing the remote host SSH public key from [%s]...', host.hostname, known_hosts) cmd = ['ssh-keygen', '-f', known_hosts, '-R', host.hostname] logger.debug('Call: %s', ' '.join(cmd)) if not dry: try: subprocess.check_call(cmd) except subprocess.CalledProcessError as ex: logger.error(format_error(format_exception(ex)))
python
def remove_from_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Remove the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. """ for host in hosts: logger.info('[%s] Removing the remote host SSH public key from [%s]...', host.hostname, known_hosts) cmd = ['ssh-keygen', '-f', known_hosts, '-R', host.hostname] logger.debug('Call: %s', ' '.join(cmd)) if not dry: try: subprocess.check_call(cmd) except subprocess.CalledProcessError as ex: logger.error(format_error(format_exception(ex)))
[ "def", "remove_from_known_hosts", "(", "self", ",", "hosts", ",", "known_hosts", "=", "DEFAULT_KNOWN_HOSTS", ",", "dry", "=", "False", ")", ":", "for", "host", "in", "hosts", ":", "logger", ".", "info", "(", "'[%s] Removing the remote host SSH public key from [%s]...'", ",", "host", ".", "hostname", ",", "known_hosts", ")", "cmd", "=", "[", "'ssh-keygen'", ",", "'-f'", ",", "known_hosts", ",", "'-R'", ",", "host", ".", "hostname", "]", "logger", ".", "debug", "(", "'Call: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "if", "not", "dry", ":", "try", ":", "subprocess", ".", "check_call", "(", "cmd", ")", "except", "subprocess", ".", "CalledProcessError", "as", "ex", ":", "logger", ".", "error", "(", "format_error", "(", "format_exception", "(", "ex", ")", ")", ")" ]
Remove the remote host SSH public key to the `known_hosts` file. :param hosts: the list of the remote `Host` objects. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run.
[ "Remove", "the", "remote", "host", "SSH", "public", "key", "to", "the", "known_hosts", "file", "." ]
59c50eabb74c4e0eeb729266df57c285e6661b0b
https://github.com/samuel-phan/mssh-copy-id/blob/59c50eabb74c4e0eeb729266df57c285e6661b0b/msshcopyid/__init__.py#L73-L89
238,816
pipermerriam/ethereum-client-utils
eth_client_utils/client.py
BaseClient.process_requests
def process_requests(self): """ Loop that runs in a thread to process requests synchronously. """ while True: id, args, kwargs = self.request_queue.get() try: response = self._make_request(*args, **kwargs) except Exception as e: response = e self.results[id] = response
python
def process_requests(self): """ Loop that runs in a thread to process requests synchronously. """ while True: id, args, kwargs = self.request_queue.get() try: response = self._make_request(*args, **kwargs) except Exception as e: response = e self.results[id] = response
[ "def", "process_requests", "(", "self", ")", ":", "while", "True", ":", "id", ",", "args", ",", "kwargs", "=", "self", ".", "request_queue", ".", "get", "(", ")", "try", ":", "response", "=", "self", ".", "_make_request", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "response", "=", "e", "self", ".", "results", "[", "id", "]", "=", "response" ]
Loop that runs in a thread to process requests synchronously.
[ "Loop", "that", "runs", "in", "a", "thread", "to", "process", "requests", "synchronously", "." ]
34d0976305a262200a1159b2f336b69ce4f02d70
https://github.com/pipermerriam/ethereum-client-utils/blob/34d0976305a262200a1159b2f336b69ce4f02d70/eth_client_utils/client.py#L30-L40
238,817
pipermerriam/ethereum-client-utils
eth_client_utils/client.py
JSONRPCBaseClient.default_from_address
def default_from_address(self): """ Cache the coinbase address so that we don't make two requests for every single transaction. """ if self._coinbase_cache_til is not None: if time.time - self._coinbase_cache_til > 30: self._coinbase_cache_til = None self._coinbase_cache = None if self._coinbase_cache is None: self._coinbase_cache = self.get_coinbase() return self._coinbase_cache
python
def default_from_address(self): """ Cache the coinbase address so that we don't make two requests for every single transaction. """ if self._coinbase_cache_til is not None: if time.time - self._coinbase_cache_til > 30: self._coinbase_cache_til = None self._coinbase_cache = None if self._coinbase_cache is None: self._coinbase_cache = self.get_coinbase() return self._coinbase_cache
[ "def", "default_from_address", "(", "self", ")", ":", "if", "self", ".", "_coinbase_cache_til", "is", "not", "None", ":", "if", "time", ".", "time", "-", "self", ".", "_coinbase_cache_til", ">", "30", ":", "self", ".", "_coinbase_cache_til", "=", "None", "self", ".", "_coinbase_cache", "=", "None", "if", "self", ".", "_coinbase_cache", "is", "None", ":", "self", ".", "_coinbase_cache", "=", "self", ".", "get_coinbase", "(", ")", "return", "self", ".", "_coinbase_cache" ]
Cache the coinbase address so that we don't make two requests for every single transaction.
[ "Cache", "the", "coinbase", "address", "so", "that", "we", "don", "t", "make", "two", "requests", "for", "every", "single", "transaction", "." ]
34d0976305a262200a1159b2f336b69ce4f02d70
https://github.com/pipermerriam/ethereum-client-utils/blob/34d0976305a262200a1159b2f336b69ce4f02d70/eth_client_utils/client.py#L72-L85
238,818
rosenbrockc/ci
pyci/server.py
Server.find_pulls
def find_pulls(self, testpulls=None): """Finds a list of new pull requests that need to be processed. :arg testpulls: a list of tserver.FakePull instances so we can test the code functionality without making live requests to github. """ #We check all the repositories installed for new (open) pull requests. #If any exist, we check the pull request number against our archive to #see if we have to do anything for it. result = {} for lname, repo in self.repositories.items(): if lname not in self.archive: raise ValueError("Trying to find pull requests for a repository " "that hasn't been installed. Use server.install().") if self.runnable is not None and lname not in self.runnable: #We just ignore this repository completely and don't even bother #performing a live check on github. continue pulls = testpulls if testpulls is not None else repo.repo.get_pulls("open") result[lname] = [] for pull in pulls: newpull = True if pull.snumber in self.archive[lname]: #Check the status of that pull request processing. If it was #successful, we just ignore this open pull request; it is #obviously waiting to be merged in. if self.archive[lname][pull.snumber]["completed"] == True: newpull = False if newpull: #Add the pull request to the list that needs to be processed. #We don't add the request to the archive yet because the #processing step hasn't happened yet. result[lname].append(PullRequest(self, repo, pull, testpulls is not None)) return result
python
def find_pulls(self, testpulls=None): """Finds a list of new pull requests that need to be processed. :arg testpulls: a list of tserver.FakePull instances so we can test the code functionality without making live requests to github. """ #We check all the repositories installed for new (open) pull requests. #If any exist, we check the pull request number against our archive to #see if we have to do anything for it. result = {} for lname, repo in self.repositories.items(): if lname not in self.archive: raise ValueError("Trying to find pull requests for a repository " "that hasn't been installed. Use server.install().") if self.runnable is not None and lname not in self.runnable: #We just ignore this repository completely and don't even bother #performing a live check on github. continue pulls = testpulls if testpulls is not None else repo.repo.get_pulls("open") result[lname] = [] for pull in pulls: newpull = True if pull.snumber in self.archive[lname]: #Check the status of that pull request processing. If it was #successful, we just ignore this open pull request; it is #obviously waiting to be merged in. if self.archive[lname][pull.snumber]["completed"] == True: newpull = False if newpull: #Add the pull request to the list that needs to be processed. #We don't add the request to the archive yet because the #processing step hasn't happened yet. result[lname].append(PullRequest(self, repo, pull, testpulls is not None)) return result
[ "def", "find_pulls", "(", "self", ",", "testpulls", "=", "None", ")", ":", "#We check all the repositories installed for new (open) pull requests.", "#If any exist, we check the pull request number against our archive to", "#see if we have to do anything for it.", "result", "=", "{", "}", "for", "lname", ",", "repo", "in", "self", ".", "repositories", ".", "items", "(", ")", ":", "if", "lname", "not", "in", "self", ".", "archive", ":", "raise", "ValueError", "(", "\"Trying to find pull requests for a repository \"", "\"that hasn't been installed. Use server.install().\"", ")", "if", "self", ".", "runnable", "is", "not", "None", "and", "lname", "not", "in", "self", ".", "runnable", ":", "#We just ignore this repository completely and don't even bother", "#performing a live check on github.", "continue", "pulls", "=", "testpulls", "if", "testpulls", "is", "not", "None", "else", "repo", ".", "repo", ".", "get_pulls", "(", "\"open\"", ")", "result", "[", "lname", "]", "=", "[", "]", "for", "pull", "in", "pulls", ":", "newpull", "=", "True", "if", "pull", ".", "snumber", "in", "self", ".", "archive", "[", "lname", "]", ":", "#Check the status of that pull request processing. If it was", "#successful, we just ignore this open pull request; it is", "#obviously waiting to be merged in.", "if", "self", ".", "archive", "[", "lname", "]", "[", "pull", ".", "snumber", "]", "[", "\"completed\"", "]", "==", "True", ":", "newpull", "=", "False", "if", "newpull", ":", "#Add the pull request to the list that needs to be processed.", "#We don't add the request to the archive yet because the", "#processing step hasn't happened yet.", "result", "[", "lname", "]", ".", "append", "(", "PullRequest", "(", "self", ",", "repo", ",", "pull", ",", "testpulls", "is", "not", "None", ")", ")", "return", "result" ]
Finds a list of new pull requests that need to be processed. :arg testpulls: a list of tserver.FakePull instances so we can test the code functionality without making live requests to github.
[ "Finds", "a", "list", "of", "new", "pull", "requests", "that", "need", "to", "be", "processed", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L163-L199
238,819
rosenbrockc/ci
pyci/server.py
Server._save_archive
def _save_archive(self): """Saves the JSON archive of processed pull requests. """ import json from utility import json_serial with open(self.archpath, 'w') as f: json.dump(self.archive, f, default=json_serial)
python
def _save_archive(self): """Saves the JSON archive of processed pull requests. """ import json from utility import json_serial with open(self.archpath, 'w') as f: json.dump(self.archive, f, default=json_serial)
[ "def", "_save_archive", "(", "self", ")", ":", "import", "json", "from", "utility", "import", "json_serial", "with", "open", "(", "self", ".", "archpath", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "archive", ",", "f", ",", "default", "=", "json_serial", ")" ]
Saves the JSON archive of processed pull requests.
[ "Saves", "the", "JSON", "archive", "of", "processed", "pull", "requests", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L208-L214
238,820
rosenbrockc/ci
pyci/server.py
Server._get_repos
def _get_repos(self): """Gets a list of all the installed repositories in this server. """ result = {} for xmlpath in self.installed: repo = RepositorySettings(self, xmlpath) result[repo.name.lower()] = repo return result
python
def _get_repos(self): """Gets a list of all the installed repositories in this server. """ result = {} for xmlpath in self.installed: repo = RepositorySettings(self, xmlpath) result[repo.name.lower()] = repo return result
[ "def", "_get_repos", "(", "self", ")", ":", "result", "=", "{", "}", "for", "xmlpath", "in", "self", ".", "installed", ":", "repo", "=", "RepositorySettings", "(", "self", ",", "xmlpath", ")", "result", "[", "repo", ".", "name", ".", "lower", "(", ")", "]", "=", "repo", "return", "result" ]
Gets a list of all the installed repositories in this server.
[ "Gets", "a", "list", "of", "all", "the", "installed", "repositories", "in", "this", "server", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L216-L224
238,821
rosenbrockc/ci
pyci/server.py
Server._get_installed
def _get_installed(self): """Gets a list of the file paths to repo settings files that are being monitored by the CI server. """ from utility import get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the script's database that tracks #the user's interactions with it. fulldata = get_json(self.instpath, {}) if "installed" in fulldata: return fulldata["installed"] else: return []
python
def _get_installed(self): """Gets a list of the file paths to repo settings files that are being monitored by the CI server. """ from utility import get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the script's database that tracks #the user's interactions with it. fulldata = get_json(self.instpath, {}) if "installed" in fulldata: return fulldata["installed"] else: return []
[ "def", "_get_installed", "(", "self", ")", ":", "from", "utility", "import", "get_json", "#This is a little tricky because the data file doesn't just have a list", "#of installed servers. It also manages the script's database that tracks", "#the user's interactions with it.", "fulldata", "=", "get_json", "(", "self", ".", "instpath", ",", "{", "}", ")", "if", "\"installed\"", "in", "fulldata", ":", "return", "fulldata", "[", "\"installed\"", "]", "else", ":", "return", "[", "]" ]
Gets a list of the file paths to repo settings files that are being monitored by the CI server.
[ "Gets", "a", "list", "of", "the", "file", "paths", "to", "repo", "settings", "files", "that", "are", "being", "monitored", "by", "the", "CI", "server", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L226-L238
238,822
rosenbrockc/ci
pyci/server.py
Server.uninstall
def uninstall(self, xmlpath): """Uninstalls the repository with the specified XML path from the server. """ from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if fullpath in self.installed: repo = RepositorySettings(self, fullpath) if repo.name.lower() in self.repositories: del self.repositories[repo.name.lower()] if repo.name.lower() in self.archive: del self.archive[repo.name.lower()] self._save_archive() self.installed.remove(fullpath) self._save_installed() else: warn("The repository at {} was not installed to begin with.".format(fullpath))
python
def uninstall(self, xmlpath): """Uninstalls the repository with the specified XML path from the server. """ from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if fullpath in self.installed: repo = RepositorySettings(self, fullpath) if repo.name.lower() in self.repositories: del self.repositories[repo.name.lower()] if repo.name.lower() in self.archive: del self.archive[repo.name.lower()] self._save_archive() self.installed.remove(fullpath) self._save_installed() else: warn("The repository at {} was not installed to begin with.".format(fullpath))
[ "def", "uninstall", "(", "self", ",", "xmlpath", ")", ":", "from", "os", "import", "path", "fullpath", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "xmlpath", ")", ")", "if", "fullpath", "in", "self", ".", "installed", ":", "repo", "=", "RepositorySettings", "(", "self", ",", "fullpath", ")", "if", "repo", ".", "name", ".", "lower", "(", ")", "in", "self", ".", "repositories", ":", "del", "self", ".", "repositories", "[", "repo", ".", "name", ".", "lower", "(", ")", "]", "if", "repo", ".", "name", ".", "lower", "(", ")", "in", "self", ".", "archive", ":", "del", "self", ".", "archive", "[", "repo", ".", "name", ".", "lower", "(", ")", "]", "self", ".", "_save_archive", "(", ")", "self", ".", "installed", ".", "remove", "(", "fullpath", ")", "self", ".", "_save_installed", "(", ")", "else", ":", "warn", "(", "\"The repository at {} was not installed to begin with.\"", ".", "format", "(", "fullpath", ")", ")" ]
Uninstalls the repository with the specified XML path from the server.
[ "Uninstalls", "the", "repository", "with", "the", "specified", "XML", "path", "from", "the", "server", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L240-L255
238,823
rosenbrockc/ci
pyci/server.py
Server.install
def install(self, xmlpath): """Installs the repository at the specified XML path as an additional repo to monitor pull requests for. """ #Before we can install it, we need to make sure that none of the existing #installed paths point to the same repo. from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if path.isfile(fullpath): repo = RepositorySettings(self, fullpath) if repo.name.lower() not in self.repositories: self.installed.append(fullpath) self._save_installed() self.archive[repo.name.lower()] = {} self._save_archive() self.repositories[repo.name.lower()] = repo else: warn("The file {} does not exist; install aborted.".format(fullpath))
python
def install(self, xmlpath): """Installs the repository at the specified XML path as an additional repo to monitor pull requests for. """ #Before we can install it, we need to make sure that none of the existing #installed paths point to the same repo. from os import path fullpath = path.abspath(path.expanduser(xmlpath)) if path.isfile(fullpath): repo = RepositorySettings(self, fullpath) if repo.name.lower() not in self.repositories: self.installed.append(fullpath) self._save_installed() self.archive[repo.name.lower()] = {} self._save_archive() self.repositories[repo.name.lower()] = repo else: warn("The file {} does not exist; install aborted.".format(fullpath))
[ "def", "install", "(", "self", ",", "xmlpath", ")", ":", "#Before we can install it, we need to make sure that none of the existing", "#installed paths point to the same repo.", "from", "os", "import", "path", "fullpath", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "xmlpath", ")", ")", "if", "path", ".", "isfile", "(", "fullpath", ")", ":", "repo", "=", "RepositorySettings", "(", "self", ",", "fullpath", ")", "if", "repo", ".", "name", ".", "lower", "(", ")", "not", "in", "self", ".", "repositories", ":", "self", ".", "installed", ".", "append", "(", "fullpath", ")", "self", ".", "_save_installed", "(", ")", "self", ".", "archive", "[", "repo", ".", "name", ".", "lower", "(", ")", "]", "=", "{", "}", "self", ".", "_save_archive", "(", ")", "self", ".", "repositories", "[", "repo", ".", "name", ".", "lower", "(", ")", "]", "=", "repo", "else", ":", "warn", "(", "\"The file {} does not exist; install aborted.\"", ".", "format", "(", "fullpath", ")", ")" ]
Installs the repository at the specified XML path as an additional repo to monitor pull requests for.
[ "Installs", "the", "repository", "at", "the", "specified", "XML", "path", "as", "an", "additional", "repo", "to", "monitor", "pull", "requests", "for", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L257-L275
238,824
rosenbrockc/ci
pyci/server.py
Server._save_installed
def _save_installed(self): """Saves the list of installed repo XML settings files.""" import json from utility import json_serial, get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the script's database that tracks #the user's interactions with it. fulldata = get_json(self.instpath, {}) fulldata["installed"] = self.installed with open(self.instpath, 'w') as f: json.dump(fulldata, f, default=json_serial)
python
def _save_installed(self): """Saves the list of installed repo XML settings files.""" import json from utility import json_serial, get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the script's database that tracks #the user's interactions with it. fulldata = get_json(self.instpath, {}) fulldata["installed"] = self.installed with open(self.instpath, 'w') as f: json.dump(fulldata, f, default=json_serial)
[ "def", "_save_installed", "(", "self", ")", ":", "import", "json", "from", "utility", "import", "json_serial", ",", "get_json", "#This is a little tricky because the data file doesn't just have a list", "#of installed servers. It also manages the script's database that tracks", "#the user's interactions with it.", "fulldata", "=", "get_json", "(", "self", ".", "instpath", ",", "{", "}", ")", "fulldata", "[", "\"installed\"", "]", "=", "self", ".", "installed", "with", "open", "(", "self", ".", "instpath", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "fulldata", ",", "f", ",", "default", "=", "json_serial", ")" ]
Saves the list of installed repo XML settings files.
[ "Saves", "the", "list", "of", "installed", "repo", "XML", "settings", "files", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L277-L287
238,825
rosenbrockc/ci
pyci/server.py
PullRequest.init
def init(self, archive): """Creates the repo folder locally, copies the static files and folders available locally, initalizes the repo with git so it has the correct remote origin and is ready to sync. :arg staging: the full path to the directory to stage the unit tests in. """ from os import makedirs, path, chdir, system, getcwd self.repodir = path.abspath(path.expanduser(self.repo.staging)) if ("stage" in archive and path.isdir(archive["stage"]) and self.repodir != archive["stage"] and archive["stage"] is not None): #We have a previous attempt in a different staging directory to clean. from shutil import rmtree rmtree(archive["stage"]) if not path.isdir(self.repodir): makedirs(self.repodir) #Copy across all the static files so that we don't have to download them #again and chew up the bandwidth. We don't have to copy files that already #exist in the local repo. self.repo.static.copy(self.repodir) cwd = getcwd() chdir(self.repodir) if not self._is_gitted(): #Next we need to initialize the git repo, then add all the static files #and folders to be tracked so that when we pull from origin master they #can be merged into the repo without re-downloading them. system("git init") if not self.testmode: system("git remote add origin {}.git".format(self.repo.repo.html_url)) for file in self.repo.static.files: #Here the 2:: removes the ./ specifying the path relative to the git #repository root. It is added by convention in the config files. system("git add {}".format(file["target"][2::])) for folder in self.repo.static.folders: system("git add {}".format(file["target"][2::])) #Now sync with the master branch so that we get everything else that isn't #static. Also, fetch the changes from the pull request head so that we #can merge them into a new branch for unit testing. if not self.testmode: system("git pull origin master") #Even though we have initialized the repo before, we still need to fetch the #pull request we are wanting to merge in. if not self.testmode: system("git fetch origin pull/{0}/head:testing_{0}".format(self.pull.number)) system("git checkout testing_{}".format(pull.number)) #The local repo now has the pull request's proposed changes and is ready #to be unit tested. chdir(cwd)
python
def init(self, archive): """Creates the repo folder locally, copies the static files and folders available locally, initalizes the repo with git so it has the correct remote origin and is ready to sync. :arg staging: the full path to the directory to stage the unit tests in. """ from os import makedirs, path, chdir, system, getcwd self.repodir = path.abspath(path.expanduser(self.repo.staging)) if ("stage" in archive and path.isdir(archive["stage"]) and self.repodir != archive["stage"] and archive["stage"] is not None): #We have a previous attempt in a different staging directory to clean. from shutil import rmtree rmtree(archive["stage"]) if not path.isdir(self.repodir): makedirs(self.repodir) #Copy across all the static files so that we don't have to download them #again and chew up the bandwidth. We don't have to copy files that already #exist in the local repo. self.repo.static.copy(self.repodir) cwd = getcwd() chdir(self.repodir) if not self._is_gitted(): #Next we need to initialize the git repo, then add all the static files #and folders to be tracked so that when we pull from origin master they #can be merged into the repo without re-downloading them. system("git init") if not self.testmode: system("git remote add origin {}.git".format(self.repo.repo.html_url)) for file in self.repo.static.files: #Here the 2:: removes the ./ specifying the path relative to the git #repository root. It is added by convention in the config files. system("git add {}".format(file["target"][2::])) for folder in self.repo.static.folders: system("git add {}".format(file["target"][2::])) #Now sync with the master branch so that we get everything else that isn't #static. Also, fetch the changes from the pull request head so that we #can merge them into a new branch for unit testing. if not self.testmode: system("git pull origin master") #Even though we have initialized the repo before, we still need to fetch the #pull request we are wanting to merge in. if not self.testmode: system("git fetch origin pull/{0}/head:testing_{0}".format(self.pull.number)) system("git checkout testing_{}".format(pull.number)) #The local repo now has the pull request's proposed changes and is ready #to be unit tested. chdir(cwd)
[ "def", "init", "(", "self", ",", "archive", ")", ":", "from", "os", "import", "makedirs", ",", "path", ",", "chdir", ",", "system", ",", "getcwd", "self", ".", "repodir", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "self", ".", "repo", ".", "staging", ")", ")", "if", "(", "\"stage\"", "in", "archive", "and", "path", ".", "isdir", "(", "archive", "[", "\"stage\"", "]", ")", "and", "self", ".", "repodir", "!=", "archive", "[", "\"stage\"", "]", "and", "archive", "[", "\"stage\"", "]", "is", "not", "None", ")", ":", "#We have a previous attempt in a different staging directory to clean.", "from", "shutil", "import", "rmtree", "rmtree", "(", "archive", "[", "\"stage\"", "]", ")", "if", "not", "path", ".", "isdir", "(", "self", ".", "repodir", ")", ":", "makedirs", "(", "self", ".", "repodir", ")", "#Copy across all the static files so that we don't have to download them", "#again and chew up the bandwidth. We don't have to copy files that already", "#exist in the local repo.", "self", ".", "repo", ".", "static", ".", "copy", "(", "self", ".", "repodir", ")", "cwd", "=", "getcwd", "(", ")", "chdir", "(", "self", ".", "repodir", ")", "if", "not", "self", ".", "_is_gitted", "(", ")", ":", "#Next we need to initialize the git repo, then add all the static files", "#and folders to be tracked so that when we pull from origin master they", "#can be merged into the repo without re-downloading them.", "system", "(", "\"git init\"", ")", "if", "not", "self", ".", "testmode", ":", "system", "(", "\"git remote add origin {}.git\"", ".", "format", "(", "self", ".", "repo", ".", "repo", ".", "html_url", ")", ")", "for", "file", "in", "self", ".", "repo", ".", "static", ".", "files", ":", "#Here the 2:: removes the ./ specifying the path relative to the git", "#repository root. It is added by convention in the config files.", "system", "(", "\"git add {}\"", ".", "format", "(", "file", "[", "\"target\"", "]", "[", "2", ":", ":", "]", ")", ")", "for", "folder", "in", "self", ".", "repo", ".", "static", ".", "folders", ":", "system", "(", "\"git add {}\"", ".", "format", "(", "file", "[", "\"target\"", "]", "[", "2", ":", ":", "]", ")", ")", "#Now sync with the master branch so that we get everything else that isn't", "#static. Also, fetch the changes from the pull request head so that we", "#can merge them into a new branch for unit testing.", "if", "not", "self", ".", "testmode", ":", "system", "(", "\"git pull origin master\"", ")", "#Even though we have initialized the repo before, we still need to fetch the", "#pull request we are wanting to merge in.", "if", "not", "self", ".", "testmode", ":", "system", "(", "\"git fetch origin pull/{0}/head:testing_{0}\"", ".", "format", "(", "self", ".", "pull", ".", "number", ")", ")", "system", "(", "\"git checkout testing_{}\"", ".", "format", "(", "pull", ".", "number", ")", ")", "#The local repo now has the pull request's proposed changes and is ready", "#to be unit tested.", "chdir", "(", "cwd", ")" ]
Creates the repo folder locally, copies the static files and folders available locally, initalizes the repo with git so it has the correct remote origin and is ready to sync. :arg staging: the full path to the directory to stage the unit tests in.
[ "Creates", "the", "repo", "folder", "locally", "copies", "the", "static", "files", "and", "folders", "available", "locally", "initalizes", "the", "repo", "with", "git", "so", "it", "has", "the", "correct", "remote", "origin", "and", "is", "ready", "to", "sync", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L346-L401
238,826
rosenbrockc/ci
pyci/server.py
PullRequest._fields_common
def _fields_common(self): """Returns a dictionary of fields and values that are common to all events for which fields dictionaries are created. """ result = {} if not self.testmode: result["__reponame__"] = self.repo.repo.full_name result["__repodesc__"] = self.repo.repo.description result["__repourl__"] = self.repo.repo.html_url result["__repodir__"] = self.repodir if self.organization is not None: owner = self.repo.organization else: owner = self.repo.user result["__username__"] = owner.name result["__userurl__"] = owner.html_url result["__useravatar__"] = owner.avatar_url result["__useremail__"] = owner.email return result
python
def _fields_common(self): """Returns a dictionary of fields and values that are common to all events for which fields dictionaries are created. """ result = {} if not self.testmode: result["__reponame__"] = self.repo.repo.full_name result["__repodesc__"] = self.repo.repo.description result["__repourl__"] = self.repo.repo.html_url result["__repodir__"] = self.repodir if self.organization is not None: owner = self.repo.organization else: owner = self.repo.user result["__username__"] = owner.name result["__userurl__"] = owner.html_url result["__useravatar__"] = owner.avatar_url result["__useremail__"] = owner.email return result
[ "def", "_fields_common", "(", "self", ")", ":", "result", "=", "{", "}", "if", "not", "self", ".", "testmode", ":", "result", "[", "\"__reponame__\"", "]", "=", "self", ".", "repo", ".", "repo", ".", "full_name", "result", "[", "\"__repodesc__\"", "]", "=", "self", ".", "repo", ".", "repo", ".", "description", "result", "[", "\"__repourl__\"", "]", "=", "self", ".", "repo", ".", "repo", ".", "html_url", "result", "[", "\"__repodir__\"", "]", "=", "self", ".", "repodir", "if", "self", ".", "organization", "is", "not", "None", ":", "owner", "=", "self", ".", "repo", ".", "organization", "else", ":", "owner", "=", "self", ".", "repo", ".", "user", "result", "[", "\"__username__\"", "]", "=", "owner", ".", "name", "result", "[", "\"__userurl__\"", "]", "=", "owner", ".", "html_url", "result", "[", "\"__useravatar__\"", "]", "=", "owner", ".", "avatar_url", "result", "[", "\"__useremail__\"", "]", "=", "owner", ".", "email", "return", "result" ]
Returns a dictionary of fields and values that are common to all events for which fields dictionaries are created.
[ "Returns", "a", "dictionary", "of", "fields", "and", "values", "that", "are", "common", "to", "all", "events", "for", "which", "fields", "dictionaries", "are", "created", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L509-L530
238,827
rosenbrockc/ci
pyci/server.py
PullRequest.wiki
def wiki(self): """Returns the wiki markup describing the details of the github pull request as well as a link to the details on github. """ date = self.pull.created_at.strftime("%m/%d/%Y %H:%M") return "{} {} ({} [{} github])\n".format(self.pull.avatar_url, self.pull.body, date, self.pull.html_url)
python
def wiki(self): """Returns the wiki markup describing the details of the github pull request as well as a link to the details on github. """ date = self.pull.created_at.strftime("%m/%d/%Y %H:%M") return "{} {} ({} [{} github])\n".format(self.pull.avatar_url, self.pull.body, date, self.pull.html_url)
[ "def", "wiki", "(", "self", ")", ":", "date", "=", "self", ".", "pull", ".", "created_at", ".", "strftime", "(", "\"%m/%d/%Y %H:%M\"", ")", "return", "\"{} {} ({} [{} github])\\n\"", ".", "format", "(", "self", ".", "pull", ".", "avatar_url", ",", "self", ".", "pull", ".", "body", ",", "date", ",", "self", ".", "pull", ".", "html_url", ")" ]
Returns the wiki markup describing the details of the github pull request as well as a link to the details on github.
[ "Returns", "the", "wiki", "markup", "describing", "the", "details", "of", "the", "github", "pull", "request", "as", "well", "as", "a", "link", "to", "the", "details", "on", "github", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L532-L538
238,828
rosenbrockc/ci
pyci/server.py
PullRequest.fields_general
def fields_general(self, event): """Appends any additional fields to the common ones and returns the fields dictionary. """ result = self._fields_common() basic = { "__test_html__": self.repo.testing.html(False), "__test_text__": self.repo.testing.text(False)} full = { "__test_html__": self.repo.testing.html(), "__test_text__": self.repo.testing.text()} if event in ["finish", "success"]: full["__percent__"] = "{0:.2%}".format(self.percent) full["__status__"] = self.message extra = { "start": basic, "error": basic, "finish": full, "success": full, "timeout": basic } if event in extra: result.update(extra[event]) return result
python
def fields_general(self, event): """Appends any additional fields to the common ones and returns the fields dictionary. """ result = self._fields_common() basic = { "__test_html__": self.repo.testing.html(False), "__test_text__": self.repo.testing.text(False)} full = { "__test_html__": self.repo.testing.html(), "__test_text__": self.repo.testing.text()} if event in ["finish", "success"]: full["__percent__"] = "{0:.2%}".format(self.percent) full["__status__"] = self.message extra = { "start": basic, "error": basic, "finish": full, "success": full, "timeout": basic } if event in extra: result.update(extra[event]) return result
[ "def", "fields_general", "(", "self", ",", "event", ")", ":", "result", "=", "self", ".", "_fields_common", "(", ")", "basic", "=", "{", "\"__test_html__\"", ":", "self", ".", "repo", ".", "testing", ".", "html", "(", "False", ")", ",", "\"__test_text__\"", ":", "self", ".", "repo", ".", "testing", ".", "text", "(", "False", ")", "}", "full", "=", "{", "\"__test_html__\"", ":", "self", ".", "repo", ".", "testing", ".", "html", "(", ")", ",", "\"__test_text__\"", ":", "self", ".", "repo", ".", "testing", ".", "text", "(", ")", "}", "if", "event", "in", "[", "\"finish\"", ",", "\"success\"", "]", ":", "full", "[", "\"__percent__\"", "]", "=", "\"{0:.2%}\"", ".", "format", "(", "self", ".", "percent", ")", "full", "[", "\"__status__\"", "]", "=", "self", ".", "message", "extra", "=", "{", "\"start\"", ":", "basic", ",", "\"error\"", ":", "basic", ",", "\"finish\"", ":", "full", ",", "\"success\"", ":", "full", ",", "\"timeout\"", ":", "basic", "}", "if", "event", "in", "extra", ":", "result", ".", "update", "(", "extra", "[", "event", "]", ")", "return", "result" ]
Appends any additional fields to the common ones and returns the fields dictionary.
[ "Appends", "any", "additional", "fields", "to", "the", "common", "ones", "and", "returns", "the", "fields", "dictionary", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L540-L565
238,829
rosenbrockc/ci
pyci/server.py
Wiki._get_site
def _get_site(self): """Returns the mwclient.Site for accessing and editing the wiki pages. """ import mwclient parts = self.server.settings.wiki.replace("http", "").replace("://", "").split("/") self.url = parts[0] if len(parts) > 1 and parts[1].strip() != "": self.relpath = '/' + '/'.join(parts[1:len(parts)]) #The API expects us to have a trailing forward-slash. if self.relpath[-1] != "/": self.relpath += "/" if not self.testmode: self.site = mwclient.Site(self.url, path=self.relpath) else: if not self.testmode: self.site = mwclient.Site(self.url)
python
def _get_site(self): """Returns the mwclient.Site for accessing and editing the wiki pages. """ import mwclient parts = self.server.settings.wiki.replace("http", "").replace("://", "").split("/") self.url = parts[0] if len(parts) > 1 and parts[1].strip() != "": self.relpath = '/' + '/'.join(parts[1:len(parts)]) #The API expects us to have a trailing forward-slash. if self.relpath[-1] != "/": self.relpath += "/" if not self.testmode: self.site = mwclient.Site(self.url, path=self.relpath) else: if not self.testmode: self.site = mwclient.Site(self.url)
[ "def", "_get_site", "(", "self", ")", ":", "import", "mwclient", "parts", "=", "self", ".", "server", ".", "settings", ".", "wiki", ".", "replace", "(", "\"http\"", ",", "\"\"", ")", ".", "replace", "(", "\"://\"", ",", "\"\"", ")", ".", "split", "(", "\"/\"", ")", "self", ".", "url", "=", "parts", "[", "0", "]", "if", "len", "(", "parts", ")", ">", "1", "and", "parts", "[", "1", "]", ".", "strip", "(", ")", "!=", "\"\"", ":", "self", ".", "relpath", "=", "'/'", "+", "'/'", ".", "join", "(", "parts", "[", "1", ":", "len", "(", "parts", ")", "]", ")", "#The API expects us to have a trailing forward-slash.", "if", "self", ".", "relpath", "[", "-", "1", "]", "!=", "\"/\"", ":", "self", ".", "relpath", "+=", "\"/\"", "if", "not", "self", ".", "testmode", ":", "self", ".", "site", "=", "mwclient", ".", "Site", "(", "self", ".", "url", ",", "path", "=", "self", ".", "relpath", ")", "else", ":", "if", "not", "self", ".", "testmode", ":", "self", ".", "site", "=", "mwclient", ".", "Site", "(", "self", ".", "url", ")" ]
Returns the mwclient.Site for accessing and editing the wiki pages.
[ "Returns", "the", "mwclient", ".", "Site", "for", "accessing", "and", "editing", "the", "wiki", "pages", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L607-L622
238,830
rosenbrockc/ci
pyci/server.py
Wiki._site_login
def _site_login(self, repo): """Logs the user specified in the repo into the wiki. :arg repo: an instance of config.RepositorySettings with wiki credentials. """ try: if not self.testmode: self.site.login(repo.wiki["user"], repo.wiki["password"]) except LoginError as e: print(e[1]['result']) self.basepage = repo.wiki["basepage"]
python
def _site_login(self, repo): """Logs the user specified in the repo into the wiki. :arg repo: an instance of config.RepositorySettings with wiki credentials. """ try: if not self.testmode: self.site.login(repo.wiki["user"], repo.wiki["password"]) except LoginError as e: print(e[1]['result']) self.basepage = repo.wiki["basepage"]
[ "def", "_site_login", "(", "self", ",", "repo", ")", ":", "try", ":", "if", "not", "self", ".", "testmode", ":", "self", ".", "site", ".", "login", "(", "repo", ".", "wiki", "[", "\"user\"", "]", ",", "repo", ".", "wiki", "[", "\"password\"", "]", ")", "except", "LoginError", "as", "e", ":", "print", "(", "e", "[", "1", "]", "[", "'result'", "]", ")", "self", ".", "basepage", "=", "repo", ".", "wiki", "[", "\"basepage\"", "]" ]
Logs the user specified in the repo into the wiki. :arg repo: an instance of config.RepositorySettings with wiki credentials.
[ "Logs", "the", "user", "specified", "in", "the", "repo", "into", "the", "wiki", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L624-L634
238,831
rosenbrockc/ci
pyci/server.py
Wiki.create
def create(self, request): """Creates a new wiki page for the specified PullRequest instance. The page gets initialized with basic information about the pull request, the tests that will be run, etc. Returns the URL on the wiki. :arg request: the PullRequest instance with testing information. """ self._site_login(request.repo) self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) #We add the link to the main repo page during this creation; we also create #the full unit test report page here. self._edit_main(request) return self._create_new(request)
python
def create(self, request): """Creates a new wiki page for the specified PullRequest instance. The page gets initialized with basic information about the pull request, the tests that will be run, etc. Returns the URL on the wiki. :arg request: the PullRequest instance with testing information. """ self._site_login(request.repo) self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) #We add the link to the main repo page during this creation; we also create #the full unit test report page here. self._edit_main(request) return self._create_new(request)
[ "def", "create", "(", "self", ",", "request", ")", ":", "self", ".", "_site_login", "(", "request", ".", "repo", ")", "self", ".", "prefix", "=", "\"{}_Pull_Request_{}\"", ".", "format", "(", "request", ".", "repo", ".", "name", ",", "request", ".", "pull", ".", "number", ")", "#We add the link to the main repo page during this creation; we also create", "#the full unit test report page here.", "self", ".", "_edit_main", "(", "request", ")", "return", "self", ".", "_create_new", "(", "request", ")" ]
Creates a new wiki page for the specified PullRequest instance. The page gets initialized with basic information about the pull request, the tests that will be run, etc. Returns the URL on the wiki. :arg request: the PullRequest instance with testing information.
[ "Creates", "a", "new", "wiki", "page", "for", "the", "specified", "PullRequest", "instance", ".", "The", "page", "gets", "initialized", "with", "basic", "information", "about", "the", "pull", "request", "the", "tests", "that", "will", "be", "run", "etc", ".", "Returns", "the", "URL", "on", "the", "wiki", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L636-L649
238,832
rosenbrockc/ci
pyci/server.py
Wiki.update
def update(self, request): """Updates the wiki page with the results of the unit tests run for the pull request. :arg percent: the percent success rate of the unit tests. :arg ttotal: the total time elapsed in running *all* the unit tests. """ from os import path self._site_login(request.repo) self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) #Before we can update the results from stdout, we first need to upload them to the #server. The files can be quite big sometimes; if a file is larger than 1MB, we ... for i, test in enumerate(request.repo.testing.tests): test["remote_file"] = "{}_{}.txt".format(self.prefix, i) if test["result"] is not None and path.isfile(test["result"]): #Over here, we might consider doing something different if the wiki server #is the same physical machine as the CI server; we needn't use the network #protocols for the copy then. However, the machine knows already if an address #it is accessing is its own; the copy, at worst, would be through the named #pipes over TCP. It is wasteful compared to a HDD copy, but simplifies the #uploading (which must also make an entry in the wiki database). if not self.testmode: self.site.upload(open(test["result"]), test["remote_file"], '`stdout` from `{}`'.format(test["command"])) #Now we can just overwrite the page with the additional test results, including the #links to the stdout files we uploaded. head = list(self._newpage_head) #Add a link to the details page that points back to the github pull request URL. head.append("==Github Pull Request Info==\n") head.append(request.wiki()) head.append("==Commands Run for Unit Testing==\n") head.append(request.repo.testing.wiki()) if not self.testmode: page = self.site.Pages[self.newpage] result = page.save('\n'.join(head), summary='Edited by CI bot with uploaded unit test details.', minor=True, bot=True) return result[u'result'] == u'Success' else: return '\n'.join(head)
python
def update(self, request): """Updates the wiki page with the results of the unit tests run for the pull request. :arg percent: the percent success rate of the unit tests. :arg ttotal: the total time elapsed in running *all* the unit tests. """ from os import path self._site_login(request.repo) self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) #Before we can update the results from stdout, we first need to upload them to the #server. The files can be quite big sometimes; if a file is larger than 1MB, we ... for i, test in enumerate(request.repo.testing.tests): test["remote_file"] = "{}_{}.txt".format(self.prefix, i) if test["result"] is not None and path.isfile(test["result"]): #Over here, we might consider doing something different if the wiki server #is the same physical machine as the CI server; we needn't use the network #protocols for the copy then. However, the machine knows already if an address #it is accessing is its own; the copy, at worst, would be through the named #pipes over TCP. It is wasteful compared to a HDD copy, but simplifies the #uploading (which must also make an entry in the wiki database). if not self.testmode: self.site.upload(open(test["result"]), test["remote_file"], '`stdout` from `{}`'.format(test["command"])) #Now we can just overwrite the page with the additional test results, including the #links to the stdout files we uploaded. head = list(self._newpage_head) #Add a link to the details page that points back to the github pull request URL. head.append("==Github Pull Request Info==\n") head.append(request.wiki()) head.append("==Commands Run for Unit Testing==\n") head.append(request.repo.testing.wiki()) if not self.testmode: page = self.site.Pages[self.newpage] result = page.save('\n'.join(head), summary='Edited by CI bot with uploaded unit test details.', minor=True, bot=True) return result[u'result'] == u'Success' else: return '\n'.join(head)
[ "def", "update", "(", "self", ",", "request", ")", ":", "from", "os", "import", "path", "self", ".", "_site_login", "(", "request", ".", "repo", ")", "self", ".", "prefix", "=", "\"{}_Pull_Request_{}\"", ".", "format", "(", "request", ".", "repo", ".", "name", ",", "request", ".", "pull", ".", "number", ")", "#Before we can update the results from stdout, we first need to upload them to the", "#server. The files can be quite big sometimes; if a file is larger than 1MB, we ...", "for", "i", ",", "test", "in", "enumerate", "(", "request", ".", "repo", ".", "testing", ".", "tests", ")", ":", "test", "[", "\"remote_file\"", "]", "=", "\"{}_{}.txt\"", ".", "format", "(", "self", ".", "prefix", ",", "i", ")", "if", "test", "[", "\"result\"", "]", "is", "not", "None", "and", "path", ".", "isfile", "(", "test", "[", "\"result\"", "]", ")", ":", "#Over here, we might consider doing something different if the wiki server", "#is the same physical machine as the CI server; we needn't use the network", "#protocols for the copy then. However, the machine knows already if an address", "#it is accessing is its own; the copy, at worst, would be through the named", "#pipes over TCP. It is wasteful compared to a HDD copy, but simplifies the", "#uploading (which must also make an entry in the wiki database).", "if", "not", "self", ".", "testmode", ":", "self", ".", "site", ".", "upload", "(", "open", "(", "test", "[", "\"result\"", "]", ")", ",", "test", "[", "\"remote_file\"", "]", ",", "'`stdout` from `{}`'", ".", "format", "(", "test", "[", "\"command\"", "]", ")", ")", "#Now we can just overwrite the page with the additional test results, including the", "#links to the stdout files we uploaded.", "head", "=", "list", "(", "self", ".", "_newpage_head", ")", "#Add a link to the details page that points back to the github pull request URL.", "head", ".", "append", "(", "\"==Github Pull Request Info==\\n\"", ")", "head", ".", "append", "(", "request", ".", "wiki", "(", ")", ")", "head", ".", "append", "(", "\"==Commands Run for Unit Testing==\\n\"", ")", "head", ".", "append", "(", "request", ".", "repo", ".", "testing", ".", "wiki", "(", ")", ")", "if", "not", "self", ".", "testmode", ":", "page", "=", "self", ".", "site", ".", "Pages", "[", "self", ".", "newpage", "]", "result", "=", "page", ".", "save", "(", "'\\n'", ".", "join", "(", "head", ")", ",", "summary", "=", "'Edited by CI bot with uploaded unit test details.'", ",", "minor", "=", "True", ",", "bot", "=", "True", ")", "return", "result", "[", "u'result'", "]", "==", "u'Success'", "else", ":", "return", "'\\n'", ".", "join", "(", "head", ")" ]
Updates the wiki page with the results of the unit tests run for the pull request. :arg percent: the percent success rate of the unit tests. :arg ttotal: the total time elapsed in running *all* the unit tests.
[ "Updates", "the", "wiki", "page", "with", "the", "results", "of", "the", "unit", "tests", "run", "for", "the", "pull", "request", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L651-L691
238,833
rosenbrockc/ci
pyci/server.py
Wiki._create_new
def _create_new(self, request): """Creates the new wiki page that houses the details of the unit testing runs. """ self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) head = list(self._newpage_head) head.append(request.repo.testing.wiki(False)) if not self.testmode: page = self.site.Pages[self.newpage] result = page.save('\n'.join(head), summary='Created by CI bot for unit test details.', bot=True) return result[u'result'] == u'Success' else: return '\n'.join(head)
python
def _create_new(self, request): """Creates the new wiki page that houses the details of the unit testing runs. """ self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) head = list(self._newpage_head) head.append(request.repo.testing.wiki(False)) if not self.testmode: page = self.site.Pages[self.newpage] result = page.save('\n'.join(head), summary='Created by CI bot for unit test details.', bot=True) return result[u'result'] == u'Success' else: return '\n'.join(head)
[ "def", "_create_new", "(", "self", ",", "request", ")", ":", "self", ".", "prefix", "=", "\"{}_Pull_Request_{}\"", ".", "format", "(", "request", ".", "repo", ".", "name", ",", "request", ".", "pull", ".", "number", ")", "head", "=", "list", "(", "self", ".", "_newpage_head", ")", "head", ".", "append", "(", "request", ".", "repo", ".", "testing", ".", "wiki", "(", "False", ")", ")", "if", "not", "self", ".", "testmode", ":", "page", "=", "self", ".", "site", ".", "Pages", "[", "self", ".", "newpage", "]", "result", "=", "page", ".", "save", "(", "'\\n'", ".", "join", "(", "head", ")", ",", "summary", "=", "'Created by CI bot for unit test details.'", ",", "bot", "=", "True", ")", "return", "result", "[", "u'result'", "]", "==", "u'Success'", "else", ":", "return", "'\\n'", ".", "join", "(", "head", ")" ]
Creates the new wiki page that houses the details of the unit testing runs.
[ "Creates", "the", "new", "wiki", "page", "that", "houses", "the", "details", "of", "the", "unit", "testing", "runs", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L693-L704
238,834
rosenbrockc/ci
pyci/server.py
Wiki._edit_main
def _edit_main(self, request): """Adds the link to the new unit testing results on the repo's main wiki page. """ self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) if not self.testmode: page = site.pages[self.basepage] text = page.text() else: text = "This is a fake wiki page.\n\n<!--@CI:Placeholder-->" self.newpage = self.prefix link = "Pull Request #{}".format(request.pull.number) text = text.replace("<!--@CI:Placeholder-->", "* [[{}|{}]]\n<!--@CI:Placeholder-->".format(self.newpage, link)) if not self.testmode: result = page.save(text, summary="Added {} unit test link.".format(link), minor=True, bot=True) return result[u'result'] == u'Success' else: return text
python
def _edit_main(self, request): """Adds the link to the new unit testing results on the repo's main wiki page. """ self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number) if not self.testmode: page = site.pages[self.basepage] text = page.text() else: text = "This is a fake wiki page.\n\n<!--@CI:Placeholder-->" self.newpage = self.prefix link = "Pull Request #{}".format(request.pull.number) text = text.replace("<!--@CI:Placeholder-->", "* [[{}|{}]]\n<!--@CI:Placeholder-->".format(self.newpage, link)) if not self.testmode: result = page.save(text, summary="Added {} unit test link.".format(link), minor=True, bot=True) return result[u'result'] == u'Success' else: return text
[ "def", "_edit_main", "(", "self", ",", "request", ")", ":", "self", ".", "prefix", "=", "\"{}_Pull_Request_{}\"", ".", "format", "(", "request", ".", "repo", ".", "name", ",", "request", ".", "pull", ".", "number", ")", "if", "not", "self", ".", "testmode", ":", "page", "=", "site", ".", "pages", "[", "self", ".", "basepage", "]", "text", "=", "page", ".", "text", "(", ")", "else", ":", "text", "=", "\"This is a fake wiki page.\\n\\n<!--@CI:Placeholder-->\"", "self", ".", "newpage", "=", "self", ".", "prefix", "link", "=", "\"Pull Request #{}\"", ".", "format", "(", "request", ".", "pull", ".", "number", ")", "text", "=", "text", ".", "replace", "(", "\"<!--@CI:Placeholder-->\"", ",", "\"* [[{}|{}]]\\n<!--@CI:Placeholder-->\"", ".", "format", "(", "self", ".", "newpage", ",", "link", ")", ")", "if", "not", "self", ".", "testmode", ":", "result", "=", "page", ".", "save", "(", "text", ",", "summary", "=", "\"Added {} unit test link.\"", ".", "format", "(", "link", ")", ",", "minor", "=", "True", ",", "bot", "=", "True", ")", "return", "result", "[", "u'result'", "]", "==", "u'Success'", "else", ":", "return", "text" ]
Adds the link to the new unit testing results on the repo's main wiki page.
[ "Adds", "the", "link", "to", "the", "new", "unit", "testing", "results", "on", "the", "repo", "s", "main", "wiki", "page", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L706-L724
238,835
rosenbrockc/ci
pyci/server.py
CronManager.email
def email(self, repo, event, fields, dryrun=False): """Sends an email to the configured recipients for the specified event. :arg repo: the name of the repository to include in the email subject. :arg event: one of ["start", "success", "failure", "timeout", "error"]. :arg fields: a dictionary of field values to replace into the email template contents to specialize them. :arg dryrun: when true, the email object and contents are initialized, but the request is never sent to the SMTP server. """ tcontents = self._get_template(event, "txt", fields) hcontents = self._get_template(event, "html", fields) if tcontents is not None and hcontents is not None: return Email(self.server, repo, self.settings[repo], tcontents, hcontents, dryrun)
python
def email(self, repo, event, fields, dryrun=False): """Sends an email to the configured recipients for the specified event. :arg repo: the name of the repository to include in the email subject. :arg event: one of ["start", "success", "failure", "timeout", "error"]. :arg fields: a dictionary of field values to replace into the email template contents to specialize them. :arg dryrun: when true, the email object and contents are initialized, but the request is never sent to the SMTP server. """ tcontents = self._get_template(event, "txt", fields) hcontents = self._get_template(event, "html", fields) if tcontents is not None and hcontents is not None: return Email(self.server, repo, self.settings[repo], tcontents, hcontents, dryrun)
[ "def", "email", "(", "self", ",", "repo", ",", "event", ",", "fields", ",", "dryrun", "=", "False", ")", ":", "tcontents", "=", "self", ".", "_get_template", "(", "event", ",", "\"txt\"", ",", "fields", ")", "hcontents", "=", "self", ".", "_get_template", "(", "event", ",", "\"html\"", ",", "fields", ")", "if", "tcontents", "is", "not", "None", "and", "hcontents", "is", "not", "None", ":", "return", "Email", "(", "self", ".", "server", ",", "repo", ",", "self", ".", "settings", "[", "repo", "]", ",", "tcontents", ",", "hcontents", ",", "dryrun", ")" ]
Sends an email to the configured recipients for the specified event. :arg repo: the name of the repository to include in the email subject. :arg event: one of ["start", "success", "failure", "timeout", "error"]. :arg fields: a dictionary of field values to replace into the email template contents to specialize them. :arg dryrun: when true, the email object and contents are initialized, but the request is never sent to the SMTP server.
[ "Sends", "an", "email", "to", "the", "configured", "recipients", "for", "the", "specified", "event", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L762-L775
238,836
JukeboxPipeline/jukebox-core
src/jukeboxcore/ostool.py
detect_sys
def detect_sys(): """Tries to identify your python platform :returns: a dict with the gathered information :rtype: dict :raises: None the returned dict has these keys: 'system', 'bit', 'compiler', 'python_version_tuple' eg.:: {'system':'Windows', 'bit':'32bit', 'compiler':'MSC v.1500 32bit (Intel)', 'python_version_tuple':('2', '7', '6')} """ system = platform.system() bit = platform.architecture()[0] compiler = platform.python_compiler() ver = platform.python_version_tuple() return {'system': system, 'bit': bit, 'compiler': compiler, 'python_version_tuple': ver}
python
def detect_sys(): """Tries to identify your python platform :returns: a dict with the gathered information :rtype: dict :raises: None the returned dict has these keys: 'system', 'bit', 'compiler', 'python_version_tuple' eg.:: {'system':'Windows', 'bit':'32bit', 'compiler':'MSC v.1500 32bit (Intel)', 'python_version_tuple':('2', '7', '6')} """ system = platform.system() bit = platform.architecture()[0] compiler = platform.python_compiler() ver = platform.python_version_tuple() return {'system': system, 'bit': bit, 'compiler': compiler, 'python_version_tuple': ver}
[ "def", "detect_sys", "(", ")", ":", "system", "=", "platform", ".", "system", "(", ")", "bit", "=", "platform", ".", "architecture", "(", ")", "[", "0", "]", "compiler", "=", "platform", ".", "python_compiler", "(", ")", "ver", "=", "platform", ".", "python_version_tuple", "(", ")", "return", "{", "'system'", ":", "system", ",", "'bit'", ":", "bit", ",", "'compiler'", ":", "compiler", ",", "'python_version_tuple'", ":", "ver", "}" ]
Tries to identify your python platform :returns: a dict with the gathered information :rtype: dict :raises: None the returned dict has these keys: 'system', 'bit', 'compiler', 'python_version_tuple' eg.:: {'system':'Windows', 'bit':'32bit', 'compiler':'MSC v.1500 32bit (Intel)', 'python_version_tuple':('2', '7', '6')}
[ "Tries", "to", "identify", "your", "python", "platform" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/ostool.py#L24-L42
238,837
JukeboxPipeline/jukebox-core
src/jukeboxcore/ostool.py
WindowsInterface.get_maya_location
def get_maya_location(self, ): """ Return the installation path to maya :returns: path to maya :rtype: str :raises: errors.SoftwareNotFoundError """ import _winreg # query winreg entry # the last flag is needed, if we want to test with 32 bit python! # Because Maya is an 64 bit key! for ver in MAYA_VERSIONS: try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, MAYA_REG_KEY.format(mayaversion=ver), 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY) value = _winreg.QueryValueEx(key, "MAYA_INSTALL_LOCATION")[0] except WindowsError: log.debug('Maya %s installation not found in registry!' % ver) if not value: raise errors.SoftwareNotFoundError('Maya %s installation not found in registry!' % MAYA_VERSIONS) return value
python
def get_maya_location(self, ): """ Return the installation path to maya :returns: path to maya :rtype: str :raises: errors.SoftwareNotFoundError """ import _winreg # query winreg entry # the last flag is needed, if we want to test with 32 bit python! # Because Maya is an 64 bit key! for ver in MAYA_VERSIONS: try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, MAYA_REG_KEY.format(mayaversion=ver), 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY) value = _winreg.QueryValueEx(key, "MAYA_INSTALL_LOCATION")[0] except WindowsError: log.debug('Maya %s installation not found in registry!' % ver) if not value: raise errors.SoftwareNotFoundError('Maya %s installation not found in registry!' % MAYA_VERSIONS) return value
[ "def", "get_maya_location", "(", "self", ",", ")", ":", "import", "_winreg", "# query winreg entry", "# the last flag is needed, if we want to test with 32 bit python!", "# Because Maya is an 64 bit key!", "for", "ver", "in", "MAYA_VERSIONS", ":", "try", ":", "key", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "MAYA_REG_KEY", ".", "format", "(", "mayaversion", "=", "ver", ")", ",", "0", ",", "_winreg", ".", "KEY_READ", "|", "_winreg", ".", "KEY_WOW64_64KEY", ")", "value", "=", "_winreg", ".", "QueryValueEx", "(", "key", ",", "\"MAYA_INSTALL_LOCATION\"", ")", "[", "0", "]", "except", "WindowsError", ":", "log", ".", "debug", "(", "'Maya %s installation not found in registry!'", "%", "ver", ")", "if", "not", "value", ":", "raise", "errors", ".", "SoftwareNotFoundError", "(", "'Maya %s installation not found in registry!'", "%", "MAYA_VERSIONS", ")", "return", "value" ]
Return the installation path to maya :returns: path to maya :rtype: str :raises: errors.SoftwareNotFoundError
[ "Return", "the", "installation", "path", "to", "maya" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/ostool.py#L132-L153
238,838
JukeboxPipeline/jukebox-core
src/jukeboxcore/ostool.py
WindowsInterface.get_maya_envpath
def get_maya_envpath(self): """Return the PYTHONPATH neccessary for running mayapy If you start native mayapy, it will setup these paths. You might want to prepend this to your path if running from an external intepreter. :returns: the PYTHONPATH that is used for running mayapy :rtype: str :raises: None """ opj = os.path.join ml = self.get_maya_location() mb = self.get_maya_bin() msp = self.get_maya_sitepackage_dir() pyzip = opj(mb, "python27.zip") pydir = opj(ml, "Python") pydll = opj(pydir, "DLLs") pylib = opj(pydir, "lib") pyplat = opj(pylib, "plat-win") pytk = opj(pylib, "lib-tk") path = os.pathsep.join((pyzip, pydll, pylib, pyplat, pytk, mb, pydir, msp)) return path
python
def get_maya_envpath(self): """Return the PYTHONPATH neccessary for running mayapy If you start native mayapy, it will setup these paths. You might want to prepend this to your path if running from an external intepreter. :returns: the PYTHONPATH that is used for running mayapy :rtype: str :raises: None """ opj = os.path.join ml = self.get_maya_location() mb = self.get_maya_bin() msp = self.get_maya_sitepackage_dir() pyzip = opj(mb, "python27.zip") pydir = opj(ml, "Python") pydll = opj(pydir, "DLLs") pylib = opj(pydir, "lib") pyplat = opj(pylib, "plat-win") pytk = opj(pylib, "lib-tk") path = os.pathsep.join((pyzip, pydll, pylib, pyplat, pytk, mb, pydir, msp)) return path
[ "def", "get_maya_envpath", "(", "self", ")", ":", "opj", "=", "os", ".", "path", ".", "join", "ml", "=", "self", ".", "get_maya_location", "(", ")", "mb", "=", "self", ".", "get_maya_bin", "(", ")", "msp", "=", "self", ".", "get_maya_sitepackage_dir", "(", ")", "pyzip", "=", "opj", "(", "mb", ",", "\"python27.zip\"", ")", "pydir", "=", "opj", "(", "ml", ",", "\"Python\"", ")", "pydll", "=", "opj", "(", "pydir", ",", "\"DLLs\"", ")", "pylib", "=", "opj", "(", "pydir", ",", "\"lib\"", ")", "pyplat", "=", "opj", "(", "pylib", ",", "\"plat-win\"", ")", "pytk", "=", "opj", "(", "pylib", ",", "\"lib-tk\"", ")", "path", "=", "os", ".", "pathsep", ".", "join", "(", "(", "pyzip", ",", "pydll", ",", "pylib", ",", "pyplat", ",", "pytk", ",", "mb", ",", "pydir", ",", "msp", ")", ")", "return", "path" ]
Return the PYTHONPATH neccessary for running mayapy If you start native mayapy, it will setup these paths. You might want to prepend this to your path if running from an external intepreter. :returns: the PYTHONPATH that is used for running mayapy :rtype: str :raises: None
[ "Return", "the", "PYTHONPATH", "neccessary", "for", "running", "mayapy" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/ostool.py#L195-L217
238,839
FujiMakoto/AgentML
agentml/parser/trigger/response/container.py
ResponseContainer._sort
def _sort(self): """ Sort the response dictionaries priority levels for ordered iteration """ self._log.debug('Sorting responses by priority') self._responses = OrderedDict(sorted(list(self._responses.items()), reverse=True)) self.sorted = True
python
def _sort(self): """ Sort the response dictionaries priority levels for ordered iteration """ self._log.debug('Sorting responses by priority') self._responses = OrderedDict(sorted(list(self._responses.items()), reverse=True)) self.sorted = True
[ "def", "_sort", "(", "self", ")", ":", "self", ".", "_log", ".", "debug", "(", "'Sorting responses by priority'", ")", "self", ".", "_responses", "=", "OrderedDict", "(", "sorted", "(", "list", "(", "self", ".", "_responses", ".", "items", "(", ")", ")", ",", "reverse", "=", "True", ")", ")", "self", ".", "sorted", "=", "True" ]
Sort the response dictionaries priority levels for ordered iteration
[ "Sort", "the", "response", "dictionaries", "priority", "levels", "for", "ordered", "iteration" ]
c8cb64b460d876666bf29ea2c682189874c7c403
https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/response/container.py#L22-L28
238,840
joelcolucci/flask-registerblueprints
flask_registerblueprints/register.py
register_blueprints
def register_blueprints(app, application_package_name=None, blueprint_directory=None): """Register Flask blueprints on app object""" if not application_package_name: application_package_name = 'app' if not blueprint_directory: blueprint_directory = os.path.join(os.getcwd(), application_package_name) blueprint_directories = get_child_directories(blueprint_directory) for directory in blueprint_directories: abs_package = '{}.{}'.format(application_package_name, directory) service = importlib.import_module(abs_package) app.register_blueprint(service.blueprint_api, url_prefix='')
python
def register_blueprints(app, application_package_name=None, blueprint_directory=None): """Register Flask blueprints on app object""" if not application_package_name: application_package_name = 'app' if not blueprint_directory: blueprint_directory = os.path.join(os.getcwd(), application_package_name) blueprint_directories = get_child_directories(blueprint_directory) for directory in blueprint_directories: abs_package = '{}.{}'.format(application_package_name, directory) service = importlib.import_module(abs_package) app.register_blueprint(service.blueprint_api, url_prefix='')
[ "def", "register_blueprints", "(", "app", ",", "application_package_name", "=", "None", ",", "blueprint_directory", "=", "None", ")", ":", "if", "not", "application_package_name", ":", "application_package_name", "=", "'app'", "if", "not", "blueprint_directory", ":", "blueprint_directory", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "application_package_name", ")", "blueprint_directories", "=", "get_child_directories", "(", "blueprint_directory", ")", "for", "directory", "in", "blueprint_directories", ":", "abs_package", "=", "'{}.{}'", ".", "format", "(", "application_package_name", ",", "directory", ")", "service", "=", "importlib", ".", "import_module", "(", "abs_package", ")", "app", ".", "register_blueprint", "(", "service", ".", "blueprint_api", ",", "url_prefix", "=", "''", ")" ]
Register Flask blueprints on app object
[ "Register", "Flask", "blueprints", "on", "app", "object" ]
c117404691b66594f2cc84bff103ce893c633ecc
https://github.com/joelcolucci/flask-registerblueprints/blob/c117404691b66594f2cc84bff103ce893c633ecc/flask_registerblueprints/register.py#L7-L21
238,841
joelcolucci/flask-registerblueprints
flask_registerblueprints/register.py
get_child_directories
def get_child_directories(path): """Return names of immediate child directories""" if not _is_valid_directory(path): raise exceptions.InvalidDirectory entries = os.listdir(path) directory_names = [] for entry in entries: abs_entry_path = os.path.join(path, entry) if _is_valid_directory(abs_entry_path): directory_names.append(entry) return directory_names
python
def get_child_directories(path): """Return names of immediate child directories""" if not _is_valid_directory(path): raise exceptions.InvalidDirectory entries = os.listdir(path) directory_names = [] for entry in entries: abs_entry_path = os.path.join(path, entry) if _is_valid_directory(abs_entry_path): directory_names.append(entry) return directory_names
[ "def", "get_child_directories", "(", "path", ")", ":", "if", "not", "_is_valid_directory", "(", "path", ")", ":", "raise", "exceptions", ".", "InvalidDirectory", "entries", "=", "os", ".", "listdir", "(", "path", ")", "directory_names", "=", "[", "]", "for", "entry", "in", "entries", ":", "abs_entry_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "entry", ")", "if", "_is_valid_directory", "(", "abs_entry_path", ")", ":", "directory_names", ".", "append", "(", "entry", ")", "return", "directory_names" ]
Return names of immediate child directories
[ "Return", "names", "of", "immediate", "child", "directories" ]
c117404691b66594f2cc84bff103ce893c633ecc
https://github.com/joelcolucci/flask-registerblueprints/blob/c117404691b66594f2cc84bff103ce893c633ecc/flask_registerblueprints/register.py#L24-L37
238,842
JoshAshby/pyRedisORM
redisORM/redis_model.py
RedisKeys.delete
def delete(self): """ Deletes all the keys from redis along with emptying the objects internal `_data` dict, then deleting itself at the end of it all. """ redis_search_key = ":".join([self.namespace, self.key, "*"]) keys = self.conn.keys(redis_search_key) if keys: for key in keys: part = key.split(":")[-1] self._data.pop(part) self.conn.delete(part) del self
python
def delete(self): """ Deletes all the keys from redis along with emptying the objects internal `_data` dict, then deleting itself at the end of it all. """ redis_search_key = ":".join([self.namespace, self.key, "*"]) keys = self.conn.keys(redis_search_key) if keys: for key in keys: part = key.split(":")[-1] self._data.pop(part) self.conn.delete(part) del self
[ "def", "delete", "(", "self", ")", ":", "redis_search_key", "=", "\":\"", ".", "join", "(", "[", "self", ".", "namespace", ",", "self", ".", "key", ",", "\"*\"", "]", ")", "keys", "=", "self", ".", "conn", ".", "keys", "(", "redis_search_key", ")", "if", "keys", ":", "for", "key", "in", "keys", ":", "part", "=", "key", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", "self", ".", "_data", ".", "pop", "(", "part", ")", "self", ".", "conn", ".", "delete", "(", "part", ")", "del", "self" ]
Deletes all the keys from redis along with emptying the objects internal `_data` dict, then deleting itself at the end of it all.
[ "Deletes", "all", "the", "keys", "from", "redis", "along", "with", "emptying", "the", "objects", "internal", "_data", "dict", "then", "deleting", "itself", "at", "the", "end", "of", "it", "all", "." ]
02b40889453638c5f0a1dc63df5279cfbfd1fe4c
https://github.com/JoshAshby/pyRedisORM/blob/02b40889453638c5f0a1dc63df5279cfbfd1fe4c/redisORM/redis_model.py#L102-L115
238,843
JoshAshby/pyRedisORM
redisORM/redis_model.py
RedisKeys.get
def get(self, part): """ Retrieves a part of the model from redis and stores it. :param part: The part of the model to retrieve. :raises RedisORMException: If the redis type is different from string or list (the only two supported types at this time.) """ redis_key = ':'.join([self.namespace, self.key, part]) objectType = self.conn.type(redis_key) if objectType == "string": self._data[part] = self.conn.get(redis_key) elif objectType == "list": self._data[part] = RedisList(redis_key, self.conn) else: raise RedisORMException("Other types besides string and list are unsupported at this time.")
python
def get(self, part): """ Retrieves a part of the model from redis and stores it. :param part: The part of the model to retrieve. :raises RedisORMException: If the redis type is different from string or list (the only two supported types at this time.) """ redis_key = ':'.join([self.namespace, self.key, part]) objectType = self.conn.type(redis_key) if objectType == "string": self._data[part] = self.conn.get(redis_key) elif objectType == "list": self._data[part] = RedisList(redis_key, self.conn) else: raise RedisORMException("Other types besides string and list are unsupported at this time.")
[ "def", "get", "(", "self", ",", "part", ")", ":", "redis_key", "=", "':'", ".", "join", "(", "[", "self", ".", "namespace", ",", "self", ".", "key", ",", "part", "]", ")", "objectType", "=", "self", ".", "conn", ".", "type", "(", "redis_key", ")", "if", "objectType", "==", "\"string\"", ":", "self", ".", "_data", "[", "part", "]", "=", "self", ".", "conn", ".", "get", "(", "redis_key", ")", "elif", "objectType", "==", "\"list\"", ":", "self", ".", "_data", "[", "part", "]", "=", "RedisList", "(", "redis_key", ",", "self", ".", "conn", ")", "else", ":", "raise", "RedisORMException", "(", "\"Other types besides string and list are unsupported at this time.\"", ")" ]
Retrieves a part of the model from redis and stores it. :param part: The part of the model to retrieve. :raises RedisORMException: If the redis type is different from string or list (the only two supported types at this time.)
[ "Retrieves", "a", "part", "of", "the", "model", "from", "redis", "and", "stores", "it", "." ]
02b40889453638c5f0a1dc63df5279cfbfd1fe4c
https://github.com/JoshAshby/pyRedisORM/blob/02b40889453638c5f0a1dc63df5279cfbfd1fe4c/redisORM/redis_model.py#L117-L135
238,844
wooga/play-deliver
playdeliver/inapp_product.py
upload
def upload(client, source_dir): """Upload inappproducts to play store.""" print('') print('upload inappproducs') print('---------------------') products_folder = os.path.join(source_dir, 'products') product_files = filter(os.path.isfile, list_dir_abspath(products_folder)) current_product_skus = map(lambda product: product['sku'], client.list_inappproducts()) print(current_product_skus) for product_file in product_files: with open(product_file) as product_file: product = json.load(product_file) #check if the product is new sku = product['sku'] product['packageName'] = client.package_name print(sku) if sku in current_product_skus: print("update product {0}".format(sku)) client.update_inappproduct(product, sku) else: print("create product {0}".format(sku)) client.insert_inappproduct(product)
python
def upload(client, source_dir): """Upload inappproducts to play store.""" print('') print('upload inappproducs') print('---------------------') products_folder = os.path.join(source_dir, 'products') product_files = filter(os.path.isfile, list_dir_abspath(products_folder)) current_product_skus = map(lambda product: product['sku'], client.list_inappproducts()) print(current_product_skus) for product_file in product_files: with open(product_file) as product_file: product = json.load(product_file) #check if the product is new sku = product['sku'] product['packageName'] = client.package_name print(sku) if sku in current_product_skus: print("update product {0}".format(sku)) client.update_inappproduct(product, sku) else: print("create product {0}".format(sku)) client.insert_inappproduct(product)
[ "def", "upload", "(", "client", ",", "source_dir", ")", ":", "print", "(", "''", ")", "print", "(", "'upload inappproducs'", ")", "print", "(", "'---------------------'", ")", "products_folder", "=", "os", ".", "path", ".", "join", "(", "source_dir", ",", "'products'", ")", "product_files", "=", "filter", "(", "os", ".", "path", ".", "isfile", ",", "list_dir_abspath", "(", "products_folder", ")", ")", "current_product_skus", "=", "map", "(", "lambda", "product", ":", "product", "[", "'sku'", "]", ",", "client", ".", "list_inappproducts", "(", ")", ")", "print", "(", "current_product_skus", ")", "for", "product_file", "in", "product_files", ":", "with", "open", "(", "product_file", ")", "as", "product_file", ":", "product", "=", "json", ".", "load", "(", "product_file", ")", "#check if the product is new", "sku", "=", "product", "[", "'sku'", "]", "product", "[", "'packageName'", "]", "=", "client", ".", "package_name", "print", "(", "sku", ")", "if", "sku", "in", "current_product_skus", ":", "print", "(", "\"update product {0}\"", ".", "format", "(", "sku", ")", ")", "client", ".", "update_inappproduct", "(", "product", ",", "sku", ")", "else", ":", "print", "(", "\"create product {0}\"", ".", "format", "(", "sku", ")", ")", "client", ".", "insert_inappproduct", "(", "product", ")" ]
Upload inappproducts to play store.
[ "Upload", "inappproducts", "to", "play", "store", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/inapp_product.py#L7-L30
238,845
wooga/play-deliver
playdeliver/inapp_product.py
download
def download(client, target_dir): """Download inappproducts from play store.""" print('') print("download inappproducts") print('---------------------') products = client.list_inappproducts() for product in products: path = os.path.join(target_dir, 'products') del product['packageName'] mkdir_p(path) with open(os.path.join(path, product['sku'] + '.json'), 'w') as outfile: print("save product for {0}".format(product['sku'])) json.dump( product, outfile, sort_keys=True, indent=4, separators=(',', ': '))
python
def download(client, target_dir): """Download inappproducts from play store.""" print('') print("download inappproducts") print('---------------------') products = client.list_inappproducts() for product in products: path = os.path.join(target_dir, 'products') del product['packageName'] mkdir_p(path) with open(os.path.join(path, product['sku'] + '.json'), 'w') as outfile: print("save product for {0}".format(product['sku'])) json.dump( product, outfile, sort_keys=True, indent=4, separators=(',', ': '))
[ "def", "download", "(", "client", ",", "target_dir", ")", ":", "print", "(", "''", ")", "print", "(", "\"download inappproducts\"", ")", "print", "(", "'---------------------'", ")", "products", "=", "client", ".", "list_inappproducts", "(", ")", "for", "product", "in", "products", ":", "path", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'products'", ")", "del", "product", "[", "'packageName'", "]", "mkdir_p", "(", "path", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "product", "[", "'sku'", "]", "+", "'.json'", ")", ",", "'w'", ")", "as", "outfile", ":", "print", "(", "\"save product for {0}\"", ".", "format", "(", "product", "[", "'sku'", "]", ")", ")", "json", ".", "dump", "(", "product", ",", "outfile", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
Download inappproducts from play store.
[ "Download", "inappproducts", "from", "play", "store", "." ]
9de0f35376f5342720b3a90bd3ca296b1f3a3f4c
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/inapp_product.py#L33-L48
238,846
sbarham/dsrt
dsrt/application/utils.py
dataset_exists
def dataset_exists(dataset_name): '''If a dataset with the given name exists, return its absolute path; otherwise return None''' dataset_dir = os.path.join(LIB_DIR, 'datasets') dataset_path = os.path.join(dataset_dir, dataset_name) return dataset_path if os.path.isdir(dataset_path) else None
python
def dataset_exists(dataset_name): '''If a dataset with the given name exists, return its absolute path; otherwise return None''' dataset_dir = os.path.join(LIB_DIR, 'datasets') dataset_path = os.path.join(dataset_dir, dataset_name) return dataset_path if os.path.isdir(dataset_path) else None
[ "def", "dataset_exists", "(", "dataset_name", ")", ":", "dataset_dir", "=", "os", ".", "path", ".", "join", "(", "LIB_DIR", ",", "'datasets'", ")", "dataset_path", "=", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "dataset_name", ")", "return", "dataset_path", "if", "os", ".", "path", ".", "isdir", "(", "dataset_path", ")", "else", "None" ]
If a dataset with the given name exists, return its absolute path; otherwise return None
[ "If", "a", "dataset", "with", "the", "given", "name", "exists", "return", "its", "absolute", "path", ";", "otherwise", "return", "None" ]
bc664739f2f52839461d3e72773b71146fd56a9a
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/dsrt/application/utils.py#L40-L45
238,847
realestate-com-au/dashmat
dashmat/core_modules/splunk/splunk-sdk-1.3.0/splunklib/modularinput/script.py
Script.run_script
def run_script(self, args, event_writer, input_stream): """Handles all the specifics of running a modular input :param args: List of command line arguments passed to this script. :param event_writer: An ``EventWriter`` object for writing events. :param input_stream: An input stream for reading inputs. :returns: An integer to be used as the exit value of this program. """ try: if len(args) == 1: # This script is running as an input. Input definitions will be # passed on stdin as XML, and the script will write events on # stdout and log entries on stderr. self._input_definition = InputDefinition.parse(input_stream) self.stream_events(self._input_definition, event_writer) event_writer.close() return 0 elif str(args[1]).lower() == "--scheme": # Splunk has requested XML specifying the scheme for this # modular input Return it and exit. scheme = self.get_scheme() if scheme is None: event_writer.log( EventWriter.FATAL, "Modular input script returned a null scheme.") return 1 else: event_writer.write_xml_document(scheme.to_xml()) return 0 elif args[1].lower() == "--validate-arguments": validation_definition = ValidationDefinition.parse(input_stream) try: self.validate_input(validation_definition) return 0 except Exception as e: root = ET.Element("error") ET.SubElement(root, "message").text = e.message event_writer.write_xml_document(root) return 1 else: err_string = "ERROR Invalid arguments to modular input script:" + ' '.join( args) event_writer._err.write(err_string) except Exception as e: err_string = EventWriter.ERROR + e.message event_writer._err.write(err_string) return 1
python
def run_script(self, args, event_writer, input_stream): """Handles all the specifics of running a modular input :param args: List of command line arguments passed to this script. :param event_writer: An ``EventWriter`` object for writing events. :param input_stream: An input stream for reading inputs. :returns: An integer to be used as the exit value of this program. """ try: if len(args) == 1: # This script is running as an input. Input definitions will be # passed on stdin as XML, and the script will write events on # stdout and log entries on stderr. self._input_definition = InputDefinition.parse(input_stream) self.stream_events(self._input_definition, event_writer) event_writer.close() return 0 elif str(args[1]).lower() == "--scheme": # Splunk has requested XML specifying the scheme for this # modular input Return it and exit. scheme = self.get_scheme() if scheme is None: event_writer.log( EventWriter.FATAL, "Modular input script returned a null scheme.") return 1 else: event_writer.write_xml_document(scheme.to_xml()) return 0 elif args[1].lower() == "--validate-arguments": validation_definition = ValidationDefinition.parse(input_stream) try: self.validate_input(validation_definition) return 0 except Exception as e: root = ET.Element("error") ET.SubElement(root, "message").text = e.message event_writer.write_xml_document(root) return 1 else: err_string = "ERROR Invalid arguments to modular input script:" + ' '.join( args) event_writer._err.write(err_string) except Exception as e: err_string = EventWriter.ERROR + e.message event_writer._err.write(err_string) return 1
[ "def", "run_script", "(", "self", ",", "args", ",", "event_writer", ",", "input_stream", ")", ":", "try", ":", "if", "len", "(", "args", ")", "==", "1", ":", "# This script is running as an input. Input definitions will be", "# passed on stdin as XML, and the script will write events on", "# stdout and log entries on stderr.", "self", ".", "_input_definition", "=", "InputDefinition", ".", "parse", "(", "input_stream", ")", "self", ".", "stream_events", "(", "self", ".", "_input_definition", ",", "event_writer", ")", "event_writer", ".", "close", "(", ")", "return", "0", "elif", "str", "(", "args", "[", "1", "]", ")", ".", "lower", "(", ")", "==", "\"--scheme\"", ":", "# Splunk has requested XML specifying the scheme for this", "# modular input Return it and exit.", "scheme", "=", "self", ".", "get_scheme", "(", ")", "if", "scheme", "is", "None", ":", "event_writer", ".", "log", "(", "EventWriter", ".", "FATAL", ",", "\"Modular input script returned a null scheme.\"", ")", "return", "1", "else", ":", "event_writer", ".", "write_xml_document", "(", "scheme", ".", "to_xml", "(", ")", ")", "return", "0", "elif", "args", "[", "1", "]", ".", "lower", "(", ")", "==", "\"--validate-arguments\"", ":", "validation_definition", "=", "ValidationDefinition", ".", "parse", "(", "input_stream", ")", "try", ":", "self", ".", "validate_input", "(", "validation_definition", ")", "return", "0", "except", "Exception", "as", "e", ":", "root", "=", "ET", ".", "Element", "(", "\"error\"", ")", "ET", ".", "SubElement", "(", "root", ",", "\"message\"", ")", ".", "text", "=", "e", ".", "message", "event_writer", ".", "write_xml_document", "(", "root", ")", "return", "1", "else", ":", "err_string", "=", "\"ERROR Invalid arguments to modular input script:\"", "+", "' '", ".", "join", "(", "args", ")", "event_writer", ".", "_err", ".", "write", "(", "err_string", ")", "except", "Exception", "as", "e", ":", "err_string", "=", "EventWriter", ".", "ERROR", "+", "e", ".", "message", "event_writer", ".", "_err", ".", "write", "(", "err_string", ")", "return", "1" ]
Handles all the specifics of running a modular input :param args: List of command line arguments passed to this script. :param event_writer: An ``EventWriter`` object for writing events. :param input_stream: An input stream for reading inputs. :returns: An integer to be used as the exit value of this program.
[ "Handles", "all", "the", "specifics", "of", "running", "a", "modular", "input" ]
433886e52698f0ddb9956f087b76041966c3bcd1
https://github.com/realestate-com-au/dashmat/blob/433886e52698f0ddb9956f087b76041966c3bcd1/dashmat/core_modules/splunk/splunk-sdk-1.3.0/splunklib/modularinput/script.py#L57-L108
238,848
cslarsen/elv
elv/elv.py
Parse.money
def money(s, thousand_sep=".", decimal_sep=","): """Converts money amount in string to a Decimal object. With the default arguments, the format is expected to be ``-38.500,00``, where dots separate thousands and comma the decimals. Args: thousand_sep: Separator for thousands. decimal_sep: Separator for decimals. Returns: A ``Decimal`` object of the string encoded money amount. """ s = s.replace(thousand_sep, "") s = s.replace(decimal_sep, ".") return Decimal(s)
python
def money(s, thousand_sep=".", decimal_sep=","): """Converts money amount in string to a Decimal object. With the default arguments, the format is expected to be ``-38.500,00``, where dots separate thousands and comma the decimals. Args: thousand_sep: Separator for thousands. decimal_sep: Separator for decimals. Returns: A ``Decimal`` object of the string encoded money amount. """ s = s.replace(thousand_sep, "") s = s.replace(decimal_sep, ".") return Decimal(s)
[ "def", "money", "(", "s", ",", "thousand_sep", "=", "\".\"", ",", "decimal_sep", "=", "\",\"", ")", ":", "s", "=", "s", ".", "replace", "(", "thousand_sep", ",", "\"\"", ")", "s", "=", "s", ".", "replace", "(", "decimal_sep", ",", "\".\"", ")", "return", "Decimal", "(", "s", ")" ]
Converts money amount in string to a Decimal object. With the default arguments, the format is expected to be ``-38.500,00``, where dots separate thousands and comma the decimals. Args: thousand_sep: Separator for thousands. decimal_sep: Separator for decimals. Returns: A ``Decimal`` object of the string encoded money amount.
[ "Converts", "money", "amount", "in", "string", "to", "a", "Decimal", "object", "." ]
4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L45-L60
238,849
cslarsen/elv
elv/elv.py
Parse.csv_row_to_transaction
def csv_row_to_transaction(index, row, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses a row of strings to a ``Transaction`` object. Args: index: The index of this row in the original CSV file. Used for sorting ``Transaction``s by their order of appearance. row: The row containing strings for [transfer_date, posted_date, message, money_amount, money_total]. source_encoding: The encoding that will be used to decode strings to UTF-8. date_format: The format of dates in this row. thousand_sep: The thousand separator in money amounts. decimal_sep: The decimal separator in money amounts. Returns: A ``Transaction`` object. """ xfer, posted, message, amount, total = row xfer = Parse.date(xfer) posted = Parse.date(posted) message = Parse.to_utf8(message, source_encoding) amount = Parse.money(amount) total = Parse.money(total) return Transaction(index, xfer, posted, message, amount, total)
python
def csv_row_to_transaction(index, row, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses a row of strings to a ``Transaction`` object. Args: index: The index of this row in the original CSV file. Used for sorting ``Transaction``s by their order of appearance. row: The row containing strings for [transfer_date, posted_date, message, money_amount, money_total]. source_encoding: The encoding that will be used to decode strings to UTF-8. date_format: The format of dates in this row. thousand_sep: The thousand separator in money amounts. decimal_sep: The decimal separator in money amounts. Returns: A ``Transaction`` object. """ xfer, posted, message, amount, total = row xfer = Parse.date(xfer) posted = Parse.date(posted) message = Parse.to_utf8(message, source_encoding) amount = Parse.money(amount) total = Parse.money(total) return Transaction(index, xfer, posted, message, amount, total)
[ "def", "csv_row_to_transaction", "(", "index", ",", "row", ",", "source_encoding", "=", "\"latin1\"", ",", "date_format", "=", "\"%d-%m-%Y\"", ",", "thousand_sep", "=", "\".\"", ",", "decimal_sep", "=", "\",\"", ")", ":", "xfer", ",", "posted", ",", "message", ",", "amount", ",", "total", "=", "row", "xfer", "=", "Parse", ".", "date", "(", "xfer", ")", "posted", "=", "Parse", ".", "date", "(", "posted", ")", "message", "=", "Parse", ".", "to_utf8", "(", "message", ",", "source_encoding", ")", "amount", "=", "Parse", ".", "money", "(", "amount", ")", "total", "=", "Parse", ".", "money", "(", "total", ")", "return", "Transaction", "(", "index", ",", "xfer", ",", "posted", ",", "message", ",", "amount", ",", "total", ")" ]
Parses a row of strings to a ``Transaction`` object. Args: index: The index of this row in the original CSV file. Used for sorting ``Transaction``s by their order of appearance. row: The row containing strings for [transfer_date, posted_date, message, money_amount, money_total]. source_encoding: The encoding that will be used to decode strings to UTF-8. date_format: The format of dates in this row. thousand_sep: The thousand separator in money amounts. decimal_sep: The decimal separator in money amounts. Returns: A ``Transaction`` object.
[ "Parses", "a", "row", "of", "strings", "to", "a", "Transaction", "object", "." ]
4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L70-L101
238,850
cslarsen/elv
elv/elv.py
Parse.csv_to_transactions
def csv_to_transactions(handle, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses CSV data from stream and returns ``Transactions``. Args: index: The index of this row in the original CSV file. Used for sorting ``Transaction``s by their order of appearance. row: The row containing strings for [transfer_date, posted_date, message, money_amount, money_total]. source_encoding: The encoding that will be used to decode strings to UTF-8. date_format: The format of dates in this row. thousand_sep: The thousand separator in money amounts. decimal_sep: The decimal separator in money amounts. Returns: A ``Transactions`` object. """ trans = Transactions() rows = csv.reader(handle, delimiter=";", quotechar="\"") for index, row in enumerate(rows): trans.append(Parse.csv_row_to_transaction(index, row)) return trans
python
def csv_to_transactions(handle, source_encoding="latin1", date_format="%d-%m-%Y", thousand_sep=".", decimal_sep=","): """ Parses CSV data from stream and returns ``Transactions``. Args: index: The index of this row in the original CSV file. Used for sorting ``Transaction``s by their order of appearance. row: The row containing strings for [transfer_date, posted_date, message, money_amount, money_total]. source_encoding: The encoding that will be used to decode strings to UTF-8. date_format: The format of dates in this row. thousand_sep: The thousand separator in money amounts. decimal_sep: The decimal separator in money amounts. Returns: A ``Transactions`` object. """ trans = Transactions() rows = csv.reader(handle, delimiter=";", quotechar="\"") for index, row in enumerate(rows): trans.append(Parse.csv_row_to_transaction(index, row)) return trans
[ "def", "csv_to_transactions", "(", "handle", ",", "source_encoding", "=", "\"latin1\"", ",", "date_format", "=", "\"%d-%m-%Y\"", ",", "thousand_sep", "=", "\".\"", ",", "decimal_sep", "=", "\",\"", ")", ":", "trans", "=", "Transactions", "(", ")", "rows", "=", "csv", ".", "reader", "(", "handle", ",", "delimiter", "=", "\";\"", ",", "quotechar", "=", "\"\\\"\"", ")", "for", "index", ",", "row", "in", "enumerate", "(", "rows", ")", ":", "trans", ".", "append", "(", "Parse", ".", "csv_row_to_transaction", "(", "index", ",", "row", ")", ")", "return", "trans" ]
Parses CSV data from stream and returns ``Transactions``. Args: index: The index of this row in the original CSV file. Used for sorting ``Transaction``s by their order of appearance. row: The row containing strings for [transfer_date, posted_date, message, money_amount, money_total]. source_encoding: The encoding that will be used to decode strings to UTF-8. date_format: The format of dates in this row. thousand_sep: The thousand separator in money amounts. decimal_sep: The decimal separator in money amounts. Returns: A ``Transactions`` object.
[ "Parses", "CSV", "data", "from", "stream", "and", "returns", "Transactions", "." ]
4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L104-L134
238,851
cslarsen/elv
elv/elv.py
Transactions.to_sqlite3
def to_sqlite3(self, location=":memory:"): """Returns an SQLITE3 connection to a database containing the transactions.""" def decimal_to_sqlite3(n): return int(100*n) def sqlite3_to_decimal(s): return Decimal(s)/100 sqlite3.register_adapter(Decimal, decimal_to_sqlite3) sqlite3.register_converter("decimal", sqlite3_to_decimal) con = sqlite3.connect(location, detect_types=sqlite3.PARSE_COLNAMES | sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute("""create table transactions( id primary key, xfer date, posted date, message text, amount decimal, total decimal)""") for t in self: cur.execute("INSERT INTO transactions values(?,?,?,?,?,?)", (t.index, t.xfer, t.posted, t.message, t.amount, t.total)) return con
python
def to_sqlite3(self, location=":memory:"): """Returns an SQLITE3 connection to a database containing the transactions.""" def decimal_to_sqlite3(n): return int(100*n) def sqlite3_to_decimal(s): return Decimal(s)/100 sqlite3.register_adapter(Decimal, decimal_to_sqlite3) sqlite3.register_converter("decimal", sqlite3_to_decimal) con = sqlite3.connect(location, detect_types=sqlite3.PARSE_COLNAMES | sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute("""create table transactions( id primary key, xfer date, posted date, message text, amount decimal, total decimal)""") for t in self: cur.execute("INSERT INTO transactions values(?,?,?,?,?,?)", (t.index, t.xfer, t.posted, t.message, t.amount, t.total)) return con
[ "def", "to_sqlite3", "(", "self", ",", "location", "=", "\":memory:\"", ")", ":", "def", "decimal_to_sqlite3", "(", "n", ")", ":", "return", "int", "(", "100", "*", "n", ")", "def", "sqlite3_to_decimal", "(", "s", ")", ":", "return", "Decimal", "(", "s", ")", "/", "100", "sqlite3", ".", "register_adapter", "(", "Decimal", ",", "decimal_to_sqlite3", ")", "sqlite3", ".", "register_converter", "(", "\"decimal\"", ",", "sqlite3_to_decimal", ")", "con", "=", "sqlite3", ".", "connect", "(", "location", ",", "detect_types", "=", "sqlite3", ".", "PARSE_COLNAMES", "|", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "con", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"\"\"create table transactions(\n id primary key,\n xfer date,\n posted date,\n message text,\n amount decimal,\n total decimal)\"\"\"", ")", "for", "t", "in", "self", ":", "cur", ".", "execute", "(", "\"INSERT INTO transactions values(?,?,?,?,?,?)\"", ",", "(", "t", ".", "index", ",", "t", ".", "xfer", ",", "t", ".", "posted", ",", "t", ".", "message", ",", "t", ".", "amount", ",", "t", ".", "total", ")", ")", "return", "con" ]
Returns an SQLITE3 connection to a database containing the transactions.
[ "Returns", "an", "SQLITE3", "connection", "to", "a", "database", "containing", "the", "transactions", "." ]
4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L286-L312
238,852
cslarsen/elv
elv/elv.py
Transactions.group_by
def group_by(self, key, field=lambda x: x.xfer): """Returns all transactions whose given ``field`` matches ``key``. Returns: A ``Transactions`` object. """ return Transactions([t for t in self.trans if field(t) == key])
python
def group_by(self, key, field=lambda x: x.xfer): """Returns all transactions whose given ``field`` matches ``key``. Returns: A ``Transactions`` object. """ return Transactions([t for t in self.trans if field(t) == key])
[ "def", "group_by", "(", "self", ",", "key", ",", "field", "=", "lambda", "x", ":", "x", ".", "xfer", ")", ":", "return", "Transactions", "(", "[", "t", "for", "t", "in", "self", ".", "trans", "if", "field", "(", "t", ")", "==", "key", "]", ")" ]
Returns all transactions whose given ``field`` matches ``key``. Returns: A ``Transactions`` object.
[ "Returns", "all", "transactions", "whose", "given", "field", "matches", "key", "." ]
4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L367-L373
238,853
cslarsen/elv
elv/elv.py
Transactions.range
def range(self, start_date=None, stop_date=None, field=lambda x: x.xfer): """Return a ``Transactions`` object in an inclusive date range. Args: start_date: A ``datetime.Date`` object that marks the inclusive start date for the range. stop_date: A ``datetime.Date`` object that marks the inclusive end date for the range. field: The field to compare start and end dates to. Default is the ``xfer`` field. Returns: A ``Transactions`` object. """ assert start_date <= stop_date, \ "Start date must be earlier than end date." out = Transactions() for t in self.trans: date = field(t) if (start_date is not None) and not (date >= start_date): continue if (stop_date is not None) and not (date <= stop_date): continue out.append(t) return out
python
def range(self, start_date=None, stop_date=None, field=lambda x: x.xfer): """Return a ``Transactions`` object in an inclusive date range. Args: start_date: A ``datetime.Date`` object that marks the inclusive start date for the range. stop_date: A ``datetime.Date`` object that marks the inclusive end date for the range. field: The field to compare start and end dates to. Default is the ``xfer`` field. Returns: A ``Transactions`` object. """ assert start_date <= stop_date, \ "Start date must be earlier than end date." out = Transactions() for t in self.trans: date = field(t) if (start_date is not None) and not (date >= start_date): continue if (stop_date is not None) and not (date <= stop_date): continue out.append(t) return out
[ "def", "range", "(", "self", ",", "start_date", "=", "None", ",", "stop_date", "=", "None", ",", "field", "=", "lambda", "x", ":", "x", ".", "xfer", ")", ":", "assert", "start_date", "<=", "stop_date", ",", "\"Start date must be earlier than end date.\"", "out", "=", "Transactions", "(", ")", "for", "t", "in", "self", ".", "trans", ":", "date", "=", "field", "(", "t", ")", "if", "(", "start_date", "is", "not", "None", ")", "and", "not", "(", "date", ">=", "start_date", ")", ":", "continue", "if", "(", "stop_date", "is", "not", "None", ")", "and", "not", "(", "date", "<=", "stop_date", ")", ":", "continue", "out", ".", "append", "(", "t", ")", "return", "out" ]
Return a ``Transactions`` object in an inclusive date range. Args: start_date: A ``datetime.Date`` object that marks the inclusive start date for the range. stop_date: A ``datetime.Date`` object that marks the inclusive end date for the range. field: The field to compare start and end dates to. Default is the ``xfer`` field. Returns: A ``Transactions`` object.
[ "Return", "a", "Transactions", "object", "in", "an", "inclusive", "date", "range", "." ]
4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097
https://github.com/cslarsen/elv/blob/4bacf2093a0dcbe6a2b4d79be0fe339bb2b99097/elv/elv.py#L398-L427
238,854
emilydolson/avida-spatial-tools
avidaspatial/utils.py
agg_grid
def agg_grid(grid, agg=None): """ Many functions return a 2d list with a complex data type in each cell. For instance, grids representing environments have a set of resources, while reading in multiple data files at once will yield a list containing the values for that cell from each file. In order to visualize these data types it is helpful to summarize the more complex data types with a single number. For instance, you might want to take the length of a resource set to see how many resource types are present. Alternately, you might want to take the mode of a list to see the most common phenotype in a cell. This function facilitates this analysis by calling the given aggregation function (agg) on each cell of the given grid and returning the result. agg - A function indicating how to summarize grid contents. Default: len. """ grid = deepcopy(grid) if agg is None: if type(grid[0][0]) is list and type(grid[0][0][0]) is str: agg = string_avg else: agg = mode for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = agg(grid[i][j]) return grid
python
def agg_grid(grid, agg=None): """ Many functions return a 2d list with a complex data type in each cell. For instance, grids representing environments have a set of resources, while reading in multiple data files at once will yield a list containing the values for that cell from each file. In order to visualize these data types it is helpful to summarize the more complex data types with a single number. For instance, you might want to take the length of a resource set to see how many resource types are present. Alternately, you might want to take the mode of a list to see the most common phenotype in a cell. This function facilitates this analysis by calling the given aggregation function (agg) on each cell of the given grid and returning the result. agg - A function indicating how to summarize grid contents. Default: len. """ grid = deepcopy(grid) if agg is None: if type(grid[0][0]) is list and type(grid[0][0][0]) is str: agg = string_avg else: agg = mode for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = agg(grid[i][j]) return grid
[ "def", "agg_grid", "(", "grid", ",", "agg", "=", "None", ")", ":", "grid", "=", "deepcopy", "(", "grid", ")", "if", "agg", "is", "None", ":", "if", "type", "(", "grid", "[", "0", "]", "[", "0", "]", ")", "is", "list", "and", "type", "(", "grid", "[", "0", "]", "[", "0", "]", "[", "0", "]", ")", "is", "str", ":", "agg", "=", "string_avg", "else", ":", "agg", "=", "mode", "for", "i", "in", "range", "(", "len", "(", "grid", ")", ")", ":", "for", "j", "in", "range", "(", "len", "(", "grid", "[", "i", "]", ")", ")", ":", "grid", "[", "i", "]", "[", "j", "]", "=", "agg", "(", "grid", "[", "i", "]", "[", "j", "]", ")", "return", "grid" ]
Many functions return a 2d list with a complex data type in each cell. For instance, grids representing environments have a set of resources, while reading in multiple data files at once will yield a list containing the values for that cell from each file. In order to visualize these data types it is helpful to summarize the more complex data types with a single number. For instance, you might want to take the length of a resource set to see how many resource types are present. Alternately, you might want to take the mode of a list to see the most common phenotype in a cell. This function facilitates this analysis by calling the given aggregation function (agg) on each cell of the given grid and returning the result. agg - A function indicating how to summarize grid contents. Default: len.
[ "Many", "functions", "return", "a", "2d", "list", "with", "a", "complex", "data", "type", "in", "each", "cell", ".", "For", "instance", "grids", "representing", "environments", "have", "a", "set", "of", "resources", "while", "reading", "in", "multiple", "data", "files", "at", "once", "will", "yield", "a", "list", "containing", "the", "values", "for", "that", "cell", "from", "each", "file", ".", "In", "order", "to", "visualize", "these", "data", "types", "it", "is", "helpful", "to", "summarize", "the", "more", "complex", "data", "types", "with", "a", "single", "number", ".", "For", "instance", "you", "might", "want", "to", "take", "the", "length", "of", "a", "resource", "set", "to", "see", "how", "many", "resource", "types", "are", "present", ".", "Alternately", "you", "might", "want", "to", "take", "the", "mode", "of", "a", "list", "to", "see", "the", "most", "common", "phenotype", "in", "a", "cell", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L66-L95
238,855
emilydolson/avida-spatial-tools
avidaspatial/utils.py
flatten_array
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
python
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
[ "def", "flatten_array", "(", "grid", ")", ":", "grid", "=", "[", "grid", "[", "i", "]", "[", "j", "]", "for", "i", "in", "range", "(", "len", "(", "grid", ")", ")", "for", "j", "in", "range", "(", "len", "(", "grid", "[", "i", "]", ")", ")", "]", "while", "type", "(", "grid", "[", "0", "]", ")", "is", "list", ":", "grid", "=", "flatten_array", "(", "grid", ")", "return", "grid" ]
Takes a multi-dimensional array and returns a 1 dimensional array with the same contents.
[ "Takes", "a", "multi", "-", "dimensional", "array", "and", "returns", "a", "1", "dimensional", "array", "with", "the", "same", "contents", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L113-L121
238,856
emilydolson/avida-spatial-tools
avidaspatial/utils.py
prepend_zeros_to_lists
def prepend_zeros_to_lists(ls): """ Takes a list of lists and appends 0s to the beggining of each sub_list until they are all the same length. Used for sign-extending binary numbers. """ longest = max([len(l) for l in ls]) for i in range(len(ls)): while len(ls[i]) < longest: ls[i].insert(0, "0")
python
def prepend_zeros_to_lists(ls): """ Takes a list of lists and appends 0s to the beggining of each sub_list until they are all the same length. Used for sign-extending binary numbers. """ longest = max([len(l) for l in ls]) for i in range(len(ls)): while len(ls[i]) < longest: ls[i].insert(0, "0")
[ "def", "prepend_zeros_to_lists", "(", "ls", ")", ":", "longest", "=", "max", "(", "[", "len", "(", "l", ")", "for", "l", "in", "ls", "]", ")", "for", "i", "in", "range", "(", "len", "(", "ls", ")", ")", ":", "while", "len", "(", "ls", "[", "i", "]", ")", "<", "longest", ":", "ls", "[", "i", "]", ".", "insert", "(", "0", ",", "\"0\"", ")" ]
Takes a list of lists and appends 0s to the beggining of each sub_list until they are all the same length. Used for sign-extending binary numbers.
[ "Takes", "a", "list", "of", "lists", "and", "appends", "0s", "to", "the", "beggining", "of", "each", "sub_list", "until", "they", "are", "all", "the", "same", "length", ".", "Used", "for", "sign", "-", "extending", "binary", "numbers", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L124-L133
238,857
emilydolson/avida-spatial-tools
avidaspatial/utils.py
squared_toroidal_dist
def squared_toroidal_dist(p1, p2, world_size=(60, 60)): """ Separated out because sqrt has a lot of overhead """ halfx = world_size[0]/2.0 if world_size[0] == world_size[1]: halfy = halfx else: halfy = world_size[1]/2.0 deltax = p1[0] - p2[0] if deltax < -halfx: deltax += world_size[0] elif deltax > halfx: deltax -= world_size[0] deltay = p1[1] - p2[1] if deltay < -halfy: deltay += world_size[1] elif deltay > halfy: deltay -= world_size[1] return deltax*deltax + deltay*deltay
python
def squared_toroidal_dist(p1, p2, world_size=(60, 60)): """ Separated out because sqrt has a lot of overhead """ halfx = world_size[0]/2.0 if world_size[0] == world_size[1]: halfy = halfx else: halfy = world_size[1]/2.0 deltax = p1[0] - p2[0] if deltax < -halfx: deltax += world_size[0] elif deltax > halfx: deltax -= world_size[0] deltay = p1[1] - p2[1] if deltay < -halfy: deltay += world_size[1] elif deltay > halfy: deltay -= world_size[1] return deltax*deltax + deltay*deltay
[ "def", "squared_toroidal_dist", "(", "p1", ",", "p2", ",", "world_size", "=", "(", "60", ",", "60", ")", ")", ":", "halfx", "=", "world_size", "[", "0", "]", "/", "2.0", "if", "world_size", "[", "0", "]", "==", "world_size", "[", "1", "]", ":", "halfy", "=", "halfx", "else", ":", "halfy", "=", "world_size", "[", "1", "]", "/", "2.0", "deltax", "=", "p1", "[", "0", "]", "-", "p2", "[", "0", "]", "if", "deltax", "<", "-", "halfx", ":", "deltax", "+=", "world_size", "[", "0", "]", "elif", "deltax", ">", "halfx", ":", "deltax", "-=", "world_size", "[", "0", "]", "deltay", "=", "p1", "[", "1", "]", "-", "p2", "[", "1", "]", "if", "deltay", "<", "-", "halfy", ":", "deltay", "+=", "world_size", "[", "1", "]", "elif", "deltay", ">", "halfy", ":", "deltay", "-=", "world_size", "[", "1", "]", "return", "deltax", "*", "deltax", "+", "deltay", "*", "deltay" ]
Separated out because sqrt has a lot of overhead
[ "Separated", "out", "because", "sqrt", "has", "a", "lot", "of", "overhead" ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L143-L165
238,858
emilydolson/avida-spatial-tools
avidaspatial/utils.py
phenotype_to_res_set
def phenotype_to_res_set(phenotype, resources): """ Converts a binary string to a set containing the resources indicated by the bits in the string. Inputs: phenotype - a binary string resources - a list of string indicating which resources correspond to which indices of the phenotype returns: A set of strings indicating resources """ assert(phenotype[0:2] == "0b") phenotype = phenotype[2:] # Fill in leading zeroes while len(phenotype) < len(resources): phenotype = "0" + phenotype res_set = set() for i in range(len(phenotype)): if phenotype[i] == "1": res_set.add(resources[i]) assert(phenotype.count("1") == len(res_set)) return res_set
python
def phenotype_to_res_set(phenotype, resources): """ Converts a binary string to a set containing the resources indicated by the bits in the string. Inputs: phenotype - a binary string resources - a list of string indicating which resources correspond to which indices of the phenotype returns: A set of strings indicating resources """ assert(phenotype[0:2] == "0b") phenotype = phenotype[2:] # Fill in leading zeroes while len(phenotype) < len(resources): phenotype = "0" + phenotype res_set = set() for i in range(len(phenotype)): if phenotype[i] == "1": res_set.add(resources[i]) assert(phenotype.count("1") == len(res_set)) return res_set
[ "def", "phenotype_to_res_set", "(", "phenotype", ",", "resources", ")", ":", "assert", "(", "phenotype", "[", "0", ":", "2", "]", "==", "\"0b\"", ")", "phenotype", "=", "phenotype", "[", "2", ":", "]", "# Fill in leading zeroes", "while", "len", "(", "phenotype", ")", "<", "len", "(", "resources", ")", ":", "phenotype", "=", "\"0\"", "+", "phenotype", "res_set", "=", "set", "(", ")", "for", "i", "in", "range", "(", "len", "(", "phenotype", ")", ")", ":", "if", "phenotype", "[", "i", "]", "==", "\"1\"", ":", "res_set", ".", "add", "(", "resources", "[", "i", "]", ")", "assert", "(", "phenotype", ".", "count", "(", "\"1\"", ")", "==", "len", "(", "res_set", ")", ")", "return", "res_set" ]
Converts a binary string to a set containing the resources indicated by the bits in the string. Inputs: phenotype - a binary string resources - a list of string indicating which resources correspond to which indices of the phenotype returns: A set of strings indicating resources
[ "Converts", "a", "binary", "string", "to", "a", "set", "containing", "the", "resources", "indicated", "by", "the", "bits", "in", "the", "string", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L217-L241
238,859
emilydolson/avida-spatial-tools
avidaspatial/utils.py
res_set_to_phenotype
def res_set_to_phenotype(res_set, full_list): """ Converts a set of strings indicating resources to a binary string where the positions of 1s indicate which resources are present. Inputs: res_set - a set of strings indicating which resources are present full_list - a list of strings indicating all resources which could could be present, and the order in which they should map to bits in the phenotype returns: A binary string """ full_list = list(full_list) phenotype = len(full_list) * ["0"] for i in range(len(full_list)): if full_list[i] in res_set: phenotype[i] = "1" assert(phenotype.count("1") == len(res_set)) # Remove uneceesary leading 0s while phenotype[0] == "0" and len(phenotype) > 1: phenotype = phenotype[1:] return "0b"+"".join(phenotype)
python
def res_set_to_phenotype(res_set, full_list): """ Converts a set of strings indicating resources to a binary string where the positions of 1s indicate which resources are present. Inputs: res_set - a set of strings indicating which resources are present full_list - a list of strings indicating all resources which could could be present, and the order in which they should map to bits in the phenotype returns: A binary string """ full_list = list(full_list) phenotype = len(full_list) * ["0"] for i in range(len(full_list)): if full_list[i] in res_set: phenotype[i] = "1" assert(phenotype.count("1") == len(res_set)) # Remove uneceesary leading 0s while phenotype[0] == "0" and len(phenotype) > 1: phenotype = phenotype[1:] return "0b"+"".join(phenotype)
[ "def", "res_set_to_phenotype", "(", "res_set", ",", "full_list", ")", ":", "full_list", "=", "list", "(", "full_list", ")", "phenotype", "=", "len", "(", "full_list", ")", "*", "[", "\"0\"", "]", "for", "i", "in", "range", "(", "len", "(", "full_list", ")", ")", ":", "if", "full_list", "[", "i", "]", "in", "res_set", ":", "phenotype", "[", "i", "]", "=", "\"1\"", "assert", "(", "phenotype", ".", "count", "(", "\"1\"", ")", "==", "len", "(", "res_set", ")", ")", "# Remove uneceesary leading 0s", "while", "phenotype", "[", "0", "]", "==", "\"0\"", "and", "len", "(", "phenotype", ")", ">", "1", ":", "phenotype", "=", "phenotype", "[", "1", ":", "]", "return", "\"0b\"", "+", "\"\"", ".", "join", "(", "phenotype", ")" ]
Converts a set of strings indicating resources to a binary string where the positions of 1s indicate which resources are present. Inputs: res_set - a set of strings indicating which resources are present full_list - a list of strings indicating all resources which could could be present, and the order in which they should map to bits in the phenotype returns: A binary string
[ "Converts", "a", "set", "of", "strings", "indicating", "resources", "to", "a", "binary", "string", "where", "the", "positions", "of", "1s", "indicate", "which", "resources", "are", "present", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L244-L269
238,860
emilydolson/avida-spatial-tools
avidaspatial/utils.py
weighted_hamming
def weighted_hamming(b1, b2): """ Hamming distance that emphasizes differences earlier in strings. """ assert(len(b1) == len(b2)) hamming = 0 for i in range(len(b1)): if b1[i] != b2[i]: # differences at more significant (leftward) bits # are more important if i > 0: hamming += 1 + 1.0/i # This weighting is completely arbitrary return hamming
python
def weighted_hamming(b1, b2): """ Hamming distance that emphasizes differences earlier in strings. """ assert(len(b1) == len(b2)) hamming = 0 for i in range(len(b1)): if b1[i] != b2[i]: # differences at more significant (leftward) bits # are more important if i > 0: hamming += 1 + 1.0/i # This weighting is completely arbitrary return hamming
[ "def", "weighted_hamming", "(", "b1", ",", "b2", ")", ":", "assert", "(", "len", "(", "b1", ")", "==", "len", "(", "b2", ")", ")", "hamming", "=", "0", "for", "i", "in", "range", "(", "len", "(", "b1", ")", ")", ":", "if", "b1", "[", "i", "]", "!=", "b2", "[", "i", "]", ":", "# differences at more significant (leftward) bits", "# are more important", "if", "i", ">", "0", ":", "hamming", "+=", "1", "+", "1.0", "/", "i", "# This weighting is completely arbitrary", "return", "hamming" ]
Hamming distance that emphasizes differences earlier in strings.
[ "Hamming", "distance", "that", "emphasizes", "differences", "earlier", "in", "strings", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L272-L285
238,861
emilydolson/avida-spatial-tools
avidaspatial/utils.py
n_tasks
def n_tasks(dec_num): """ Takes a decimal number as input and returns the number of ones in the binary representation. This translates to the number of tasks being done by an organism with a phenotype represented as a decimal number. """ bitstring = "" try: bitstring = dec_num[2:] except: bitstring = bin(int(dec_num))[2:] # cut off 0b # print bin(int(dec_num)), bitstring return bitstring.count("1")
python
def n_tasks(dec_num): """ Takes a decimal number as input and returns the number of ones in the binary representation. This translates to the number of tasks being done by an organism with a phenotype represented as a decimal number. """ bitstring = "" try: bitstring = dec_num[2:] except: bitstring = bin(int(dec_num))[2:] # cut off 0b # print bin(int(dec_num)), bitstring return bitstring.count("1")
[ "def", "n_tasks", "(", "dec_num", ")", ":", "bitstring", "=", "\"\"", "try", ":", "bitstring", "=", "dec_num", "[", "2", ":", "]", "except", ":", "bitstring", "=", "bin", "(", "int", "(", "dec_num", ")", ")", "[", "2", ":", "]", "# cut off 0b", "# print bin(int(dec_num)), bitstring", "return", "bitstring", ".", "count", "(", "\"1\"", ")" ]
Takes a decimal number as input and returns the number of ones in the binary representation. This translates to the number of tasks being done by an organism with a phenotype represented as a decimal number.
[ "Takes", "a", "decimal", "number", "as", "input", "and", "returns", "the", "number", "of", "ones", "in", "the", "binary", "representation", ".", "This", "translates", "to", "the", "number", "of", "tasks", "being", "done", "by", "an", "organism", "with", "a", "phenotype", "represented", "as", "a", "decimal", "number", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L288-L301
238,862
emilydolson/avida-spatial-tools
avidaspatial/utils.py
convert_to_pysal
def convert_to_pysal(data): """ Pysal expects a distance matrix, and data formatted in a numpy array. This functions takes a data grid and returns those things. """ w = pysal.lat2W(len(data[0]), len(data)) data = np.array(data) data = np.reshape(data, (len(data)*len(data[0]), 1)) return w, data
python
def convert_to_pysal(data): """ Pysal expects a distance matrix, and data formatted in a numpy array. This functions takes a data grid and returns those things. """ w = pysal.lat2W(len(data[0]), len(data)) data = np.array(data) data = np.reshape(data, (len(data)*len(data[0]), 1)) return w, data
[ "def", "convert_to_pysal", "(", "data", ")", ":", "w", "=", "pysal", ".", "lat2W", "(", "len", "(", "data", "[", "0", "]", ")", ",", "len", "(", "data", ")", ")", "data", "=", "np", ".", "array", "(", "data", ")", "data", "=", "np", ".", "reshape", "(", "data", ",", "(", "len", "(", "data", ")", "*", "len", "(", "data", "[", "0", "]", ")", ",", "1", ")", ")", "return", "w", ",", "data" ]
Pysal expects a distance matrix, and data formatted in a numpy array. This functions takes a data grid and returns those things.
[ "Pysal", "expects", "a", "distance", "matrix", "and", "data", "formatted", "in", "a", "numpy", "array", ".", "This", "functions", "takes", "a", "data", "grid", "and", "returns", "those", "things", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L304-L312
238,863
emilydolson/avida-spatial-tools
avidaspatial/utils.py
median
def median(ls): """ Takes a list and returns the median. """ ls = sorted(ls) return ls[int(floor(len(ls)/2.0))]
python
def median(ls): """ Takes a list and returns the median. """ ls = sorted(ls) return ls[int(floor(len(ls)/2.0))]
[ "def", "median", "(", "ls", ")", ":", "ls", "=", "sorted", "(", "ls", ")", "return", "ls", "[", "int", "(", "floor", "(", "len", "(", "ls", ")", "/", "2.0", ")", ")", "]" ]
Takes a list and returns the median.
[ "Takes", "a", "list", "and", "returns", "the", "median", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L333-L338
238,864
emilydolson/avida-spatial-tools
avidaspatial/utils.py
string_avg
def string_avg(strings, binary=True): """ Takes a list of strings of equal length and returns a string containing the most common value from each index in the string. Optional argument: binary - a boolean indicating whether or not to treat strings as binary numbers (fill in leading zeros if lengths differ). """ if binary: # Assume this is a binary number and fill leading zeros strings = deepcopy(strings) longest = len(max(strings, key=len)) for i in range(len(strings)): while len(strings[i]) < longest: split_string = strings[i].split("b") strings[i] = "0b0" + split_string[1] avg = "" for i in (range(len(strings[0]))): opts = [] for s in strings: opts.append(s[i]) avg += max(set(opts), key=opts.count) return avg
python
def string_avg(strings, binary=True): """ Takes a list of strings of equal length and returns a string containing the most common value from each index in the string. Optional argument: binary - a boolean indicating whether or not to treat strings as binary numbers (fill in leading zeros if lengths differ). """ if binary: # Assume this is a binary number and fill leading zeros strings = deepcopy(strings) longest = len(max(strings, key=len)) for i in range(len(strings)): while len(strings[i]) < longest: split_string = strings[i].split("b") strings[i] = "0b0" + split_string[1] avg = "" for i in (range(len(strings[0]))): opts = [] for s in strings: opts.append(s[i]) avg += max(set(opts), key=opts.count) return avg
[ "def", "string_avg", "(", "strings", ",", "binary", "=", "True", ")", ":", "if", "binary", ":", "# Assume this is a binary number and fill leading zeros", "strings", "=", "deepcopy", "(", "strings", ")", "longest", "=", "len", "(", "max", "(", "strings", ",", "key", "=", "len", ")", ")", "for", "i", "in", "range", "(", "len", "(", "strings", ")", ")", ":", "while", "len", "(", "strings", "[", "i", "]", ")", "<", "longest", ":", "split_string", "=", "strings", "[", "i", "]", ".", "split", "(", "\"b\"", ")", "strings", "[", "i", "]", "=", "\"0b0\"", "+", "split_string", "[", "1", "]", "avg", "=", "\"\"", "for", "i", "in", "(", "range", "(", "len", "(", "strings", "[", "0", "]", ")", ")", ")", ":", "opts", "=", "[", "]", "for", "s", "in", "strings", ":", "opts", ".", "append", "(", "s", "[", "i", "]", ")", "avg", "+=", "max", "(", "set", "(", "opts", ")", ",", "key", "=", "opts", ".", "count", ")", "return", "avg" ]
Takes a list of strings of equal length and returns a string containing the most common value from each index in the string. Optional argument: binary - a boolean indicating whether or not to treat strings as binary numbers (fill in leading zeros if lengths differ).
[ "Takes", "a", "list", "of", "strings", "of", "equal", "length", "and", "returns", "a", "string", "containing", "the", "most", "common", "value", "from", "each", "index", "in", "the", "string", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L341-L366
238,865
emilydolson/avida-spatial-tools
avidaspatial/utils.py
get_world_dimensions
def get_world_dimensions(gridfile, delim=" "): """ This function takes the name of a file in grid_task format and returns the dimensions of the world it represents. """ infile = open(gridfile) lines = infile.readlines() infile.close() world_x = len(lines[0].strip().split(delim)) world_y = len(lines) return (world_x, world_y)
python
def get_world_dimensions(gridfile, delim=" "): """ This function takes the name of a file in grid_task format and returns the dimensions of the world it represents. """ infile = open(gridfile) lines = infile.readlines() infile.close() world_x = len(lines[0].strip().split(delim)) world_y = len(lines) return (world_x, world_y)
[ "def", "get_world_dimensions", "(", "gridfile", ",", "delim", "=", "\" \"", ")", ":", "infile", "=", "open", "(", "gridfile", ")", "lines", "=", "infile", ".", "readlines", "(", ")", "infile", ".", "close", "(", ")", "world_x", "=", "len", "(", "lines", "[", "0", "]", ".", "strip", "(", ")", ".", "split", "(", "delim", ")", ")", "world_y", "=", "len", "(", "lines", ")", "return", "(", "world_x", ",", "world_y", ")" ]
This function takes the name of a file in grid_task format and returns the dimensions of the world it represents.
[ "This", "function", "takes", "the", "name", "of", "a", "file", "in", "grid_task", "format", "and", "returns", "the", "dimensions", "of", "the", "world", "it", "represents", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L369-L379
238,866
Carreau/Love
love/flit.py
modify_config
def modify_config(path): """ Context manager to modify a flit config file. Will read the config file, validate the config, yield the config object, validate and write back the config to the file on exit """ if isinstance(path, str): path = Path(path) config = _read_pkg_ini(path) _validate_config(config, path) # don't catch exception, we won't write the new config. yield config _validate_config(config, path) with path.open('w') as f: config.write(f)
python
def modify_config(path): """ Context manager to modify a flit config file. Will read the config file, validate the config, yield the config object, validate and write back the config to the file on exit """ if isinstance(path, str): path = Path(path) config = _read_pkg_ini(path) _validate_config(config, path) # don't catch exception, we won't write the new config. yield config _validate_config(config, path) with path.open('w') as f: config.write(f)
[ "def", "modify_config", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "str", ")", ":", "path", "=", "Path", "(", "path", ")", "config", "=", "_read_pkg_ini", "(", "path", ")", "_validate_config", "(", "config", ",", "path", ")", "# don't catch exception, we won't write the new config.", "yield", "config", "_validate_config", "(", "config", ",", "path", ")", "with", "path", ".", "open", "(", "'w'", ")", "as", "f", ":", "config", ".", "write", "(", "f", ")" ]
Context manager to modify a flit config file. Will read the config file, validate the config, yield the config object, validate and write back the config to the file on exit
[ "Context", "manager", "to", "modify", "a", "flit", "config", "file", "." ]
a85d1139b32ee926b3bee73447e32e89b86983ba
https://github.com/Carreau/Love/blob/a85d1139b32ee926b3bee73447e32e89b86983ba/love/flit.py#L11-L28
238,867
6809/dragonlib
dragonlib/core/basic_parser.py
ParsedBASIC.pformat
def pformat(self): ''' Manually pformat to force using """...""" and supress escaping apostrophe ''' result = "{\n" indent1 = " " * 4 indent2 = " " * 8 for line_no, code_objects in sorted(self.items()): result += '%s%i: [\n' % (indent1, line_no) for code_object in code_objects: result += '%s"""<%s:%s>""",\n' % ( indent2, code_object.PART_TYPE, code_object.content ) result += '%s],\n' % indent1 result += "}" return result
python
def pformat(self): ''' Manually pformat to force using """...""" and supress escaping apostrophe ''' result = "{\n" indent1 = " " * 4 indent2 = " " * 8 for line_no, code_objects in sorted(self.items()): result += '%s%i: [\n' % (indent1, line_no) for code_object in code_objects: result += '%s"""<%s:%s>""",\n' % ( indent2, code_object.PART_TYPE, code_object.content ) result += '%s],\n' % indent1 result += "}" return result
[ "def", "pformat", "(", "self", ")", ":", "result", "=", "\"{\\n\"", "indent1", "=", "\" \"", "*", "4", "indent2", "=", "\" \"", "*", "8", "for", "line_no", ",", "code_objects", "in", "sorted", "(", "self", ".", "items", "(", ")", ")", ":", "result", "+=", "'%s%i: [\\n'", "%", "(", "indent1", ",", "line_no", ")", "for", "code_object", "in", "code_objects", ":", "result", "+=", "'%s\"\"\"<%s:%s>\"\"\",\\n'", "%", "(", "indent2", ",", "code_object", ".", "PART_TYPE", ",", "code_object", ".", "content", ")", "result", "+=", "'%s],\\n'", "%", "indent1", "result", "+=", "\"}\"", "return", "result" ]
Manually pformat to force using """...""" and supress escaping apostrophe
[ "Manually", "pformat", "to", "force", "using", "...", "and", "supress", "escaping", "apostrophe" ]
faa4011e76c5857db96efdb4199e2fd49711e999
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic_parser.py#L65-L81
238,868
6809/dragonlib
dragonlib/core/basic_parser.py
BASICParser._parse_string
def _parse_string(self, line): """ Consume the complete string until next " or \n """ log.debug("*** parse STRING: >>>%r<<<", line) parts = self.regex_split_string.split(line, maxsplit=1) if len(parts) == 1: # end return parts[0], None pre, match, post = parts log.debug("\tpre: >>>%r<<<", pre) log.debug("\tmatch: >>>%r<<<", match) log.debug("\tpost: >>>%r<<<", post) pre = pre + match log.debug("Parse string result: %r,%r", pre, post) return pre, post
python
def _parse_string(self, line): """ Consume the complete string until next " or \n """ log.debug("*** parse STRING: >>>%r<<<", line) parts = self.regex_split_string.split(line, maxsplit=1) if len(parts) == 1: # end return parts[0], None pre, match, post = parts log.debug("\tpre: >>>%r<<<", pre) log.debug("\tmatch: >>>%r<<<", match) log.debug("\tpost: >>>%r<<<", post) pre = pre + match log.debug("Parse string result: %r,%r", pre, post) return pre, post
[ "def", "_parse_string", "(", "self", ",", "line", ")", ":", "log", ".", "debug", "(", "\"*** parse STRING: >>>%r<<<\"", ",", "line", ")", "parts", "=", "self", ".", "regex_split_string", ".", "split", "(", "line", ",", "maxsplit", "=", "1", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "# end", "return", "parts", "[", "0", "]", ",", "None", "pre", ",", "match", ",", "post", "=", "parts", "log", ".", "debug", "(", "\"\\tpre: >>>%r<<<\"", ",", "pre", ")", "log", ".", "debug", "(", "\"\\tmatch: >>>%r<<<\"", ",", "match", ")", "log", ".", "debug", "(", "\"\\tpost: >>>%r<<<\"", ",", "post", ")", "pre", "=", "pre", "+", "match", "log", ".", "debug", "(", "\"Parse string result: %r,%r\"", ",", "pre", ",", "post", ")", "return", "pre", ",", "post" ]
Consume the complete string until next " or \n
[ "Consume", "the", "complete", "string", "until", "next", "or", "\\", "n" ]
faa4011e76c5857db96efdb4199e2fd49711e999
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic_parser.py#L162-L177
238,869
6809/dragonlib
dragonlib/core/basic_parser.py
BASICParser._parse_code
def _parse_code(self, line): """ parse the given BASIC line and branch into DATA, String and consume a complete Comment """ log.debug("*** parse CODE: >>>%r<<<", line) parts = self.regex_split_all.split(line, maxsplit=1) if len(parts) == 1: # end self.line_data.append(BASIC_Code(parts[0])) return pre, match, post = parts log.debug("\tpre: >>>%r<<<", pre) log.debug("\tmatch: >>>%r<<<", match) log.debug("\tpost: >>>%r<<<", post) if match == '"': log.debug("%r --> parse STRING", match) self.line_data.append(BASIC_Code(pre)) string_part, rest = self._parse_string(post) self.line_data.append(BASIC_String(match + string_part)) if rest: self._parse_code(rest) return self.line_data.append(BASIC_Code(pre + match)) if match == "DATA": log.debug("%r --> parse DATA", match) data_part, rest = self._parse_data(post) self.line_data.append(BASIC_Data(data_part)) if rest: self._parse_code(rest) return elif match in ("'", "REM"): log.debug("%r --> consume rest of the line as COMMENT", match) if post: self.line_data.append(BASIC_Comment(post)) return raise RuntimeError("Wrong Reg.Exp.? match is: %r" % match)
python
def _parse_code(self, line): """ parse the given BASIC line and branch into DATA, String and consume a complete Comment """ log.debug("*** parse CODE: >>>%r<<<", line) parts = self.regex_split_all.split(line, maxsplit=1) if len(parts) == 1: # end self.line_data.append(BASIC_Code(parts[0])) return pre, match, post = parts log.debug("\tpre: >>>%r<<<", pre) log.debug("\tmatch: >>>%r<<<", match) log.debug("\tpost: >>>%r<<<", post) if match == '"': log.debug("%r --> parse STRING", match) self.line_data.append(BASIC_Code(pre)) string_part, rest = self._parse_string(post) self.line_data.append(BASIC_String(match + string_part)) if rest: self._parse_code(rest) return self.line_data.append(BASIC_Code(pre + match)) if match == "DATA": log.debug("%r --> parse DATA", match) data_part, rest = self._parse_data(post) self.line_data.append(BASIC_Data(data_part)) if rest: self._parse_code(rest) return elif match in ("'", "REM"): log.debug("%r --> consume rest of the line as COMMENT", match) if post: self.line_data.append(BASIC_Comment(post)) return raise RuntimeError("Wrong Reg.Exp.? match is: %r" % match)
[ "def", "_parse_code", "(", "self", ",", "line", ")", ":", "log", ".", "debug", "(", "\"*** parse CODE: >>>%r<<<\"", ",", "line", ")", "parts", "=", "self", ".", "regex_split_all", ".", "split", "(", "line", ",", "maxsplit", "=", "1", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "# end", "self", ".", "line_data", ".", "append", "(", "BASIC_Code", "(", "parts", "[", "0", "]", ")", ")", "return", "pre", ",", "match", ",", "post", "=", "parts", "log", ".", "debug", "(", "\"\\tpre: >>>%r<<<\"", ",", "pre", ")", "log", ".", "debug", "(", "\"\\tmatch: >>>%r<<<\"", ",", "match", ")", "log", ".", "debug", "(", "\"\\tpost: >>>%r<<<\"", ",", "post", ")", "if", "match", "==", "'\"'", ":", "log", ".", "debug", "(", "\"%r --> parse STRING\"", ",", "match", ")", "self", ".", "line_data", ".", "append", "(", "BASIC_Code", "(", "pre", ")", ")", "string_part", ",", "rest", "=", "self", ".", "_parse_string", "(", "post", ")", "self", ".", "line_data", ".", "append", "(", "BASIC_String", "(", "match", "+", "string_part", ")", ")", "if", "rest", ":", "self", ".", "_parse_code", "(", "rest", ")", "return", "self", ".", "line_data", ".", "append", "(", "BASIC_Code", "(", "pre", "+", "match", ")", ")", "if", "match", "==", "\"DATA\"", ":", "log", ".", "debug", "(", "\"%r --> parse DATA\"", ",", "match", ")", "data_part", ",", "rest", "=", "self", ".", "_parse_data", "(", "post", ")", "self", ".", "line_data", ".", "append", "(", "BASIC_Data", "(", "data_part", ")", ")", "if", "rest", ":", "self", ".", "_parse_code", "(", "rest", ")", "return", "elif", "match", "in", "(", "\"'\"", ",", "\"REM\"", ")", ":", "log", ".", "debug", "(", "\"%r --> consume rest of the line as COMMENT\"", ",", "match", ")", "if", "post", ":", "self", ".", "line_data", ".", "append", "(", "BASIC_Comment", "(", "post", ")", ")", "return", "raise", "RuntimeError", "(", "\"Wrong Reg.Exp.? match is: %r\"", "%", "match", ")" ]
parse the given BASIC line and branch into DATA, String and consume a complete Comment
[ "parse", "the", "given", "BASIC", "line", "and", "branch", "into", "DATA", "String", "and", "consume", "a", "complete", "Comment" ]
faa4011e76c5857db96efdb4199e2fd49711e999
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic_parser.py#L179-L218
238,870
pip-services3-python/pip-services3-commons-python
pip_services3_commons/run/Closer.py
Closer.close
def close(correlation_id, components): """ Closes multiple components. To be closed components must implement [[ICloseable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed. """ if components == None: return for component in components: Closer.close_one(correlation_id, component)
python
def close(correlation_id, components): """ Closes multiple components. To be closed components must implement [[ICloseable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed. """ if components == None: return for component in components: Closer.close_one(correlation_id, component)
[ "def", "close", "(", "correlation_id", ",", "components", ")", ":", "if", "components", "==", "None", ":", "return", "for", "component", "in", "components", ":", "Closer", ".", "close_one", "(", "correlation_id", ",", "component", ")" ]
Closes multiple components. To be closed components must implement [[ICloseable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed.
[ "Closes", "multiple", "components", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/run/Closer.py#L35-L50
238,871
salsita/flask-ecstatic
flask_ecstatic.py
add
def add(app, url = None, path = None, endpoint=None, decorate=None, index='index.html', **options): """Adds static files endpoint with optional directory index.""" url = url or app.static_url_path or '' path = os.path.abspath(path or app.static_folder or '.') endpoint = endpoint or 'static_' + os.path.basename(path) decorate = decorate or (lambda f: f) endpoints = {} if path == app.static_folder: raise ValueError('Files in `{}` path are already automatically served on `{}` URL by Flask.' ' Set Flask app static_folder to None, if you want to serve them using Flask Ecstatic at `{}` URL' .format(path, app.static_url_path, url)) @app.route(url + '/<path:filename>', endpoint = endpoint) @handle404 @decorate def static_files(filename): if index: filename = safe_join(path, filename) if os.path.isdir(filename): filename = os.path.join(filename, index) return send_file(filename, **options) else: return send_from_directory(path, filename, **options) endpoints[endpoint] = static_files if index: @app.route(url + '/', endpoint = endpoint + '_index') @handle404 @decorate def static_index(): return send_from_directory(path, index, **options) endpoints[endpoint + '_index'] = static_index if url: @app.route(url, endpoint = endpoint + '_index_bare') @handle404 @decorate def static_index_bare(): return send_from_directory(path, index, **options) endpoints[endpoint + '_index_bare'] = static_index_bare return endpoints
python
def add(app, url = None, path = None, endpoint=None, decorate=None, index='index.html', **options): """Adds static files endpoint with optional directory index.""" url = url or app.static_url_path or '' path = os.path.abspath(path or app.static_folder or '.') endpoint = endpoint or 'static_' + os.path.basename(path) decorate = decorate or (lambda f: f) endpoints = {} if path == app.static_folder: raise ValueError('Files in `{}` path are already automatically served on `{}` URL by Flask.' ' Set Flask app static_folder to None, if you want to serve them using Flask Ecstatic at `{}` URL' .format(path, app.static_url_path, url)) @app.route(url + '/<path:filename>', endpoint = endpoint) @handle404 @decorate def static_files(filename): if index: filename = safe_join(path, filename) if os.path.isdir(filename): filename = os.path.join(filename, index) return send_file(filename, **options) else: return send_from_directory(path, filename, **options) endpoints[endpoint] = static_files if index: @app.route(url + '/', endpoint = endpoint + '_index') @handle404 @decorate def static_index(): return send_from_directory(path, index, **options) endpoints[endpoint + '_index'] = static_index if url: @app.route(url, endpoint = endpoint + '_index_bare') @handle404 @decorate def static_index_bare(): return send_from_directory(path, index, **options) endpoints[endpoint + '_index_bare'] = static_index_bare return endpoints
[ "def", "add", "(", "app", ",", "url", "=", "None", ",", "path", "=", "None", ",", "endpoint", "=", "None", ",", "decorate", "=", "None", ",", "index", "=", "'index.html'", ",", "*", "*", "options", ")", ":", "url", "=", "url", "or", "app", ".", "static_url_path", "or", "''", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", "or", "app", ".", "static_folder", "or", "'.'", ")", "endpoint", "=", "endpoint", "or", "'static_'", "+", "os", ".", "path", ".", "basename", "(", "path", ")", "decorate", "=", "decorate", "or", "(", "lambda", "f", ":", "f", ")", "endpoints", "=", "{", "}", "if", "path", "==", "app", ".", "static_folder", ":", "raise", "ValueError", "(", "'Files in `{}` path are already automatically served on `{}` URL by Flask.'", "' Set Flask app static_folder to None, if you want to serve them using Flask Ecstatic at `{}` URL'", ".", "format", "(", "path", ",", "app", ".", "static_url_path", ",", "url", ")", ")", "@", "app", ".", "route", "(", "url", "+", "'/<path:filename>'", ",", "endpoint", "=", "endpoint", ")", "@", "handle404", "@", "decorate", "def", "static_files", "(", "filename", ")", ":", "if", "index", ":", "filename", "=", "safe_join", "(", "path", ",", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "filename", ",", "index", ")", "return", "send_file", "(", "filename", ",", "*", "*", "options", ")", "else", ":", "return", "send_from_directory", "(", "path", ",", "filename", ",", "*", "*", "options", ")", "endpoints", "[", "endpoint", "]", "=", "static_files", "if", "index", ":", "@", "app", ".", "route", "(", "url", "+", "'/'", ",", "endpoint", "=", "endpoint", "+", "'_index'", ")", "@", "handle404", "@", "decorate", "def", "static_index", "(", ")", ":", "return", "send_from_directory", "(", "path", ",", "index", ",", "*", "*", "options", ")", "endpoints", "[", "endpoint", "+", "'_index'", "]", "=", "static_index", "if", "url", ":", "@", "app", ".", "route", "(", "url", ",", "endpoint", "=", "endpoint", "+", "'_index_bare'", ")", "@", "handle404", "@", "decorate", "def", "static_index_bare", "(", ")", ":", "return", "send_from_directory", "(", "path", ",", "index", ",", "*", "*", "options", ")", "endpoints", "[", "endpoint", "+", "'_index_bare'", "]", "=", "static_index_bare", "return", "endpoints" ]
Adds static files endpoint with optional directory index.
[ "Adds", "static", "files", "endpoint", "with", "optional", "directory", "index", "." ]
27f67f36eee3afe5855958e4187ff1268d7a5e69
https://github.com/salsita/flask-ecstatic/blob/27f67f36eee3afe5855958e4187ff1268d7a5e69/flask_ecstatic.py#L19-L65
238,872
6809/dragonlib
dragonlib/api.py
BaseAPI.program_dump2ascii_lines
def program_dump2ascii_lines(self, dump, program_start=None): """ convert a memory dump of a tokensized BASIC listing into ASCII listing list. """ dump = bytearray(dump) # assert isinstance(dump, bytearray) if program_start is None: program_start = self.DEFAULT_PROGRAM_START return self.listing.program_dump2ascii_lines(dump, program_start)
python
def program_dump2ascii_lines(self, dump, program_start=None): """ convert a memory dump of a tokensized BASIC listing into ASCII listing list. """ dump = bytearray(dump) # assert isinstance(dump, bytearray) if program_start is None: program_start = self.DEFAULT_PROGRAM_START return self.listing.program_dump2ascii_lines(dump, program_start)
[ "def", "program_dump2ascii_lines", "(", "self", ",", "dump", ",", "program_start", "=", "None", ")", ":", "dump", "=", "bytearray", "(", "dump", ")", "# assert isinstance(dump, bytearray)", "if", "program_start", "is", "None", ":", "program_start", "=", "self", ".", "DEFAULT_PROGRAM_START", "return", "self", ".", "listing", ".", "program_dump2ascii_lines", "(", "dump", ",", "program_start", ")" ]
convert a memory dump of a tokensized BASIC listing into ASCII listing list.
[ "convert", "a", "memory", "dump", "of", "a", "tokensized", "BASIC", "listing", "into", "ASCII", "listing", "list", "." ]
faa4011e76c5857db96efdb4199e2fd49711e999
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/api.py#L43-L53
238,873
6809/dragonlib
dragonlib/api.py
BaseAPI.ascii_listing2program_dump
def ascii_listing2program_dump(self, basic_program_ascii, program_start=None): """ convert a ASCII BASIC program listing into tokens. This tokens list can be used to insert it into the Emulator RAM. """ if program_start is None: program_start = self.DEFAULT_PROGRAM_START basic_lines = self.ascii_listing2basic_lines(basic_program_ascii, program_start) program_dump=self.listing.basic_lines2program_dump(basic_lines, program_start) assert isinstance(program_dump, bytearray), ( "is type: %s and not bytearray: %s" % (type(program_dump), repr(program_dump)) ) return program_dump
python
def ascii_listing2program_dump(self, basic_program_ascii, program_start=None): """ convert a ASCII BASIC program listing into tokens. This tokens list can be used to insert it into the Emulator RAM. """ if program_start is None: program_start = self.DEFAULT_PROGRAM_START basic_lines = self.ascii_listing2basic_lines(basic_program_ascii, program_start) program_dump=self.listing.basic_lines2program_dump(basic_lines, program_start) assert isinstance(program_dump, bytearray), ( "is type: %s and not bytearray: %s" % (type(program_dump), repr(program_dump)) ) return program_dump
[ "def", "ascii_listing2program_dump", "(", "self", ",", "basic_program_ascii", ",", "program_start", "=", "None", ")", ":", "if", "program_start", "is", "None", ":", "program_start", "=", "self", ".", "DEFAULT_PROGRAM_START", "basic_lines", "=", "self", ".", "ascii_listing2basic_lines", "(", "basic_program_ascii", ",", "program_start", ")", "program_dump", "=", "self", ".", "listing", ".", "basic_lines2program_dump", "(", "basic_lines", ",", "program_start", ")", "assert", "isinstance", "(", "program_dump", ",", "bytearray", ")", ",", "(", "\"is type: %s and not bytearray: %s\"", "%", "(", "type", "(", "program_dump", ")", ",", "repr", "(", "program_dump", ")", ")", ")", "return", "program_dump" ]
convert a ASCII BASIC program listing into tokens. This tokens list can be used to insert it into the Emulator RAM.
[ "convert", "a", "ASCII", "BASIC", "program", "listing", "into", "tokens", ".", "This", "tokens", "list", "can", "be", "used", "to", "insert", "it", "into", "the", "Emulator", "RAM", "." ]
faa4011e76c5857db96efdb4199e2fd49711e999
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/api.py#L76-L91
238,874
flo-compbio/goparser
goparser/annotation.py
GOAnnotation.get_gaf_format
def get_gaf_format(self): """Return a GAF 2.0-compatible string representation of the annotation. Parameters ---------- Returns ------- str The formatted string. """ sep = '\t' return sep.join( [self.gene, self.db_ref, self.term.id, self.evidence, '|'.join(self.db_ref), '|'.join(self.with_)])
python
def get_gaf_format(self): """Return a GAF 2.0-compatible string representation of the annotation. Parameters ---------- Returns ------- str The formatted string. """ sep = '\t' return sep.join( [self.gene, self.db_ref, self.term.id, self.evidence, '|'.join(self.db_ref), '|'.join(self.with_)])
[ "def", "get_gaf_format", "(", "self", ")", ":", "sep", "=", "'\\t'", "return", "sep", ".", "join", "(", "[", "self", ".", "gene", ",", "self", ".", "db_ref", ",", "self", ".", "term", ".", "id", ",", "self", ".", "evidence", ",", "'|'", ".", "join", "(", "self", ".", "db_ref", ")", ",", "'|'", ".", "join", "(", "self", ".", "with_", ")", "]", ")" ]
Return a GAF 2.0-compatible string representation of the annotation. Parameters ---------- Returns ------- str The formatted string.
[ "Return", "a", "GAF", "2", ".", "0", "-", "compatible", "string", "representation", "of", "the", "annotation", "." ]
5e27d7d04a26a70a1d9dc113357041abff72be3f
https://github.com/flo-compbio/goparser/blob/5e27d7d04a26a70a1d9dc113357041abff72be3f/goparser/annotation.py#L199-L213
238,875
twneale/hercules
hercules/stream.py
Stream.ahead
def ahead(self, i, j=None): '''Raising stopiteration with end the parse. ''' if j is None: return self._stream[self.i + i] else: return self._stream[self.i + i: self.i + j]
python
def ahead(self, i, j=None): '''Raising stopiteration with end the parse. ''' if j is None: return self._stream[self.i + i] else: return self._stream[self.i + i: self.i + j]
[ "def", "ahead", "(", "self", ",", "i", ",", "j", "=", "None", ")", ":", "if", "j", "is", "None", ":", "return", "self", ".", "_stream", "[", "self", ".", "i", "+", "i", "]", "else", ":", "return", "self", ".", "_stream", "[", "self", ".", "i", "+", "i", ":", "self", ".", "i", "+", "j", "]" ]
Raising stopiteration with end the parse.
[ "Raising", "stopiteration", "with", "end", "the", "parse", "." ]
cd61582ef7e593093e9b28b56798df4203d1467a
https://github.com/twneale/hercules/blob/cd61582ef7e593093e9b28b56798df4203d1467a/hercules/stream.py#L63-L69
238,876
genesluder/python-agiletixapi
agiletixapi/utils.py
method_name
def method_name(func): """Method wrapper that adds the name of the method being called to its arguments list in Pascal case """ @wraps(func) def _method_name(*args, **kwargs): name = to_pascal_case(func.__name__) return func(name=name, *args, **kwargs) return _method_name
python
def method_name(func): """Method wrapper that adds the name of the method being called to its arguments list in Pascal case """ @wraps(func) def _method_name(*args, **kwargs): name = to_pascal_case(func.__name__) return func(name=name, *args, **kwargs) return _method_name
[ "def", "method_name", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_method_name", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "to_pascal_case", "(", "func", ".", "__name__", ")", "return", "func", "(", "name", "=", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_method_name" ]
Method wrapper that adds the name of the method being called to its arguments list in Pascal case
[ "Method", "wrapper", "that", "adds", "the", "name", "of", "the", "method", "being", "called", "to", "its", "arguments", "list", "in", "Pascal", "case" ]
a7a3907414cd5623f4542b03cb970862368a894a
https://github.com/genesluder/python-agiletixapi/blob/a7a3907414cd5623f4542b03cb970862368a894a/agiletixapi/utils.py#L53-L61
238,877
genesluder/python-agiletixapi
agiletixapi/utils.py
to_pascal_case
def to_pascal_case(s): """Transform underscore separated string to pascal case """ return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())
python
def to_pascal_case(s): """Transform underscore separated string to pascal case """ return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize())
[ "def", "to_pascal_case", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "r'(?!^)_([a-zA-Z])'", ",", "lambda", "m", ":", "m", ".", "group", "(", "1", ")", ".", "upper", "(", ")", ",", "s", ".", "capitalize", "(", ")", ")" ]
Transform underscore separated string to pascal case
[ "Transform", "underscore", "separated", "string", "to", "pascal", "case" ]
a7a3907414cd5623f4542b03cb970862368a894a
https://github.com/genesluder/python-agiletixapi/blob/a7a3907414cd5623f4542b03cb970862368a894a/agiletixapi/utils.py#L79-L83
238,878
genesluder/python-agiletixapi
agiletixapi/utils.py
to_underscore
def to_underscore(s): """Transform camel or pascal case to underscore separated string """ return re.sub( r'(?!^)([A-Z]+)', lambda m: "_{0}".format(m.group(1).lower()), re.sub(r'(?!^)([A-Z]{1}[a-z]{1})', lambda m: "_{0}".format(m.group(1).lower()), s) ).lower()
python
def to_underscore(s): """Transform camel or pascal case to underscore separated string """ return re.sub( r'(?!^)([A-Z]+)', lambda m: "_{0}".format(m.group(1).lower()), re.sub(r'(?!^)([A-Z]{1}[a-z]{1})', lambda m: "_{0}".format(m.group(1).lower()), s) ).lower()
[ "def", "to_underscore", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "r'(?!^)([A-Z]+)'", ",", "lambda", "m", ":", "\"_{0}\"", ".", "format", "(", "m", ".", "group", "(", "1", ")", ".", "lower", "(", ")", ")", ",", "re", ".", "sub", "(", "r'(?!^)([A-Z]{1}[a-z]{1})'", ",", "lambda", "m", ":", "\"_{0}\"", ".", "format", "(", "m", ".", "group", "(", "1", ")", ".", "lower", "(", ")", ")", ",", "s", ")", ")", ".", "lower", "(", ")" ]
Transform camel or pascal case to underscore separated string
[ "Transform", "camel", "or", "pascal", "case", "to", "underscore", "separated", "string" ]
a7a3907414cd5623f4542b03cb970862368a894a
https://github.com/genesluder/python-agiletixapi/blob/a7a3907414cd5623f4542b03cb970862368a894a/agiletixapi/utils.py#L86-L94
238,879
pip-services3-python/pip-services3-commons-python
pip_services3_commons/commands/Event.py
Event.notify
def notify(self, correlation_id, args): """ Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with. """ for listener in self._listeners: try: listener.on_event(correlation_id, self, args) except Exception as ex: raise InvocationException( correlation_id, "EXEC_FAILED", "Raising event " + self._name + " failed: " + str(ex) ).with_details("event", self._name).wrap(ex)
python
def notify(self, correlation_id, args): """ Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with. """ for listener in self._listeners: try: listener.on_event(correlation_id, self, args) except Exception as ex: raise InvocationException( correlation_id, "EXEC_FAILED", "Raising event " + self._name + " failed: " + str(ex) ).with_details("event", self._name).wrap(ex)
[ "def", "notify", "(", "self", ",", "correlation_id", ",", "args", ")", ":", "for", "listener", "in", "self", ".", "_listeners", ":", "try", ":", "listener", ".", "on_event", "(", "correlation_id", ",", "self", ",", "args", ")", "except", "Exception", "as", "ex", ":", "raise", "InvocationException", "(", "correlation_id", ",", "\"EXEC_FAILED\"", ",", "\"Raising event \"", "+", "self", ".", "_name", "+", "\" failed: \"", "+", "str", "(", "ex", ")", ")", ".", "with_details", "(", "\"event\"", ",", "self", ".", "_name", ")", ".", "wrap", "(", "ex", ")" ]
Fires this event and notifies all registred listeners. :param correlation_id: (optional) transaction id to trace execution through call chain. :param args: the parameters to raise this event with.
[ "Fires", "this", "event", "and", "notifies", "all", "registred", "listeners", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/commands/Event.py#L79-L95
238,880
Bystroushaak/pyDHTMLParser
src/dhtmlparser/htmlelement/html_parser.py
HTMLParser._parseIsTag
def _parseIsTag(self): """ Detect whether the element is HTML tag or not. Result is saved to the :attr:`_istag` property. """ el = self._element self._istag = el and el[0] == "<" and el[-1] == ">"
python
def _parseIsTag(self): """ Detect whether the element is HTML tag or not. Result is saved to the :attr:`_istag` property. """ el = self._element self._istag = el and el[0] == "<" and el[-1] == ">"
[ "def", "_parseIsTag", "(", "self", ")", ":", "el", "=", "self", ".", "_element", "self", ".", "_istag", "=", "el", "and", "el", "[", "0", "]", "==", "\"<\"", "and", "el", "[", "-", "1", "]", "==", "\">\"" ]
Detect whether the element is HTML tag or not. Result is saved to the :attr:`_istag` property.
[ "Detect", "whether", "the", "element", "is", "HTML", "tag", "or", "not", "." ]
4756f93dd048500b038ece2323fe26e46b6bfdea
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L162-L169
238,881
Bystroushaak/pyDHTMLParser
src/dhtmlparser/htmlelement/html_parser.py
HTMLParser._parseIsComment
def _parseIsComment(self): """ Detect whether the element is HTML comment or not. Result is saved to the :attr:`_iscomment` property. """ self._iscomment = ( self._element.startswith("<!--") and self._element.endswith("-->") )
python
def _parseIsComment(self): """ Detect whether the element is HTML comment or not. Result is saved to the :attr:`_iscomment` property. """ self._iscomment = ( self._element.startswith("<!--") and self._element.endswith("-->") )
[ "def", "_parseIsComment", "(", "self", ")", ":", "self", ".", "_iscomment", "=", "(", "self", ".", "_element", ".", "startswith", "(", "\"<!--\"", ")", "and", "self", ".", "_element", ".", "endswith", "(", "\"-->\"", ")", ")" ]
Detect whether the element is HTML comment or not. Result is saved to the :attr:`_iscomment` property.
[ "Detect", "whether", "the", "element", "is", "HTML", "comment", "or", "not", "." ]
4756f93dd048500b038ece2323fe26e46b6bfdea
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L197-L205
238,882
Bystroushaak/pyDHTMLParser
src/dhtmlparser/htmlelement/html_parser.py
HTMLParser._parseTagName
def _parseTagName(self): """ Parse name of the tag. Result is saved to the :attr:`_tagname` property. """ for el in self._element.split(): el = el.replace("/", "").replace("<", "").replace(">", "") if el.strip(): self._tagname = el.rstrip() return
python
def _parseTagName(self): """ Parse name of the tag. Result is saved to the :attr:`_tagname` property. """ for el in self._element.split(): el = el.replace("/", "").replace("<", "").replace(">", "") if el.strip(): self._tagname = el.rstrip() return
[ "def", "_parseTagName", "(", "self", ")", ":", "for", "el", "in", "self", ".", "_element", ".", "split", "(", ")", ":", "el", "=", "el", ".", "replace", "(", "\"/\"", ",", "\"\"", ")", ".", "replace", "(", "\"<\"", ",", "\"\"", ")", ".", "replace", "(", "\">\"", ",", "\"\"", ")", "if", "el", ".", "strip", "(", ")", ":", "self", ".", "_tagname", "=", "el", ".", "rstrip", "(", ")", "return" ]
Parse name of the tag. Result is saved to the :attr:`_tagname` property.
[ "Parse", "name", "of", "the", "tag", "." ]
4756f93dd048500b038ece2323fe26e46b6bfdea
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L207-L218
238,883
Bystroushaak/pyDHTMLParser
src/dhtmlparser/htmlelement/html_parser.py
HTMLParser._parseParams
def _parseParams(self): """ Parse parameters from their string HTML representation to dictionary. Result is saved to the :attr:`params` property. """ # check if there are any parameters if " " not in self._element or "=" not in self._element: return # remove '<' & '>' params = self._element.strip()[1:-1].strip() # remove tagname offset = params.find(self.getTagName()) + len(self.getTagName()) params = params[offset:].strip() # parser machine next_state = 0 key = "" value = "" end_quote = "" buff = ["", ""] for c in params: if next_state == 0: # key if c.strip() != "": # safer than list space, tab and all if c == "=": # possible whitespaces in UTF next_state = 1 else: key += c elif next_state == 1: # value decisioner if c.strip() != "": # skip whitespaces if c == "'" or c == '"': next_state = 3 end_quote = c else: next_state = 2 value += c elif next_state == 2: # one word parameter without quotes if c.strip() == "": next_state = 0 self.params[key] = value key = "" value = "" else: value += c elif next_state == 3: # quoted string if c == end_quote and (buff[0] != "\\" or (buff[0]) == "\\" and buff[1] == "\\"): next_state = 0 self.params[key] = unescape(value, end_quote) key = "" value = "" end_quote = "" else: value += c buff = _rotate_buff(buff) buff[0] = c if key: if end_quote and value.strip(): self.params[key] = unescape(value, end_quote) else: self.params[key] = value if "/" in self.params.keys(): del self.params["/"] self._isnonpairtag = True
python
def _parseParams(self): """ Parse parameters from their string HTML representation to dictionary. Result is saved to the :attr:`params` property. """ # check if there are any parameters if " " not in self._element or "=" not in self._element: return # remove '<' & '>' params = self._element.strip()[1:-1].strip() # remove tagname offset = params.find(self.getTagName()) + len(self.getTagName()) params = params[offset:].strip() # parser machine next_state = 0 key = "" value = "" end_quote = "" buff = ["", ""] for c in params: if next_state == 0: # key if c.strip() != "": # safer than list space, tab and all if c == "=": # possible whitespaces in UTF next_state = 1 else: key += c elif next_state == 1: # value decisioner if c.strip() != "": # skip whitespaces if c == "'" or c == '"': next_state = 3 end_quote = c else: next_state = 2 value += c elif next_state == 2: # one word parameter without quotes if c.strip() == "": next_state = 0 self.params[key] = value key = "" value = "" else: value += c elif next_state == 3: # quoted string if c == end_quote and (buff[0] != "\\" or (buff[0]) == "\\" and buff[1] == "\\"): next_state = 0 self.params[key] = unescape(value, end_quote) key = "" value = "" end_quote = "" else: value += c buff = _rotate_buff(buff) buff[0] = c if key: if end_quote and value.strip(): self.params[key] = unescape(value, end_quote) else: self.params[key] = value if "/" in self.params.keys(): del self.params["/"] self._isnonpairtag = True
[ "def", "_parseParams", "(", "self", ")", ":", "# check if there are any parameters", "if", "\" \"", "not", "in", "self", ".", "_element", "or", "\"=\"", "not", "in", "self", ".", "_element", ":", "return", "# remove '<' & '>'", "params", "=", "self", ".", "_element", ".", "strip", "(", ")", "[", "1", ":", "-", "1", "]", ".", "strip", "(", ")", "# remove tagname", "offset", "=", "params", ".", "find", "(", "self", ".", "getTagName", "(", ")", ")", "+", "len", "(", "self", ".", "getTagName", "(", ")", ")", "params", "=", "params", "[", "offset", ":", "]", ".", "strip", "(", ")", "# parser machine", "next_state", "=", "0", "key", "=", "\"\"", "value", "=", "\"\"", "end_quote", "=", "\"\"", "buff", "=", "[", "\"\"", ",", "\"\"", "]", "for", "c", "in", "params", ":", "if", "next_state", "==", "0", ":", "# key", "if", "c", ".", "strip", "(", ")", "!=", "\"\"", ":", "# safer than list space, tab and all", "if", "c", "==", "\"=\"", ":", "# possible whitespaces in UTF", "next_state", "=", "1", "else", ":", "key", "+=", "c", "elif", "next_state", "==", "1", ":", "# value decisioner", "if", "c", ".", "strip", "(", ")", "!=", "\"\"", ":", "# skip whitespaces", "if", "c", "==", "\"'\"", "or", "c", "==", "'\"'", ":", "next_state", "=", "3", "end_quote", "=", "c", "else", ":", "next_state", "=", "2", "value", "+=", "c", "elif", "next_state", "==", "2", ":", "# one word parameter without quotes", "if", "c", ".", "strip", "(", ")", "==", "\"\"", ":", "next_state", "=", "0", "self", ".", "params", "[", "key", "]", "=", "value", "key", "=", "\"\"", "value", "=", "\"\"", "else", ":", "value", "+=", "c", "elif", "next_state", "==", "3", ":", "# quoted string", "if", "c", "==", "end_quote", "and", "(", "buff", "[", "0", "]", "!=", "\"\\\\\"", "or", "(", "buff", "[", "0", "]", ")", "==", "\"\\\\\"", "and", "buff", "[", "1", "]", "==", "\"\\\\\"", ")", ":", "next_state", "=", "0", "self", ".", "params", "[", "key", "]", "=", "unescape", "(", "value", ",", "end_quote", ")", "key", "=", "\"\"", "value", "=", "\"\"", "end_quote", "=", "\"\"", "else", ":", "value", "+=", "c", "buff", "=", "_rotate_buff", "(", "buff", ")", "buff", "[", "0", "]", "=", "c", "if", "key", ":", "if", "end_quote", "and", "value", ".", "strip", "(", ")", ":", "self", ".", "params", "[", "key", "]", "=", "unescape", "(", "value", ",", "end_quote", ")", "else", ":", "self", ".", "params", "[", "key", "]", "=", "value", "if", "\"/\"", "in", "self", ".", "params", ".", "keys", "(", ")", ":", "del", "self", ".", "params", "[", "\"/\"", "]", "self", ".", "_isnonpairtag", "=", "True" ]
Parse parameters from their string HTML representation to dictionary. Result is saved to the :attr:`params` property.
[ "Parse", "parameters", "from", "their", "string", "HTML", "representation", "to", "dictionary", "." ]
4756f93dd048500b038ece2323fe26e46b6bfdea
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L220-L290
238,884
Bystroushaak/pyDHTMLParser
src/dhtmlparser/htmlelement/html_parser.py
HTMLParser.isOpeningTag
def isOpeningTag(self): """ Detect whether this tag is opening or not. Returns: bool: True if it is opening. """ if self.isTag() and \ not self.isComment() and \ not self.isEndTag() and \ not self.isNonPairTag(): return True return False
python
def isOpeningTag(self): """ Detect whether this tag is opening or not. Returns: bool: True if it is opening. """ if self.isTag() and \ not self.isComment() and \ not self.isEndTag() and \ not self.isNonPairTag(): return True return False
[ "def", "isOpeningTag", "(", "self", ")", ":", "if", "self", ".", "isTag", "(", ")", "and", "not", "self", ".", "isComment", "(", ")", "and", "not", "self", ".", "isEndTag", "(", ")", "and", "not", "self", ".", "isNonPairTag", "(", ")", ":", "return", "True", "return", "False" ]
Detect whether this tag is opening or not. Returns: bool: True if it is opening.
[ "Detect", "whether", "this", "tag", "is", "opening", "or", "not", "." ]
4756f93dd048500b038ece2323fe26e46b6bfdea
https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L354-L367
238,885
emilydolson/avida-spatial-tools
avidaspatial/landscape_stats.py
entropy
def entropy(dictionary): """ Helper function for entropy calculations. Takes a frequency dictionary and calculates entropy of the keys. """ total = 0.0 entropy = 0 for key in dictionary.keys(): total += dictionary[key] for key in dictionary.keys(): entropy += dictionary[key]/total * log(1.0/(dictionary[key]/total), 2) return entropy
python
def entropy(dictionary): """ Helper function for entropy calculations. Takes a frequency dictionary and calculates entropy of the keys. """ total = 0.0 entropy = 0 for key in dictionary.keys(): total += dictionary[key] for key in dictionary.keys(): entropy += dictionary[key]/total * log(1.0/(dictionary[key]/total), 2) return entropy
[ "def", "entropy", "(", "dictionary", ")", ":", "total", "=", "0.0", "entropy", "=", "0", "for", "key", "in", "dictionary", ".", "keys", "(", ")", ":", "total", "+=", "dictionary", "[", "key", "]", "for", "key", "in", "dictionary", ".", "keys", "(", ")", ":", "entropy", "+=", "dictionary", "[", "key", "]", "/", "total", "*", "log", "(", "1.0", "/", "(", "dictionary", "[", "key", "]", "/", "total", ")", ",", "2", ")", "return", "entropy" ]
Helper function for entropy calculations. Takes a frequency dictionary and calculates entropy of the keys.
[ "Helper", "function", "for", "entropy", "calculations", ".", "Takes", "a", "frequency", "dictionary", "and", "calculates", "entropy", "of", "the", "keys", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/landscape_stats.py#L70-L82
238,886
emilydolson/avida-spatial-tools
avidaspatial/landscape_stats.py
sqrt_shannon_entropy
def sqrt_shannon_entropy(filename): """ Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability. """ data = load_grid_data(filename, "int") data = agg_grid(data, mode) phenotypes = {} for r in data: for c in r: if c in phenotypes: phenotypes[c] += 1 else: phenotypes[c] = 1 for key in phenotypes.keys(): phenotypes[key] = sqrt(phenotypes[key]) return entropy(phenotypes)
python
def sqrt_shannon_entropy(filename): """ Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability. """ data = load_grid_data(filename, "int") data = agg_grid(data, mode) phenotypes = {} for r in data: for c in r: if c in phenotypes: phenotypes[c] += 1 else: phenotypes[c] = 1 for key in phenotypes.keys(): phenotypes[key] = sqrt(phenotypes[key]) return entropy(phenotypes)
[ "def", "sqrt_shannon_entropy", "(", "filename", ")", ":", "data", "=", "load_grid_data", "(", "filename", ",", "\"int\"", ")", "data", "=", "agg_grid", "(", "data", ",", "mode", ")", "phenotypes", "=", "{", "}", "for", "r", "in", "data", ":", "for", "c", "in", "r", ":", "if", "c", "in", "phenotypes", ":", "phenotypes", "[", "c", "]", "+=", "1", "else", ":", "phenotypes", "[", "c", "]", "=", "1", "for", "key", "in", "phenotypes", ".", "keys", "(", ")", ":", "phenotypes", "[", "key", "]", "=", "sqrt", "(", "phenotypes", "[", "key", "]", ")", "return", "entropy", "(", "phenotypes", ")" ]
Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability.
[ "Calculates", "Shannon", "entropy", "based", "on", "square", "root", "of", "phenotype", "count", ".", "This", "might", "account", "for", "relationship", "between", "population", "size", "and", "evolvability", "." ]
7beb0166ccefad5fa722215b030ac2a53d62b59e
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/landscape_stats.py#L85-L104
238,887
quantopian/metautils
metautils/compat.py
_composed_doc
def _composed_doc(fs): """ Generate a docstring for the composition of fs. """ if not fs: # Argument name for the docstring. return 'n' return '{f}({g})'.format(f=fs[0].__name__, g=_composed_doc(fs[1:]))
python
def _composed_doc(fs): """ Generate a docstring for the composition of fs. """ if not fs: # Argument name for the docstring. return 'n' return '{f}({g})'.format(f=fs[0].__name__, g=_composed_doc(fs[1:]))
[ "def", "_composed_doc", "(", "fs", ")", ":", "if", "not", "fs", ":", "# Argument name for the docstring.", "return", "'n'", "return", "'{f}({g})'", ".", "format", "(", "f", "=", "fs", "[", "0", "]", ".", "__name__", ",", "g", "=", "_composed_doc", "(", "fs", "[", "1", ":", "]", ")", ")" ]
Generate a docstring for the composition of fs.
[ "Generate", "a", "docstring", "for", "the", "composition", "of", "fs", "." ]
10e11c5bd8bd7ded52b97261f61c3186607bd617
https://github.com/quantopian/metautils/blob/10e11c5bd8bd7ded52b97261f61c3186607bd617/metautils/compat.py#L61-L69
238,888
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/containers.py
StaticContainerAdapter.update_model
def update_model(self, idx=None): """Updates the value of property at given index. If idx is None, all controlled indices will be updated. This method should be called directly by the user in very unusual conditions.""" if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) try: val = self._read_widget(idx) except ValueError: pass else: self._write_property(val, idx) pass pass else: try: val = self._read_widget(idx) except ValueError: pass else: self._write_property(val, idx) return
python
def update_model(self, idx=None): """Updates the value of property at given index. If idx is None, all controlled indices will be updated. This method should be called directly by the user in very unusual conditions.""" if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) try: val = self._read_widget(idx) except ValueError: pass else: self._write_property(val, idx) pass pass else: try: val = self._read_widget(idx) except ValueError: pass else: self._write_property(val, idx) return
[ "def", "update_model", "(", "self", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "None", ":", "for", "w", "in", "self", ".", "_widgets", ":", "idx", "=", "self", ".", "_get_idx_from_widget", "(", "w", ")", "try", ":", "val", "=", "self", ".", "_read_widget", "(", "idx", ")", "except", "ValueError", ":", "pass", "else", ":", "self", ".", "_write_property", "(", "val", ",", "idx", ")", "pass", "pass", "else", ":", "try", ":", "val", "=", "self", ".", "_read_widget", "(", "idx", ")", "except", "ValueError", ":", "pass", "else", ":", "self", ".", "_write_property", "(", "val", ",", "idx", ")", "return" ]
Updates the value of property at given index. If idx is None, all controlled indices will be updated. This method should be called directly by the user in very unusual conditions.
[ "Updates", "the", "value", "of", "property", "at", "given", "index", ".", "If", "idx", "is", "None", "all", "controlled", "indices", "will", "be", "updated", ".", "This", "method", "should", "be", "called", "directly", "by", "the", "user", "in", "very", "unusual", "conditions", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L146-L163
238,889
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/containers.py
StaticContainerAdapter.update_widget
def update_widget(self, idx=None): """Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.""" if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) self._write_widget(self._read_property(idx), idx) pass else: self._write_widget(self._read_property(idx), idx) return
python
def update_widget(self, idx=None): """Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.""" if idx is None: for w in self._widgets: idx = self._get_idx_from_widget(w) self._write_widget(self._read_property(idx), idx) pass else: self._write_widget(self._read_property(idx), idx) return
[ "def", "update_widget", "(", "self", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "None", ":", "for", "w", "in", "self", ".", "_widgets", ":", "idx", "=", "self", ".", "_get_idx_from_widget", "(", "w", ")", "self", ".", "_write_widget", "(", "self", ".", "_read_property", "(", "idx", ")", ",", "idx", ")", "pass", "else", ":", "self", ".", "_write_widget", "(", "self", ".", "_read_property", "(", "idx", ")", ",", "idx", ")", "return" ]
Forces the widget at given index to be updated from the property value. If index is not given, all controlled widgets will be updated. This method should be called directly by the user when the property is not observable, or in very unusual conditions.
[ "Forces", "the", "widget", "at", "given", "index", "to", "be", "updated", "from", "the", "property", "value", ".", "If", "index", "is", "not", "given", "all", "controlled", "widgets", "will", "be", "updated", ".", "This", "method", "should", "be", "called", "directly", "by", "the", "user", "when", "the", "property", "is", "not", "observable", "or", "in", "very", "unusual", "conditions", "." ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L165-L177
238,890
roboogle/gtkmvc3
gtkmvco/gtkmvc3/adapters/containers.py
StaticContainerAdapter._on_wid_changed
def _on_wid_changed(self, wid): """Called when the widget is changed""" if self._itsme: return self.update_model(self._get_idx_from_widget(wid)) return
python
def _on_wid_changed(self, wid): """Called when the widget is changed""" if self._itsme: return self.update_model(self._get_idx_from_widget(wid)) return
[ "def", "_on_wid_changed", "(", "self", ",", "wid", ")", ":", "if", "self", ".", "_itsme", ":", "return", "self", ".", "update_model", "(", "self", ".", "_get_idx_from_widget", "(", "wid", ")", ")", "return" ]
Called when the widget is changed
[ "Called", "when", "the", "widget", "is", "changed" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/containers.py#L236-L240
238,891
lewiseason/rfc
rfc/cli.py
fetch_url
def fetch_url(url): """ Fetch the given url, strip formfeeds and decode it into the defined encoding """ with closing(urllib.urlopen(url)) as f: if f.code is 200: response = f.read() return strip_formfeeds(response).decode(ENCODING)
python
def fetch_url(url): """ Fetch the given url, strip formfeeds and decode it into the defined encoding """ with closing(urllib.urlopen(url)) as f: if f.code is 200: response = f.read() return strip_formfeeds(response).decode(ENCODING)
[ "def", "fetch_url", "(", "url", ")", ":", "with", "closing", "(", "urllib", ".", "urlopen", "(", "url", ")", ")", "as", "f", ":", "if", "f", ".", "code", "is", "200", ":", "response", "=", "f", ".", "read", "(", ")", "return", "strip_formfeeds", "(", "response", ")", ".", "decode", "(", "ENCODING", ")" ]
Fetch the given url, strip formfeeds and decode it into the defined encoding
[ "Fetch", "the", "given", "url", "strip", "formfeeds", "and", "decode", "it", "into", "the", "defined", "encoding" ]
2a322d8ab681ade0f3a8574c48d62505141082bf
https://github.com/lewiseason/rfc/blob/2a322d8ab681ade0f3a8574c48d62505141082bf/rfc/cli.py#L27-L36
238,892
ravenac95/overlay4u
overlay4u/mountutils.py
match_entry_line
def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ): """Does a regex match of the mount entry string""" match_obj = regex_obj.match(str_to_match) if not match_obj: error_message = ('Line "%s" is unrecognized by overlay4u. ' 'This is only meant for use with Ubuntu Linux.') raise UnrecognizedMountEntry(error_message % str_to_match) return match_obj.groupdict()
python
def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ): """Does a regex match of the mount entry string""" match_obj = regex_obj.match(str_to_match) if not match_obj: error_message = ('Line "%s" is unrecognized by overlay4u. ' 'This is only meant for use with Ubuntu Linux.') raise UnrecognizedMountEntry(error_message % str_to_match) return match_obj.groupdict()
[ "def", "match_entry_line", "(", "str_to_match", ",", "regex_obj", "=", "MAIN_REGEX_OBJ", ")", ":", "match_obj", "=", "regex_obj", ".", "match", "(", "str_to_match", ")", "if", "not", "match_obj", ":", "error_message", "=", "(", "'Line \"%s\" is unrecognized by overlay4u. '", "'This is only meant for use with Ubuntu Linux.'", ")", "raise", "UnrecognizedMountEntry", "(", "error_message", "%", "str_to_match", ")", "return", "match_obj", ".", "groupdict", "(", ")" ]
Does a regex match of the mount entry string
[ "Does", "a", "regex", "match", "of", "the", "mount", "entry", "string" ]
621eecc0d4d40951aa8afcb533b5eec5d91c73cc
https://github.com/ravenac95/overlay4u/blob/621eecc0d4d40951aa8afcb533b5eec5d91c73cc/overlay4u/mountutils.py#L9-L16
238,893
ravenac95/overlay4u
overlay4u/mountutils.py
MountTable.as_list
def as_list(self, fs_type=None): """List mount entries""" entries = self._entries if fs_type: entries = filter(lambda a: a.fs_type == fs_type, entries) return entries
python
def as_list(self, fs_type=None): """List mount entries""" entries = self._entries if fs_type: entries = filter(lambda a: a.fs_type == fs_type, entries) return entries
[ "def", "as_list", "(", "self", ",", "fs_type", "=", "None", ")", ":", "entries", "=", "self", ".", "_entries", "if", "fs_type", ":", "entries", "=", "filter", "(", "lambda", "a", ":", "a", ".", "fs_type", "==", "fs_type", ",", "entries", ")", "return", "entries" ]
List mount entries
[ "List", "mount", "entries" ]
621eecc0d4d40951aa8afcb533b5eec5d91c73cc
https://github.com/ravenac95/overlay4u/blob/621eecc0d4d40951aa8afcb533b5eec5d91c73cc/overlay4u/mountutils.py#L56-L61
238,894
majerteam/sqla_inspect
sqla_inspect/ods.py
OdsWriter.render
def render(self, f_buf=None): """ Definitely render the workbook :param obj f_buf: A file buffer supporting the write and seek methods """ if f_buf is None: f_buf = StringIO.StringIO() with odswriter.writer(f_buf) as writer: default_sheet = writer.new_sheet(self.title) self._render_headers(default_sheet) self._render_rows(default_sheet) # abstract_sheet require the same attributes as our current writer for abstract_sheet in self.sheets: sheet = writer.new_sheet(name=abstract_sheet.title) abstract_sheet._render_headers(sheet) abstract_sheet._render_rows(sheet) f_buf.seek(0) return f_buf
python
def render(self, f_buf=None): """ Definitely render the workbook :param obj f_buf: A file buffer supporting the write and seek methods """ if f_buf is None: f_buf = StringIO.StringIO() with odswriter.writer(f_buf) as writer: default_sheet = writer.new_sheet(self.title) self._render_headers(default_sheet) self._render_rows(default_sheet) # abstract_sheet require the same attributes as our current writer for abstract_sheet in self.sheets: sheet = writer.new_sheet(name=abstract_sheet.title) abstract_sheet._render_headers(sheet) abstract_sheet._render_rows(sheet) f_buf.seek(0) return f_buf
[ "def", "render", "(", "self", ",", "f_buf", "=", "None", ")", ":", "if", "f_buf", "is", "None", ":", "f_buf", "=", "StringIO", ".", "StringIO", "(", ")", "with", "odswriter", ".", "writer", "(", "f_buf", ")", "as", "writer", ":", "default_sheet", "=", "writer", ".", "new_sheet", "(", "self", ".", "title", ")", "self", ".", "_render_headers", "(", "default_sheet", ")", "self", ".", "_render_rows", "(", "default_sheet", ")", "# abstract_sheet require the same attributes as our current writer", "for", "abstract_sheet", "in", "self", ".", "sheets", ":", "sheet", "=", "writer", ".", "new_sheet", "(", "name", "=", "abstract_sheet", ".", "title", ")", "abstract_sheet", ".", "_render_headers", "(", "sheet", ")", "abstract_sheet", ".", "_render_rows", "(", "sheet", ")", "f_buf", ".", "seek", "(", "0", ")", "return", "f_buf" ]
Definitely render the workbook :param obj f_buf: A file buffer supporting the write and seek methods
[ "Definitely", "render", "the", "workbook" ]
67edb5541e6a56b0a657d3774d1e19c1110cd402
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/ods.py#L47-L67
238,895
majerteam/sqla_inspect
sqla_inspect/ods.py
SqlaOdsExporter._get_related_exporter
def _get_related_exporter(self, related_obj, column): """ returns an SqlaOdsExporter for the given related object and stores it in the column object as a cache """ result = column.get('sqla_ods_exporter') if result is None: result = column['sqla_ods_exporter'] = SqlaOdsExporter( related_obj.__class__, is_root=False, title=column.get('label', column['key']), ) self.add_sheet(result) return result
python
def _get_related_exporter(self, related_obj, column): """ returns an SqlaOdsExporter for the given related object and stores it in the column object as a cache """ result = column.get('sqla_ods_exporter') if result is None: result = column['sqla_ods_exporter'] = SqlaOdsExporter( related_obj.__class__, is_root=False, title=column.get('label', column['key']), ) self.add_sheet(result) return result
[ "def", "_get_related_exporter", "(", "self", ",", "related_obj", ",", "column", ")", ":", "result", "=", "column", ".", "get", "(", "'sqla_ods_exporter'", ")", "if", "result", "is", "None", ":", "result", "=", "column", "[", "'sqla_ods_exporter'", "]", "=", "SqlaOdsExporter", "(", "related_obj", ".", "__class__", ",", "is_root", "=", "False", ",", "title", "=", "column", ".", "get", "(", "'label'", ",", "column", "[", "'key'", "]", ")", ",", ")", "self", ".", "add_sheet", "(", "result", ")", "return", "result" ]
returns an SqlaOdsExporter for the given related object and stores it in the column object as a cache
[ "returns", "an", "SqlaOdsExporter", "for", "the", "given", "related", "object", "and", "stores", "it", "in", "the", "column", "object", "as", "a", "cache" ]
67edb5541e6a56b0a657d3774d1e19c1110cd402
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/ods.py#L178-L191
238,896
majerteam/sqla_inspect
sqla_inspect/ods.py
SqlaOdsExporter._get_relationship_cell_val
def _get_relationship_cell_val(self, obj, column): """ Return the value to insert in a relationship cell Handle the case of complex related datas we want to handle """ val = SqlaExporter._get_relationship_cell_val(self, obj, column) if val == "": related_key = column.get('related_key', None) if column['__col__'].uselist and related_key is None and \ self.is_root: # on récupère les objets liés key = column['key'] related_objects = getattr(obj, key, None) if not related_objects: return "" else: exporter = self._get_related_exporter( related_objects[0], column, ) for rel_obj in related_objects: exporter.add_row(rel_obj) return val
python
def _get_relationship_cell_val(self, obj, column): """ Return the value to insert in a relationship cell Handle the case of complex related datas we want to handle """ val = SqlaExporter._get_relationship_cell_val(self, obj, column) if val == "": related_key = column.get('related_key', None) if column['__col__'].uselist and related_key is None and \ self.is_root: # on récupère les objets liés key = column['key'] related_objects = getattr(obj, key, None) if not related_objects: return "" else: exporter = self._get_related_exporter( related_objects[0], column, ) for rel_obj in related_objects: exporter.add_row(rel_obj) return val
[ "def", "_get_relationship_cell_val", "(", "self", ",", "obj", ",", "column", ")", ":", "val", "=", "SqlaExporter", ".", "_get_relationship_cell_val", "(", "self", ",", "obj", ",", "column", ")", "if", "val", "==", "\"\"", ":", "related_key", "=", "column", ".", "get", "(", "'related_key'", ",", "None", ")", "if", "column", "[", "'__col__'", "]", ".", "uselist", "and", "related_key", "is", "None", "and", "self", ".", "is_root", ":", "# on récupère les objets liés", "key", "=", "column", "[", "'key'", "]", "related_objects", "=", "getattr", "(", "obj", ",", "key", ",", "None", ")", "if", "not", "related_objects", ":", "return", "\"\"", "else", ":", "exporter", "=", "self", ".", "_get_related_exporter", "(", "related_objects", "[", "0", "]", ",", "column", ",", ")", "for", "rel_obj", "in", "related_objects", ":", "exporter", ".", "add_row", "(", "rel_obj", ")", "return", "val" ]
Return the value to insert in a relationship cell Handle the case of complex related datas we want to handle
[ "Return", "the", "value", "to", "insert", "in", "a", "relationship", "cell", "Handle", "the", "case", "of", "complex", "related", "datas", "we", "want", "to", "handle" ]
67edb5541e6a56b0a657d3774d1e19c1110cd402
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/ods.py#L193-L218
238,897
cyrus-/cypy
cypy/np/plotting.py
raster
def raster(times, indices, max_time=None, max_index=None, x_label="Timestep", y_label="Index", **kwargs): """Plots a raster plot given times and indices of events.""" # set default size to 1 if 's' not in kwargs: kwargs['s'] = 1 scatter(times, indices, **kwargs) if max_time is None: max_time = max(times) if max_index is None: max_index = max(indices) axis((0, max_time, 0, max_index)) if x_label is not None: xlabel(x_label) if y_label is not None: ylabel(y_label)
python
def raster(times, indices, max_time=None, max_index=None, x_label="Timestep", y_label="Index", **kwargs): """Plots a raster plot given times and indices of events.""" # set default size to 1 if 's' not in kwargs: kwargs['s'] = 1 scatter(times, indices, **kwargs) if max_time is None: max_time = max(times) if max_index is None: max_index = max(indices) axis((0, max_time, 0, max_index)) if x_label is not None: xlabel(x_label) if y_label is not None: ylabel(y_label)
[ "def", "raster", "(", "times", ",", "indices", ",", "max_time", "=", "None", ",", "max_index", "=", "None", ",", "x_label", "=", "\"Timestep\"", ",", "y_label", "=", "\"Index\"", ",", "*", "*", "kwargs", ")", ":", "# set default size to 1", "if", "'s'", "not", "in", "kwargs", ":", "kwargs", "[", "'s'", "]", "=", "1", "scatter", "(", "times", ",", "indices", ",", "*", "*", "kwargs", ")", "if", "max_time", "is", "None", ":", "max_time", "=", "max", "(", "times", ")", "if", "max_index", "is", "None", ":", "max_index", "=", "max", "(", "indices", ")", "axis", "(", "(", "0", ",", "max_time", ",", "0", ",", "max_index", ")", ")", "if", "x_label", "is", "not", "None", ":", "xlabel", "(", "x_label", ")", "if", "y_label", "is", "not", "None", ":", "ylabel", "(", "y_label", ")" ]
Plots a raster plot given times and indices of events.
[ "Plots", "a", "raster", "plot", "given", "times", "and", "indices", "of", "events", "." ]
04bb59e91fa314e8cf987743189c77a9b6bc371d
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/np/plotting.py#L25-L39
238,898
zkbt/the-friendly-stars
thefriendlystars/constellations/gaia.py
query
def query(query): ''' Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results. ''' # send the query to the Gaia archive with warnings.catch_warnings() : warnings.filterwarnings("ignore") _gaia_job = astroquery.gaia.Gaia.launch_job(query) # return the table of results return _gaia_job.get_results()
python
def query(query): ''' Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results. ''' # send the query to the Gaia archive with warnings.catch_warnings() : warnings.filterwarnings("ignore") _gaia_job = astroquery.gaia.Gaia.launch_job(query) # return the table of results return _gaia_job.get_results()
[ "def", "query", "(", "query", ")", ":", "# send the query to the Gaia archive", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ")", "_gaia_job", "=", "astroquery", ".", "gaia", ".", "Gaia", ".", "launch_job", "(", "query", ")", "# return the table of results", "return", "_gaia_job", ".", "get_results", "(", ")" ]
Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results.
[ "Send", "an", "ADQL", "query", "to", "the", "Gaia", "archive", "wait", "for", "a", "response", "and", "hang", "on", "to", "the", "results", "." ]
50d3f979e79e63c66629065c75595696dc79802e
https://github.com/zkbt/the-friendly-stars/blob/50d3f979e79e63c66629065c75595696dc79802e/thefriendlystars/constellations/gaia.py#L4-L18
238,899
znerol/txexiftool
txexiftool/__init__.py
ExiftoolProtocol.connectionMade
def connectionMade(self): """ Initializes the protocol. """ self._buffer = b'' self._queue = {} self._stopped = None self._tag = 0
python
def connectionMade(self): """ Initializes the protocol. """ self._buffer = b'' self._queue = {} self._stopped = None self._tag = 0
[ "def", "connectionMade", "(", "self", ")", ":", "self", ".", "_buffer", "=", "b''", "self", ".", "_queue", "=", "{", "}", "self", ".", "_stopped", "=", "None", "self", ".", "_tag", "=", "0" ]
Initializes the protocol.
[ "Initializes", "the", "protocol", "." ]
a3d75a31262a492f81072840d4fc818f65bf3265
https://github.com/znerol/txexiftool/blob/a3d75a31262a492f81072840d4fc818f65bf3265/txexiftool/__init__.py#L33-L40