repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
toumorokoshi/sprinter
sprinter/lib/module.py
get_subclass_from_module
def get_subclass_from_module(module, parent_class): """ Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it. """ try: r = __recursive_import(module) member_dict = dict(inspect.getmembers(r)) sprinter_class = parent_class for v in member_dict.values(): if inspect.isclass(v) and issubclass(v, parent_class) and v != parent_class: if sprinter_class is parent_class: sprinter_class = v if sprinter_class is None: raise SprinterException("No subclass %s that extends %s exists in classpath!" % (module, str(parent_class))) return sprinter_class except ImportError: e = sys.exc_info()[1] raise e
python
def get_subclass_from_module(module, parent_class): """ Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it. """ try: r = __recursive_import(module) member_dict = dict(inspect.getmembers(r)) sprinter_class = parent_class for v in member_dict.values(): if inspect.isclass(v) and issubclass(v, parent_class) and v != parent_class: if sprinter_class is parent_class: sprinter_class = v if sprinter_class is None: raise SprinterException("No subclass %s that extends %s exists in classpath!" % (module, str(parent_class))) return sprinter_class except ImportError: e = sys.exc_info()[1] raise e
[ "def", "get_subclass_from_module", "(", "module", ",", "parent_class", ")", ":", "try", ":", "r", "=", "__recursive_import", "(", "module", ")", "member_dict", "=", "dict", "(", "inspect", ".", "getmembers", "(", "r", ")", ")", "sprinter_class", "=", "parent...
Get a subclass of parent_class from the module at module get_subclass_from_module performs reflection to find the first class that extends the parent_class in the module path, and returns it.
[ "Get", "a", "subclass", "of", "parent_class", "from", "the", "module", "at", "module" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/module.py#L9-L29
train
55,100
toumorokoshi/sprinter
sprinter/lib/module.py
__recursive_import
def __recursive_import(module_name): """ Recursively looks for and imports the names, returning the module desired >>> __recursive_import("sprinter.formula.unpack") # doctest: +ELLIPSIS <module 'unpack' from '...'> currently module with relative imports don't work. """ names = module_name.split(".") path = None module = None while len(names) > 0: if module: path = module.__path__ name = names.pop(0) (module_file, pathname, description) = imp.find_module(name, path) module = imp.load_module(name, module_file, pathname, description) return module
python
def __recursive_import(module_name): """ Recursively looks for and imports the names, returning the module desired >>> __recursive_import("sprinter.formula.unpack") # doctest: +ELLIPSIS <module 'unpack' from '...'> currently module with relative imports don't work. """ names = module_name.split(".") path = None module = None while len(names) > 0: if module: path = module.__path__ name = names.pop(0) (module_file, pathname, description) = imp.find_module(name, path) module = imp.load_module(name, module_file, pathname, description) return module
[ "def", "__recursive_import", "(", "module_name", ")", ":", "names", "=", "module_name", ".", "split", "(", "\".\"", ")", "path", "=", "None", "module", "=", "None", "while", "len", "(", "names", ")", ">", "0", ":", "if", "module", ":", "path", "=", "...
Recursively looks for and imports the names, returning the module desired >>> __recursive_import("sprinter.formula.unpack") # doctest: +ELLIPSIS <module 'unpack' from '...'> currently module with relative imports don't work.
[ "Recursively", "looks", "for", "and", "imports", "the", "names", "returning", "the", "module", "desired" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/module.py#L32-L51
train
55,101
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
err_exit
def err_exit(msg, rc=1): """Print msg to stderr and exit with rc. """ print(msg, file=sys.stderr) sys.exit(rc)
python
def err_exit(msg, rc=1): """Print msg to stderr and exit with rc. """ print(msg, file=sys.stderr) sys.exit(rc)
[ "def", "err_exit", "(", "msg", ",", "rc", "=", "1", ")", ":", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "rc", ")" ]
Print msg to stderr and exit with rc.
[ "Print", "msg", "to", "stderr", "and", "exit", "with", "rc", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L195-L199
train
55,102
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.read_file
def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e))
python
def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: err_exit('Error reading %s: %s' % (infile, e.strerror or e))
[ "def", "read_file", "(", "self", ",", "infile", ")", ":", "try", ":", "with", "open", "(", "infile", ",", "'rt'", ")", "as", "file", ":", "return", "file", ".", "read", "(", ")", "except", "UnicodeDecodeError", "as", "e", ":", "err_exit", "(", "'Erro...
Read a reST file into a string.
[ "Read", "a", "reST", "file", "into", "a", "string", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L294-L303
train
55,103
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.write_file
def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e))
python
def write_file(self, html, outfile): """Write an HTML string to a file. """ try: with open(outfile, 'wt') as file: file.write(html) except (IOError, OSError) as e: err_exit('Error writing %s: %s' % (outfile, e.strerror or e))
[ "def", "write_file", "(", "self", ",", "html", ",", "outfile", ")", ":", "try", ":", "with", "open", "(", "outfile", ",", "'wt'", ")", "as", "file", ":", "file", ".", "write", "(", "html", ")", "except", "(", "IOError", ",", "OSError", ")", "as", ...
Write an HTML string to a file.
[ "Write", "an", "HTML", "string", "to", "a", "file", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L305-L312
train
55,104
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.convert_string
def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html
python
def convert_string(self, rest): """Convert a reST string to an HTML string. """ try: html = publish_string(rest, writer_name='html') except SystemExit as e: err_exit('HTML conversion failed with error: %s' % e.code) else: if sys.version_info[0] >= 3: return html.decode('utf-8') return html
[ "def", "convert_string", "(", "self", ",", "rest", ")", ":", "try", ":", "html", "=", "publish_string", "(", "rest", ",", "writer_name", "=", "'html'", ")", "except", "SystemExit", "as", "e", ":", "err_exit", "(", "'HTML conversion failed with error: %s'", "%"...
Convert a reST string to an HTML string.
[ "Convert", "a", "reST", "string", "to", "an", "HTML", "string", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L314-L324
train
55,105
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.apply_styles
def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html
python
def apply_styles(self, html, styles): """Insert style information into the HTML string. """ index = html.find('</head>') if index >= 0: return ''.join((html[:index], styles, html[index:])) return html
[ "def", "apply_styles", "(", "self", ",", "html", ",", "styles", ")", ":", "index", "=", "html", ".", "find", "(", "'</head>'", ")", "if", "index", ">=", "0", ":", "return", "''", ".", "join", "(", "(", "html", "[", ":", "index", "]", ",", "styles...
Insert style information into the HTML string.
[ "Insert", "style", "information", "into", "the", "HTML", "string", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L333-L339
train
55,106
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.publish_string
def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile
python
def publish_string(self, rest, outfile, styles=''): """Render a reST string as HTML. """ html = self.convert_string(rest) html = self.strip_xml_header(html) html = self.apply_styles(html, styles) self.write_file(html, outfile) return outfile
[ "def", "publish_string", "(", "self", ",", "rest", ",", "outfile", ",", "styles", "=", "''", ")", ":", "html", "=", "self", ".", "convert_string", "(", "rest", ")", "html", "=", "self", ".", "strip_xml_header", "(", "html", ")", "html", "=", "self", ...
Render a reST string as HTML.
[ "Render", "a", "reST", "string", "as", "HTML", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L341-L348
train
55,107
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Docutils.publish_file
def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
python
def publish_file(self, infile, outfile, styles=''): """Render a reST file as HTML. """ rest = self.read_file(infile) return self.publish_string(rest, outfile, styles)
[ "def", "publish_file", "(", "self", ",", "infile", ",", "outfile", ",", "styles", "=", "''", ")", ":", "rest", "=", "self", ".", "read_file", "(", "infile", ")", "return", "self", ".", "publish_string", "(", "rest", ",", "outfile", ",", "styles", ")" ]
Render a reST file as HTML.
[ "Render", "a", "reST", "file", "as", "HTML", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L350-L354
train
55,108
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Defaults.upgrade
def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False
python
def upgrade(self): """Upgrade the config file. """ warn('Upgrading ' + self.filename) if self.backup_config(self.filename): return self.write_default_config(self.filename) return False
[ "def", "upgrade", "(", "self", ")", ":", "warn", "(", "'Upgrading '", "+", "self", ".", "filename", ")", "if", "self", ".", "backup_config", "(", "self", ".", "filename", ")", ":", "return", "self", ".", "write_default_config", "(", "self", ".", "filenam...
Upgrade the config file.
[ "Upgrade", "the", "config", "file", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L389-L395
train
55,109
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Defaults.backup_config
def backup_config(self, filename): """Backup the current config file. """ backup_name = filename + '-' + self.version warn('Moving current configuration to ' + backup_name) try: shutil.copy2(filename, backup_name) return True except (IOError, OSError) as e: print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
python
def backup_config(self, filename): """Backup the current config file. """ backup_name = filename + '-' + self.version warn('Moving current configuration to ' + backup_name) try: shutil.copy2(filename, backup_name) return True except (IOError, OSError) as e: print('Error copying %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
[ "def", "backup_config", "(", "self", ",", "filename", ")", ":", "backup_name", "=", "filename", "+", "'-'", "+", "self", ".", "version", "warn", "(", "'Moving current configuration to '", "+", "backup_name", ")", "try", ":", "shutil", ".", "copy2", "(", "fil...
Backup the current config file.
[ "Backup", "the", "current", "config", "file", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L397-L407
train
55,110
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
Defaults.write_default_config
def write_default_config(self, filename): """Write the default config file. """ try: with open(filename, 'wt') as file: file.write(DEFAULT_CONFIG) return True except (IOError, OSError) as e: print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
python
def write_default_config(self, filename): """Write the default config file. """ try: with open(filename, 'wt') as file: file.write(DEFAULT_CONFIG) return True except (IOError, OSError) as e: print('Error writing %s: %s' % (filename, e.strerror or e), file=sys.stderr) return False
[ "def", "write_default_config", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'wt'", ")", "as", "file", ":", "file", ".", "write", "(", "DEFAULT_CONFIG", ")", "return", "True", "except", "(", "IOError", ",", ...
Write the default config file.
[ "Write", "the", "default", "config", "file", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L409-L418
train
55,111
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.reset_defaults
def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file)
python
def reset_defaults(self, config_file): """Reset defaults. """ if not exists(config_file): err_exit('No such file: %(config_file)s' % locals()) if not isfile(config_file): err_exit('Not a file: %(config_file)s' % locals()) if not os.access(config_file, os.R_OK): err_exit('File cannot be read: %(config_file)s' % locals()) self.set_defaults(config_file)
[ "def", "reset_defaults", "(", "self", ",", "config_file", ")", ":", "if", "not", "exists", "(", "config_file", ")", ":", "err_exit", "(", "'No such file: %(config_file)s'", "%", "locals", "(", ")", ")", "if", "not", "isfile", "(", "config_file", ")", ":", ...
Reset defaults.
[ "Reset", "defaults", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L440-L449
train
55,112
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.write_defaults
def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename)
python
def write_defaults(self): """Create default config file and reload. """ self.defaults.write() self.reset_defaults(self.defaults.filename)
[ "def", "write_defaults", "(", "self", ")", ":", "self", ".", "defaults", ".", "write", "(", ")", "self", ".", "reset_defaults", "(", "self", ".", "defaults", ".", "filename", ")" ]
Create default config file and reload.
[ "Create", "default", "config", "file", "and", "reload", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L451-L455
train
55,113
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.upgrade_defaults
def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename)
python
def upgrade_defaults(self): """Upgrade config file and reload. """ self.defaults.upgrade() self.reset_defaults(self.defaults.filename)
[ "def", "upgrade_defaults", "(", "self", ")", ":", "self", ".", "defaults", ".", "upgrade", "(", ")", "self", ".", "reset_defaults", "(", "self", ".", "defaults", ".", "filename", ")" ]
Upgrade config file and reload.
[ "Upgrade", "config", "file", "and", "reload", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L457-L461
train
55,114
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.list_styles
def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0)
python
def list_styles(self): """Print available styles and exit. """ known = sorted(self.defaults.known_styles) if not known: err_exit('No styles', 0) for style in known: if style == self.defaults.default_style: print(style, '(default)') else: print(style) sys.exit(0)
[ "def", "list_styles", "(", "self", ")", ":", "known", "=", "sorted", "(", "self", ".", "defaults", ".", "known_styles", ")", "if", "not", "known", ":", "err_exit", "(", "'No styles'", ",", "0", ")", "for", "style", "in", "known", ":", "if", "style", ...
Print available styles and exit.
[ "Print", "available", "styles", "and", "exit", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L509-L520
train
55,115
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.render_file
def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile
python
def render_file(self, filename): """Convert a reST file to HTML. """ dirname, basename = split(filename) with changedir(dirname): infile = abspath(basename) outfile = abspath('.%s.html' % basename) self.docutils.publish_file(infile, outfile, self.styles) return outfile
[ "def", "render_file", "(", "self", ",", "filename", ")", ":", "dirname", ",", "basename", "=", "split", "(", "filename", ")", "with", "changedir", "(", "dirname", ")", ":", "infile", "=", "abspath", "(", "basename", ")", "outfile", "=", "abspath", "(", ...
Convert a reST file to HTML.
[ "Convert", "a", "reST", "file", "to", "HTML", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L522-L530
train
55,116
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.render_long_description
def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile
python
def render_long_description(self, dirname): """Convert a package's long description to HTML. """ with changedir(dirname): self.setuptools.check_valid_package() long_description = self.setuptools.get_long_description() outfile = abspath('.long-description.html') self.docutils.publish_string(long_description, outfile, self.styles) return outfile
[ "def", "render_long_description", "(", "self", ",", "dirname", ")", ":", "with", "changedir", "(", "dirname", ")", ":", "self", ".", "setuptools", ".", "check_valid_package", "(", ")", "long_description", "=", "self", ".", "setuptools", ".", "get_long_descriptio...
Convert a package's long description to HTML.
[ "Convert", "a", "package", "s", "long", "description", "to", "HTML", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L532-L540
train
55,117
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.open_in_browser
def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile)
python
def open_in_browser(self, outfile): """Open the given HTML file in a browser. """ if self.browser == 'default': webbrowser.open('file://%s' % outfile) else: browser = webbrowser.get(self.browser) browser.open('file://%s' % outfile)
[ "def", "open_in_browser", "(", "self", ",", "outfile", ")", ":", "if", "self", ".", "browser", "==", "'default'", ":", "webbrowser", ".", "open", "(", "'file://%s'", "%", "outfile", ")", "else", ":", "browser", "=", "webbrowser", ".", "get", "(", "self",...
Open the given HTML file in a browser.
[ "Open", "the", "given", "HTML", "file", "in", "a", "browser", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L542-L549
train
55,118
Jarn/jarn.viewdoc
jarn/viewdoc/viewdoc.py
DocumentationViewer.run
def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
python
def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: arg = expanduser(arg) if isfile(arg): outfile = self.render_file(arg) elif isdir(arg): outfile = self.render_long_description(arg) else: err_exit('No such file or directory: %s' % arg) self.open_in_browser(outfile)
[ "def", "run", "(", "self", ")", ":", "os", ".", "environ", "[", "'JARN_RUN'", "]", "=", "'1'", "self", ".", "python", ".", "check_valid_python", "(", ")", "args", "=", "self", ".", "parse_options", "(", "self", ".", "args", ")", "if", "args", ":", ...
Render and display Python package documentation.
[ "Render", "and", "display", "Python", "package", "documentation", "." ]
59ae82fd1658889c41096c1d8c08dcb1047dc349
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L551-L572
train
55,119
bryanwweber/thermohw
thermohw/extract_attachments.py
ExtractAttachmentsPreprocessor.preprocess_cell
def preprocess_cell( self, cell: "NotebookNode", resources: dict, cell_index: int ) -> Tuple["NotebookNode", dict]: """Apply a transformation on each cell. Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ # Get files directory if it has been specified output_files_dir = resources.get("output_files_dir", None) # Make sure outputs key exists if not isinstance(resources["outputs"], dict): resources["outputs"] = {} # Loop through all of the attachments in the cell for name, attach in cell.get("attachments", {}).items(): orig_name = name name = re.sub(r"%[\w\d][\w\d]", "-", name) for mime, data in attach.items(): if mime not in self.extract_output_types: continue # Binary files are base64-encoded, SVG is already XML if mime in {"image/png", "image/jpeg", "application/pdf"}: # data is b64-encoded as text (str, unicode), # we want the original bytes data = a2b_base64(data) elif sys.platform == "win32": data = data.replace("\n", "\r\n").encode("UTF-8") else: data = data.encode("UTF-8") filename = self.output_filename_template.format( cell_index=cell_index, name=name, unique_key=resources.get("unique_key", ""), ) if output_files_dir is not None: filename = os.path.join(output_files_dir, filename) if name.endswith(".gif") and mime == "image/png": filename = filename.replace(".gif", ".png") # In the resources, make the figure available via # resources['outputs']['filename'] = data resources["outputs"][filename] = data # now we need to change the cell source so that it links to the # filename instead of `attachment:` attach_str = "attachment:" + orig_name if attach_str in cell.source: cell.source = cell.source.replace(attach_str, filename) return cell, resources
python
def preprocess_cell( self, cell: "NotebookNode", resources: dict, cell_index: int ) -> Tuple["NotebookNode", dict]: """Apply a transformation on each cell. Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ # Get files directory if it has been specified output_files_dir = resources.get("output_files_dir", None) # Make sure outputs key exists if not isinstance(resources["outputs"], dict): resources["outputs"] = {} # Loop through all of the attachments in the cell for name, attach in cell.get("attachments", {}).items(): orig_name = name name = re.sub(r"%[\w\d][\w\d]", "-", name) for mime, data in attach.items(): if mime not in self.extract_output_types: continue # Binary files are base64-encoded, SVG is already XML if mime in {"image/png", "image/jpeg", "application/pdf"}: # data is b64-encoded as text (str, unicode), # we want the original bytes data = a2b_base64(data) elif sys.platform == "win32": data = data.replace("\n", "\r\n").encode("UTF-8") else: data = data.encode("UTF-8") filename = self.output_filename_template.format( cell_index=cell_index, name=name, unique_key=resources.get("unique_key", ""), ) if output_files_dir is not None: filename = os.path.join(output_files_dir, filename) if name.endswith(".gif") and mime == "image/png": filename = filename.replace(".gif", ".png") # In the resources, make the figure available via # resources['outputs']['filename'] = data resources["outputs"][filename] = data # now we need to change the cell source so that it links to the # filename instead of `attachment:` attach_str = "attachment:" + orig_name if attach_str in cell.source: cell.source = cell.source.replace(attach_str, filename) return cell, resources
[ "def", "preprocess_cell", "(", "self", ",", "cell", ":", "\"NotebookNode\"", ",", "resources", ":", "dict", ",", "cell_index", ":", "int", ")", "->", "Tuple", "[", "\"NotebookNode\"", ",", "dict", "]", ":", "# Get files directory if it has been specified", "output...
Apply a transformation on each cell. Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py)
[ "Apply", "a", "transformation", "on", "each", "cell", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/extract_attachments.py#L98-L161
train
55,120
bryanwweber/thermohw
thermohw/utils.py
combine_pdf_as_bytes
def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes: """Combine PDFs and return a byte-string with the result. Arguments --------- pdfs A list of BytesIO representations of PDFs """ writer = PdfWriter() for pdf in pdfs: writer.addpages(PdfReader(pdf).pages) bio = BytesIO() writer.write(bio) bio.seek(0) output = bio.read() bio.close() return output
python
def combine_pdf_as_bytes(pdfs: List[BytesIO]) -> bytes: """Combine PDFs and return a byte-string with the result. Arguments --------- pdfs A list of BytesIO representations of PDFs """ writer = PdfWriter() for pdf in pdfs: writer.addpages(PdfReader(pdf).pages) bio = BytesIO() writer.write(bio) bio.seek(0) output = bio.read() bio.close() return output
[ "def", "combine_pdf_as_bytes", "(", "pdfs", ":", "List", "[", "BytesIO", "]", ")", "->", "bytes", ":", "writer", "=", "PdfWriter", "(", ")", "for", "pdf", "in", "pdfs", ":", "writer", ".", "addpages", "(", "PdfReader", "(", "pdf", ")", ".", "pages", ...
Combine PDFs and return a byte-string with the result. Arguments --------- pdfs A list of BytesIO representations of PDFs
[ "Combine", "PDFs", "and", "return", "a", "byte", "-", "string", "with", "the", "result", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/utils.py#L13-L30
train
55,121
iloob/python-periods
periods/period.py
Period.split
def split(self, granularity_after_split, exclude_partial=True): """ Split a period into a given granularity. Optionally include partial periods at the start and end of the period. """ if granularity_after_split == Granularity.DAY: return self.get_days() elif granularity_after_split == Granularity.WEEK: return self.get_weeks(exclude_partial) elif granularity_after_split == Granularity.MONTH: return self.get_months(exclude_partial) elif granularity_after_split == Granularity.QUARTER: return self.get_quarters(exclude_partial) elif granularity_after_split == Granularity.HALF_YEAR: return self.get_half_years(exclude_partial) elif granularity_after_split == Granularity.YEAR: return self.get_years(exclude_partial) else: raise Exception("Invalid granularity: %s" % granularity_after_split)
python
def split(self, granularity_after_split, exclude_partial=True): """ Split a period into a given granularity. Optionally include partial periods at the start and end of the period. """ if granularity_after_split == Granularity.DAY: return self.get_days() elif granularity_after_split == Granularity.WEEK: return self.get_weeks(exclude_partial) elif granularity_after_split == Granularity.MONTH: return self.get_months(exclude_partial) elif granularity_after_split == Granularity.QUARTER: return self.get_quarters(exclude_partial) elif granularity_after_split == Granularity.HALF_YEAR: return self.get_half_years(exclude_partial) elif granularity_after_split == Granularity.YEAR: return self.get_years(exclude_partial) else: raise Exception("Invalid granularity: %s" % granularity_after_split)
[ "def", "split", "(", "self", ",", "granularity_after_split", ",", "exclude_partial", "=", "True", ")", ":", "if", "granularity_after_split", "==", "Granularity", ".", "DAY", ":", "return", "self", ".", "get_days", "(", ")", "elif", "granularity_after_split", "==...
Split a period into a given granularity. Optionally include partial periods at the start and end of the period.
[ "Split", "a", "period", "into", "a", "given", "granularity", ".", "Optionally", "include", "partial", "periods", "at", "the", "start", "and", "end", "of", "the", "period", "." ]
8988373522907d72c0ee5896c2ffbb573a8500d9
https://github.com/iloob/python-periods/blob/8988373522907d72c0ee5896c2ffbb573a8500d9/periods/period.py#L80-L105
train
55,122
wheeler-microfluidics/dmf-control-board-firmware
dmf_control_board_firmware/calibrate/impedance.py
apply_calibration
def apply_calibration(df, calibration_df, calibration): ''' Apply calibration values from `fit_fb_calibration` result to `calibration` object. ''' from dmf_control_board_firmware import FeedbackResults for i, (fb_resistor, R_fb, C_fb) in calibration_df[['fb_resistor', 'R_fb', 'C_fb']].iterrows(): calibration.R_fb[int(fb_resistor)] = R_fb calibration.C_fb[int(fb_resistor)] = C_fb cleaned_df = df.dropna() grouped = cleaned_df.groupby(['frequency', 'test_capacitor', 'repeat_index']) for (f, channel, repeat_index), group in grouped: r = FeedbackResults(group.V_actuation.iloc[0], f, 5.0, group.V_hv.values, group.hv_resistor.values, group.V_fb.values, group.fb_resistor.values, calibration) # Update the measured capacitance values based on the updated # calibration model. df.loc[group.index, 'C'] = r.capacitance()
python
def apply_calibration(df, calibration_df, calibration): ''' Apply calibration values from `fit_fb_calibration` result to `calibration` object. ''' from dmf_control_board_firmware import FeedbackResults for i, (fb_resistor, R_fb, C_fb) in calibration_df[['fb_resistor', 'R_fb', 'C_fb']].iterrows(): calibration.R_fb[int(fb_resistor)] = R_fb calibration.C_fb[int(fb_resistor)] = C_fb cleaned_df = df.dropna() grouped = cleaned_df.groupby(['frequency', 'test_capacitor', 'repeat_index']) for (f, channel, repeat_index), group in grouped: r = FeedbackResults(group.V_actuation.iloc[0], f, 5.0, group.V_hv.values, group.hv_resistor.values, group.V_fb.values, group.fb_resistor.values, calibration) # Update the measured capacitance values based on the updated # calibration model. df.loc[group.index, 'C'] = r.capacitance()
[ "def", "apply_calibration", "(", "df", ",", "calibration_df", ",", "calibration", ")", ":", "from", "dmf_control_board_firmware", "import", "FeedbackResults", "for", "i", ",", "(", "fb_resistor", ",", "R_fb", ",", "C_fb", ")", "in", "calibration_df", "[", "[", ...
Apply calibration values from `fit_fb_calibration` result to `calibration` object.
[ "Apply", "calibration", "values", "from", "fit_fb_calibration", "result", "to", "calibration", "object", "." ]
1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c
https://github.com/wheeler-microfluidics/dmf-control-board-firmware/blob/1cd8cc9a148d530f9a11f634f2dbfe73f08aa27c/dmf_control_board_firmware/calibrate/impedance.py#L302-L323
train
55,123
jaraco/rst.linker
rst/linker.py
config_dict
def config_dict(config): """ Given a Sphinx config object, return a dictionary of config values. """ return dict( (key, getattr(config, key)) for key in config.values )
python
def config_dict(config): """ Given a Sphinx config object, return a dictionary of config values. """ return dict( (key, getattr(config, key)) for key in config.values )
[ "def", "config_dict", "(", "config", ")", ":", "return", "dict", "(", "(", "key", ",", "getattr", "(", "config", ",", "key", ")", ")", "for", "key", "in", "config", ".", "values", ")" ]
Given a Sphinx config object, return a dictionary of config values.
[ "Given", "a", "Sphinx", "config", "object", "return", "a", "dictionary", "of", "config", "values", "." ]
5d0ff09756c325c46c471c217bdefcfd11ce1de4
https://github.com/jaraco/rst.linker/blob/5d0ff09756c325c46c471c217bdefcfd11ce1de4/rst/linker.py#L191-L199
train
55,124
jaraco/rst.linker
rst/linker.py
Repl.from_defn
def from_defn(cls, defn): "Return the first Repl subclass that works with this" instances = (subcl(defn) for subcl in cls.__subclasses__()) return next(filter(None, instances))
python
def from_defn(cls, defn): "Return the first Repl subclass that works with this" instances = (subcl(defn) for subcl in cls.__subclasses__()) return next(filter(None, instances))
[ "def", "from_defn", "(", "cls", ",", "defn", ")", ":", "instances", "=", "(", "subcl", "(", "defn", ")", "for", "subcl", "in", "cls", ".", "__subclasses__", "(", ")", ")", "return", "next", "(", "filter", "(", "None", ",", "instances", ")", ")" ]
Return the first Repl subclass that works with this
[ "Return", "the", "first", "Repl", "subclass", "that", "works", "with", "this" ]
5d0ff09756c325c46c471c217bdefcfd11ce1de4
https://github.com/jaraco/rst.linker/blob/5d0ff09756c325c46c471c217bdefcfd11ce1de4/rst/linker.py#L22-L25
train
55,125
Chilipp/psy-simple
psy_simple/widgets/colors.py
ColormapDialog.show_colormap
def show_colormap(cls, names=[], N=10, show=True, *args, **kwargs): """Show a colormap dialog Parameters ---------- %(show_colormaps.parameters.no_use_qt)s""" names = safe_list(names) obj = cls(names, N, *args, **kwargs) vbox = obj.layout() buttons = QDialogButtonBox(QDialogButtonBox.Close, parent=obj) buttons.rejected.connect(obj.close) vbox.addWidget(buttons) if show: obj.show() return obj
python
def show_colormap(cls, names=[], N=10, show=True, *args, **kwargs): """Show a colormap dialog Parameters ---------- %(show_colormaps.parameters.no_use_qt)s""" names = safe_list(names) obj = cls(names, N, *args, **kwargs) vbox = obj.layout() buttons = QDialogButtonBox(QDialogButtonBox.Close, parent=obj) buttons.rejected.connect(obj.close) vbox.addWidget(buttons) if show: obj.show() return obj
[ "def", "show_colormap", "(", "cls", ",", "names", "=", "[", "]", ",", "N", "=", "10", ",", "show", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "names", "=", "safe_list", "(", "names", ")", "obj", "=", "cls", "(", "names", ...
Show a colormap dialog Parameters ---------- %(show_colormaps.parameters.no_use_qt)s
[ "Show", "a", "colormap", "dialog" ]
7d916406a6d3c3c27c0b7102f98fef07a4da0a61
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/widgets/colors.py#L221-L235
train
55,126
cwoebker/pen
pen/core.py
cmd_list
def cmd_list(args): """List all element in pen""" for penlist in penStore.data: puts(penlist + " (" + str(len(penStore.data[penlist])) + ")")
python
def cmd_list(args): """List all element in pen""" for penlist in penStore.data: puts(penlist + " (" + str(len(penStore.data[penlist])) + ")")
[ "def", "cmd_list", "(", "args", ")", ":", "for", "penlist", "in", "penStore", ".", "data", ":", "puts", "(", "penlist", "+", "\" (\"", "+", "str", "(", "len", "(", "penStore", ".", "data", "[", "penlist", "]", ")", ")", "+", "\")\"", ")" ]
List all element in pen
[ "List", "all", "element", "in", "pen" ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/core.py#L32-L35
train
55,127
cwoebker/pen
pen/core.py
cmd_all
def cmd_all(args): """List everything recursively""" for penlist in penStore.data: puts(penlist) with indent(4, ' -'): for penfile in penStore.data[penlist]: puts(penfile)
python
def cmd_all(args): """List everything recursively""" for penlist in penStore.data: puts(penlist) with indent(4, ' -'): for penfile in penStore.data[penlist]: puts(penfile)
[ "def", "cmd_all", "(", "args", ")", ":", "for", "penlist", "in", "penStore", ".", "data", ":", "puts", "(", "penlist", ")", "with", "indent", "(", "4", ",", "' -'", ")", ":", "for", "penfile", "in", "penStore", ".", "data", "[", "penlist", "]", ":...
List everything recursively
[ "List", "everything", "recursively" ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/core.py#L39-L45
train
55,128
cwoebker/pen
pen/core.py
cmd_create
def cmd_create(args): """Creates a list""" name = args.get(0) if name: penStore.createList(name) else: puts("not valid")
python
def cmd_create(args): """Creates a list""" name = args.get(0) if name: penStore.createList(name) else: puts("not valid")
[ "def", "cmd_create", "(", "args", ")", ":", "name", "=", "args", ".", "get", "(", "0", ")", "if", "name", ":", "penStore", ".", "createList", "(", "name", ")", "else", ":", "puts", "(", "\"not valid\"", ")" ]
Creates a list
[ "Creates", "a", "list" ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/core.py#L49-L55
train
55,129
cwoebker/pen
pen/core.py
cmd_touch_note
def cmd_touch_note(args): """Create a note""" major = args.get(0) minor = args.get(1) if major in penStore.data: if minor is None: # show items in list for note in penStore.data[major]: puts(note) elif minor in penStore.data[major]: penStore.openNote(major, minor) else: penStore.createNote(major, minor) penStore.openNote(major, minor) else: puts("No list of that name.")
python
def cmd_touch_note(args): """Create a note""" major = args.get(0) minor = args.get(1) if major in penStore.data: if minor is None: # show items in list for note in penStore.data[major]: puts(note) elif minor in penStore.data[major]: penStore.openNote(major, minor) else: penStore.createNote(major, minor) penStore.openNote(major, minor) else: puts("No list of that name.")
[ "def", "cmd_touch_note", "(", "args", ")", ":", "major", "=", "args", ".", "get", "(", "0", ")", "minor", "=", "args", ".", "get", "(", "1", ")", "if", "major", "in", "penStore", ".", "data", ":", "if", "minor", "is", "None", ":", "# show items in ...
Create a note
[ "Create", "a", "note" ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/core.py#L58-L72
train
55,130
cwoebker/pen
pen/core.py
cmd_delete
def cmd_delete(args): """Deletes a node""" major = args.get(0) minor = args.get(1) if major is not None: if major in penStore.data: if minor is None: if len(penStore.data[major]) > 0: if raw_input("are you sure (y/n)? ") not in ['y', 'Y', 'yes', 'Yes']: return ExitStatus.ABORT penStore.deleteList(major) puts("list deleted") elif minor in penStore.data[major]: penStore.deleteNote(major, minor) puts("note deleted") else: puts("no such note, sorry! (%s)" % minor) else: puts("no such list, sorry! (%s)" % major) else: print """ - pen: delete help ------------------------------------------------------------ pen delete <list> deletes list and all of its notes pen delete <list> <note> deletes note """
python
def cmd_delete(args): """Deletes a node""" major = args.get(0) minor = args.get(1) if major is not None: if major in penStore.data: if minor is None: if len(penStore.data[major]) > 0: if raw_input("are you sure (y/n)? ") not in ['y', 'Y', 'yes', 'Yes']: return ExitStatus.ABORT penStore.deleteList(major) puts("list deleted") elif minor in penStore.data[major]: penStore.deleteNote(major, minor) puts("note deleted") else: puts("no such note, sorry! (%s)" % minor) else: puts("no such list, sorry! (%s)" % major) else: print """ - pen: delete help ------------------------------------------------------------ pen delete <list> deletes list and all of its notes pen delete <list> <note> deletes note """
[ "def", "cmd_delete", "(", "args", ")", ":", "major", "=", "args", ".", "get", "(", "0", ")", "minor", "=", "args", ".", "get", "(", "1", ")", "if", "major", "is", "not", "None", ":", "if", "major", "in", "penStore", ".", "data", ":", "if", "min...
Deletes a node
[ "Deletes", "a", "node" ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/core.py#L76-L101
train
55,131
uw-it-aca/uw-restclients-django-utils
rc_django/decorators.py
restclient_admin_required
def restclient_admin_required(view_func): """ View decorator that checks whether the user is permitted to view proxy restclients. Calls login_required in case the user is not authenticated. """ def wrapper(request, *args, **kwargs): template = 'access_denied.html' if hasattr(settings, 'RESTCLIENTS_ADMIN_AUTH_MODULE'): auth_func = import_string(settings.RESTCLIENTS_ADMIN_AUTH_MODULE) else: context = {'error_msg': ( "Your application must define an authorization function as " "RESTCLIENTS_ADMIN_AUTH_MODULE in settings.py.")} return render(request, template, context=context, status=401) service = args[0] if len(args) > 0 else None url = args[1] if len(args) > 1 else None if auth_func(request, service, url): return view_func(request, *args, **kwargs) return render(request, template, status=401) return login_required(function=wrapper)
python
def restclient_admin_required(view_func): """ View decorator that checks whether the user is permitted to view proxy restclients. Calls login_required in case the user is not authenticated. """ def wrapper(request, *args, **kwargs): template = 'access_denied.html' if hasattr(settings, 'RESTCLIENTS_ADMIN_AUTH_MODULE'): auth_func = import_string(settings.RESTCLIENTS_ADMIN_AUTH_MODULE) else: context = {'error_msg': ( "Your application must define an authorization function as " "RESTCLIENTS_ADMIN_AUTH_MODULE in settings.py.")} return render(request, template, context=context, status=401) service = args[0] if len(args) > 0 else None url = args[1] if len(args) > 1 else None if auth_func(request, service, url): return view_func(request, *args, **kwargs) return render(request, template, status=401) return login_required(function=wrapper)
[ "def", "restclient_admin_required", "(", "view_func", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "template", "=", "'access_denied.html'", "if", "hasattr", "(", "settings", ",", "'RESTCLIENTS_ADMIN_AUTH_MODULE...
View decorator that checks whether the user is permitted to view proxy restclients. Calls login_required in case the user is not authenticated.
[ "View", "decorator", "that", "checks", "whether", "the", "user", "is", "permitted", "to", "view", "proxy", "restclients", ".", "Calls", "login_required", "in", "case", "the", "user", "is", "not", "authenticated", "." ]
7e0d3ecd3075cd4e43867f426e6add2118a814f1
https://github.com/uw-it-aca/uw-restclients-django-utils/blob/7e0d3ecd3075cd4e43867f426e6add2118a814f1/rc_django/decorators.py#L7-L29
train
55,132
Nagasaki45/bibo
bibo/internals.py
destination_heuristic
def destination_heuristic(data): """ A heuristic to get the folder with all other files from bib, using majority vote. """ counter = collections.Counter() for entry in data: file_field = entry['fields'].get('file') if not file_field: continue path = os.path.dirname(file_field) counter[path] += 1 if not counter: # No paths found raise click.ClickException( 'Path finding heuristics failed: no paths in the database' ) # Find the paths that appears most often sorted_paths = sorted(counter, reverse=True) groupby = itertools.groupby(sorted_paths, key=len) _, group = next(groupby) # We know that there's at least one candidate. Make sure it's # the only one candidate = next(group) try: next(group) except StopIteration: return candidate else: raise click.ClickException( 'Path finding heuristics failed: ' 'there are multiple equally valid paths in the database' )
python
def destination_heuristic(data): """ A heuristic to get the folder with all other files from bib, using majority vote. """ counter = collections.Counter() for entry in data: file_field = entry['fields'].get('file') if not file_field: continue path = os.path.dirname(file_field) counter[path] += 1 if not counter: # No paths found raise click.ClickException( 'Path finding heuristics failed: no paths in the database' ) # Find the paths that appears most often sorted_paths = sorted(counter, reverse=True) groupby = itertools.groupby(sorted_paths, key=len) _, group = next(groupby) # We know that there's at least one candidate. Make sure it's # the only one candidate = next(group) try: next(group) except StopIteration: return candidate else: raise click.ClickException( 'Path finding heuristics failed: ' 'there are multiple equally valid paths in the database' )
[ "def", "destination_heuristic", "(", "data", ")", ":", "counter", "=", "collections", ".", "Counter", "(", ")", "for", "entry", "in", "data", ":", "file_field", "=", "entry", "[", "'fields'", "]", ".", "get", "(", "'file'", ")", "if", "not", "file_field"...
A heuristic to get the folder with all other files from bib, using majority vote.
[ "A", "heuristic", "to", "get", "the", "folder", "with", "all", "other", "files", "from", "bib", "using", "majority", "vote", "." ]
e6afb28711e78eb11475834d3f9455252ac9f347
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L39-L73
train
55,133
Nagasaki45/bibo
bibo/internals.py
remove_entry
def remove_entry(data, entry): ''' Remove an entry in place. ''' file_field = entry['fields'].get('file') if file_field: try: os.remove(file_field) except IOError: click.echo('This entry\'s file was missing') data.remove(entry)
python
def remove_entry(data, entry): ''' Remove an entry in place. ''' file_field = entry['fields'].get('file') if file_field: try: os.remove(file_field) except IOError: click.echo('This entry\'s file was missing') data.remove(entry)
[ "def", "remove_entry", "(", "data", ",", "entry", ")", ":", "file_field", "=", "entry", "[", "'fields'", "]", ".", "get", "(", "'file'", ")", "if", "file_field", ":", "try", ":", "os", ".", "remove", "(", "file_field", ")", "except", "IOError", ":", ...
Remove an entry in place.
[ "Remove", "an", "entry", "in", "place", "." ]
e6afb28711e78eb11475834d3f9455252ac9f347
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L76-L87
train
55,134
Nagasaki45/bibo
bibo/internals.py
string_to_basename
def string_to_basename(s): ''' Converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. ''' s = s.strip().lower() s = re.sub(r'[^\w\s-]', '', s) return re.sub(r'[\s-]+', '-', s)
python
def string_to_basename(s): ''' Converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. ''' s = s.strip().lower() s = re.sub(r'[^\w\s-]', '', s) return re.sub(r'[\s-]+', '-', s)
[ "def", "string_to_basename", "(", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", ".", "lower", "(", ")", "s", "=", "re", ".", "sub", "(", "r'[^\\w\\s-]'", ",", "''", ",", "s", ")", "return", "re", ".", "sub", "(", "r'[\\s-]+'", ",", "'-'...
Converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.
[ "Converts", "to", "lowercase", "removes", "non", "-", "alpha", "characters", "and", "converts", "spaces", "to", "hyphens", "." ]
e6afb28711e78eb11475834d3f9455252ac9f347
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L90-L97
train
55,135
Nagasaki45/bibo
bibo/internals.py
editor
def editor(*args, **kwargs): ''' Wrapper for `click.edit` that raises an error when None is returned. ''' result = click.edit(*args, **kwargs) if result is None: msg = 'Editor exited without saving, command aborted' raise click.ClickException(msg) return result
python
def editor(*args, **kwargs): ''' Wrapper for `click.edit` that raises an error when None is returned. ''' result = click.edit(*args, **kwargs) if result is None: msg = 'Editor exited without saving, command aborted' raise click.ClickException(msg) return result
[ "def", "editor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "click", ".", "edit", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "result", "is", "None", ":", "msg", "=", "'Editor exited without saving, command aborted'", ...
Wrapper for `click.edit` that raises an error when None is returned.
[ "Wrapper", "for", "click", ".", "edit", "that", "raises", "an", "error", "when", "None", "is", "returned", "." ]
e6afb28711e78eb11475834d3f9455252ac9f347
https://github.com/Nagasaki45/bibo/blob/e6afb28711e78eb11475834d3f9455252ac9f347/bibo/internals.py#L111-L119
train
55,136
ooici/elasticpy
elasticpy/facet.py
ElasticFacet.terms
def terms(self, facet_name, field, size=10, order=None, all_terms=False, exclude=[], regex='', regex_flags=''): ''' Allow to specify field facets that return the N most frequent terms. Ordering: Allow to control the ordering of the terms facets, to be ordered by count, term, reverse_count or reverse_term. The default is count. All Terms: Allow to get all the terms in the terms facet, ones that do not match a hit, will have a count of 0. Note, this should not be used with fields that have many terms. Excluding Terms: It is possible to specify a set of terms that should be excluded from the terms facet request result. Regex Patterns: The terms API allows to define regex expression that will control which terms will be included in the faceted list. ''' self[facet_name] = dict(terms=dict(field=field, size=size)) if order: self[facet_name][terms]['order'] = order if all_terms: self[facet_name][terms]['all_terms'] = True if exclude: self[facet_name][terms]['exclude'] = exclude if regex: self[facet_name][terms]['regex'] = regex if regex_flags: self[facet_name][terms]['regex_flags'] = regex_flags return self
python
def terms(self, facet_name, field, size=10, order=None, all_terms=False, exclude=[], regex='', regex_flags=''): ''' Allow to specify field facets that return the N most frequent terms. Ordering: Allow to control the ordering of the terms facets, to be ordered by count, term, reverse_count or reverse_term. The default is count. All Terms: Allow to get all the terms in the terms facet, ones that do not match a hit, will have a count of 0. Note, this should not be used with fields that have many terms. Excluding Terms: It is possible to specify a set of terms that should be excluded from the terms facet request result. Regex Patterns: The terms API allows to define regex expression that will control which terms will be included in the faceted list. ''' self[facet_name] = dict(terms=dict(field=field, size=size)) if order: self[facet_name][terms]['order'] = order if all_terms: self[facet_name][terms]['all_terms'] = True if exclude: self[facet_name][terms]['exclude'] = exclude if regex: self[facet_name][terms]['regex'] = regex if regex_flags: self[facet_name][terms]['regex_flags'] = regex_flags return self
[ "def", "terms", "(", "self", ",", "facet_name", ",", "field", ",", "size", "=", "10", ",", "order", "=", "None", ",", "all_terms", "=", "False", ",", "exclude", "=", "[", "]", ",", "regex", "=", "''", ",", "regex_flags", "=", "''", ")", ":", "sel...
Allow to specify field facets that return the N most frequent terms. Ordering: Allow to control the ordering of the terms facets, to be ordered by count, term, reverse_count or reverse_term. The default is count. All Terms: Allow to get all the terms in the terms facet, ones that do not match a hit, will have a count of 0. Note, this should not be used with fields that have many terms. Excluding Terms: It is possible to specify a set of terms that should be excluded from the terms facet request result. Regex Patterns: The terms API allows to define regex expression that will control which terms will be included in the faceted list.
[ "Allow", "to", "specify", "field", "facets", "that", "return", "the", "N", "most", "frequent", "terms", "." ]
ec221800a80c39e80d8c31667c5b138da39219f2
https://github.com/ooici/elasticpy/blob/ec221800a80c39e80d8c31667c5b138da39219f2/elasticpy/facet.py#L24-L46
train
55,137
toumorokoshi/sprinter
sprinter/next/environment/injections.py
backup_file
def backup_file(filename): """ create a backup of the file desired """ if not os.path.exists(filename): return BACKUP_SUFFIX = ".sprinter.bak" backup_filename = filename + BACKUP_SUFFIX shutil.copyfile(filename, backup_filename)
python
def backup_file(filename): """ create a backup of the file desired """ if not os.path.exists(filename): return BACKUP_SUFFIX = ".sprinter.bak" backup_filename = filename + BACKUP_SUFFIX shutil.copyfile(filename, backup_filename)
[ "def", "backup_file", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "BACKUP_SUFFIX", "=", "\".sprinter.bak\"", "backup_filename", "=", "filename", "+", "BACKUP_SUFFIX", "shutil", ".", "copyfile",...
create a backup of the file desired
[ "create", "a", "backup", "of", "the", "file", "desired" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L162-L170
train
55,138
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.inject
def inject(self, filename, content): """ add the injection content to the dictionary """ # ensure content always has one trailing newline content = _unicode(content).rstrip() + "\n" if filename not in self.inject_dict: self.inject_dict[filename] = "" self.inject_dict[filename] += content
python
def inject(self, filename, content): """ add the injection content to the dictionary """ # ensure content always has one trailing newline content = _unicode(content).rstrip() + "\n" if filename not in self.inject_dict: self.inject_dict[filename] = "" self.inject_dict[filename] += content
[ "def", "inject", "(", "self", ",", "filename", ",", "content", ")", ":", "# ensure content always has one trailing newline", "content", "=", "_unicode", "(", "content", ")", ".", "rstrip", "(", ")", "+", "\"\\n\"", "if", "filename", "not", "in", "self", ".", ...
add the injection content to the dictionary
[ "add", "the", "injection", "content", "to", "the", "dictionary" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L42-L48
train
55,139
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.commit
def commit(self): """ commit the injections desired, overwriting any previous injections in the file. """ self.logger.debug("Starting injections...") self.logger.debug("Injections dict is:") self.logger.debug(self.inject_dict) self.logger.debug("Clear list is:") self.logger.debug(self.clear_set) for filename, content in self.inject_dict.items(): content = _unicode(content) self.logger.debug("Injecting values into %s..." % filename) self.destructive_inject(filename, content) for filename in self.clear_set: self.logger.debug("Clearing injection from %s..." % filename) self.destructive_clear(filename)
python
def commit(self): """ commit the injections desired, overwriting any previous injections in the file. """ self.logger.debug("Starting injections...") self.logger.debug("Injections dict is:") self.logger.debug(self.inject_dict) self.logger.debug("Clear list is:") self.logger.debug(self.clear_set) for filename, content in self.inject_dict.items(): content = _unicode(content) self.logger.debug("Injecting values into %s..." % filename) self.destructive_inject(filename, content) for filename in self.clear_set: self.logger.debug("Clearing injection from %s..." % filename) self.destructive_clear(filename)
[ "def", "commit", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Starting injections...\"", ")", "self", ".", "logger", ".", "debug", "(", "\"Injections dict is:\"", ")", "self", ".", "logger", ".", "debug", "(", "self", ".", "inject_di...
commit the injections desired, overwriting any previous injections in the file.
[ "commit", "the", "injections", "desired", "overwriting", "any", "previous", "injections", "in", "the", "file", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L59-L72
train
55,140
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.injected
def injected(self, filename): """ Return true if the file has already been injected before. """ full_path = os.path.expanduser(filename) if not os.path.exists(full_path): return False with codecs.open(full_path, 'r+', encoding="utf-8") as fh: contents = fh.read() return self.wrapper_match.search(contents) is not None
python
def injected(self, filename): """ Return true if the file has already been injected before. """ full_path = os.path.expanduser(filename) if not os.path.exists(full_path): return False with codecs.open(full_path, 'r+', encoding="utf-8") as fh: contents = fh.read() return self.wrapper_match.search(contents) is not None
[ "def", "injected", "(", "self", ",", "filename", ")", ":", "full_path", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "full_path", ")", ":", "return", "False", "with", "codecs", "...
Return true if the file has already been injected before.
[ "Return", "true", "if", "the", "file", "has", "already", "been", "injected", "before", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L74-L81
train
55,141
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.destructive_inject
def destructive_inject(self, filename, content): """ Injects the injections desired immediately. This should generally be run only during the commit phase, when no future injections will be done. """ content = _unicode(content) backup_file(filename) full_path = self.__generate_file(filename) with codecs.open(full_path, 'r', encoding="utf-8") as f: new_content = self.inject_content(f.read(), content) with codecs.open(full_path, 'w+', encoding="utf-8") as f: f.write(new_content)
python
def destructive_inject(self, filename, content): """ Injects the injections desired immediately. This should generally be run only during the commit phase, when no future injections will be done. """ content = _unicode(content) backup_file(filename) full_path = self.__generate_file(filename) with codecs.open(full_path, 'r', encoding="utf-8") as f: new_content = self.inject_content(f.read(), content) with codecs.open(full_path, 'w+', encoding="utf-8") as f: f.write(new_content)
[ "def", "destructive_inject", "(", "self", ",", "filename", ",", "content", ")", ":", "content", "=", "_unicode", "(", "content", ")", "backup_file", "(", "filename", ")", "full_path", "=", "self", ".", "__generate_file", "(", "filename", ")", "with", "codecs...
Injects the injections desired immediately. This should generally be run only during the commit phase, when no future injections will be done.
[ "Injects", "the", "injections", "desired", "immediately", ".", "This", "should", "generally", "be", "run", "only", "during", "the", "commit", "phase", "when", "no", "future", "injections", "will", "be", "done", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L83-L95
train
55,142
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.__generate_file
def __generate_file(self, file_path): """ Generate the file at the file_path desired. Creates any needed directories on the way. returns the absolute path of the file. """ file_path = os.path.expanduser(file_path) if not os.path.exists(os.path.dirname(file_path)): self.logger.debug("Directories missing! Creating directories for %s..." % file_path) os.makedirs(os.path.dirname(file_path)) if not os.path.exists(file_path): open(file_path, "w+").close() return file_path
python
def __generate_file(self, file_path): """ Generate the file at the file_path desired. Creates any needed directories on the way. returns the absolute path of the file. """ file_path = os.path.expanduser(file_path) if not os.path.exists(os.path.dirname(file_path)): self.logger.debug("Directories missing! Creating directories for %s..." % file_path) os.makedirs(os.path.dirname(file_path)) if not os.path.exists(file_path): open(file_path, "w+").close() return file_path
[ "def", "__generate_file", "(", "self", ",", "file_path", ")", ":", "file_path", "=", "os", ".", "path", ".", "expanduser", "(", "file_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "file_path", ...
Generate the file at the file_path desired. Creates any needed directories on the way. returns the absolute path of the file.
[ "Generate", "the", "file", "at", "the", "file_path", "desired", ".", "Creates", "any", "needed", "directories", "on", "the", "way", ".", "returns", "the", "absolute", "path", "of", "the", "file", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L107-L118
train
55,143
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.in_noninjected_file
def in_noninjected_file(self, file_path, content): """ Checks if a string exists in the file, sans the injected """ if os.path.exists(file_path): file_content = codecs.open(file_path, encoding="utf-8").read() file_content = self.wrapper_match.sub(u"", file_content) else: file_content = "" return file_content.find(content) != -1
python
def in_noninjected_file(self, file_path, content): """ Checks if a string exists in the file, sans the injected """ if os.path.exists(file_path): file_content = codecs.open(file_path, encoding="utf-8").read() file_content = self.wrapper_match.sub(u"", file_content) else: file_content = "" return file_content.find(content) != -1
[ "def", "in_noninjected_file", "(", "self", ",", "file_path", ",", "content", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "file_content", "=", "codecs", ".", "open", "(", "file_path", ",", "encoding", "=", "\"utf-8\"", ")...
Checks if a string exists in the file, sans the injected
[ "Checks", "if", "a", "string", "exists", "in", "the", "file", "sans", "the", "injected" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L120-L127
train
55,144
toumorokoshi/sprinter
sprinter/next/environment/injections.py
Injections.clear_content
def clear_content(self, content): """ Clear the injected content from the content buffer, and return the results """ content = _unicode(content) return self.wrapper_match.sub("", content)
python
def clear_content(self, content): """ Clear the injected content from the content buffer, and return the results """ content = _unicode(content) return self.wrapper_match.sub("", content)
[ "def", "clear_content", "(", "self", ",", "content", ")", ":", "content", "=", "_unicode", "(", "content", ")", "return", "self", ".", "wrapper_match", ".", "sub", "(", "\"\"", ",", "content", ")" ]
Clear the injected content from the content buffer, and return the results
[ "Clear", "the", "injected", "content", "from", "the", "content", "buffer", "and", "return", "the", "results" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L154-L159
train
55,145
gtaylor/EVE-Market-Data-Structures
emds/data_structures.py
MarketOrderList.add_order
def add_order(self, order): """ Adds a MarketOrder instance to the list of market orders contained within this order list. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketOrder order: The order to add to this order list. """ # This key is used to group the orders based on region. key = '%s_%s' % (order.region_id, order.type_id) if not self._orders.has_key(key): # We don't have any orders for this yet. Prep the region+item # combo by instantiating a new MarketItemsInRegionList for # the MarketOrders. self.set_empty_region( order.region_id, order.type_id, order.generated_at ) # The MarketOrder gets stuffed into the MarketItemsInRegionList for this # item+region combo. self._orders[key].add_order(order)
python
def add_order(self, order): """ Adds a MarketOrder instance to the list of market orders contained within this order list. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketOrder order: The order to add to this order list. """ # This key is used to group the orders based on region. key = '%s_%s' % (order.region_id, order.type_id) if not self._orders.has_key(key): # We don't have any orders for this yet. Prep the region+item # combo by instantiating a new MarketItemsInRegionList for # the MarketOrders. self.set_empty_region( order.region_id, order.type_id, order.generated_at ) # The MarketOrder gets stuffed into the MarketItemsInRegionList for this # item+region combo. self._orders[key].add_order(order)
[ "def", "add_order", "(", "self", ",", "order", ")", ":", "# This key is used to group the orders based on region.", "key", "=", "'%s_%s'", "%", "(", "order", ".", "region_id", ",", "order", ".", "type_id", ")", "if", "not", "self", ".", "_orders", ".", "has_ke...
Adds a MarketOrder instance to the list of market orders contained within this order list. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketOrder order: The order to add to this order list.
[ "Adds", "a", "MarketOrder", "instance", "to", "the", "list", "of", "market", "orders", "contained", "within", "this", "order", "list", ".", "Does", "some", "behind", "-", "the", "-", "scenes", "magic", "to", "get", "it", "all", "ready", "for", "serializati...
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/data_structures.py#L121-L143
train
55,146
gtaylor/EVE-Market-Data-Structures
emds/data_structures.py
MarketHistoryList.add_entry
def add_entry(self, entry): """ Adds a MarketHistoryEntry instance to the list of market history entries contained within this instance. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketHistoryEntry entry: The history entry to add to instance. """ # This key is used to group the orders based on region. key = '%s_%s' % (entry.region_id, entry.type_id) if not self._history.has_key(key): # We don't have any orders for this yet. Prep the region+item # combo by instantiating a new MarketItemsInRegionList for # the MarketOrders. self.set_empty_region( entry.region_id, entry.type_id, entry.generated_at ) # The MarketOrder gets stuffed into the MarketItemsInRegionList for this # item+region combo. self._history[key].add_entry(entry)
python
def add_entry(self, entry): """ Adds a MarketHistoryEntry instance to the list of market history entries contained within this instance. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketHistoryEntry entry: The history entry to add to instance. """ # This key is used to group the orders based on region. key = '%s_%s' % (entry.region_id, entry.type_id) if not self._history.has_key(key): # We don't have any orders for this yet. Prep the region+item # combo by instantiating a new MarketItemsInRegionList for # the MarketOrders. self.set_empty_region( entry.region_id, entry.type_id, entry.generated_at ) # The MarketOrder gets stuffed into the MarketItemsInRegionList for this # item+region combo. self._history[key].add_entry(entry)
[ "def", "add_entry", "(", "self", ",", "entry", ")", ":", "# This key is used to group the orders based on region.", "key", "=", "'%s_%s'", "%", "(", "entry", ".", "region_id", ",", "entry", ".", "type_id", ")", "if", "not", "self", ".", "_history", ".", "has_k...
Adds a MarketHistoryEntry instance to the list of market history entries contained within this instance. Does some behind-the-scenes magic to get it all ready for serialization. :param MarketHistoryEntry entry: The history entry to add to instance.
[ "Adds", "a", "MarketHistoryEntry", "instance", "to", "the", "list", "of", "market", "history", "entries", "contained", "within", "this", "instance", ".", "Does", "some", "behind", "-", "the", "-", "scenes", "magic", "to", "get", "it", "all", "ready", "for", ...
77d69b24f2aada3aeff8fba3d75891bfba8fdcf3
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/data_structures.py#L449-L472
train
55,147
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._find_file
def _find_file(self, file_name: str, lookup_dir: Path) -> Path or None: '''Find a file in a directory by name. Check subdirectories recursively. :param file_name: Name of the file :lookup_dir: Starting directory :returns: Path to the found file or None if the file was not found :raises: FileNotFoundError ''' self.logger.debug('Trying to find the file {file_name} inside the directory {lookup_dir}') result = None for item in lookup_dir.rglob('*'): if item.name == file_name: result = item break else: raise FileNotFoundError(file_name) self.logger.debug('File found: {result}') return result
python
def _find_file(self, file_name: str, lookup_dir: Path) -> Path or None: '''Find a file in a directory by name. Check subdirectories recursively. :param file_name: Name of the file :lookup_dir: Starting directory :returns: Path to the found file or None if the file was not found :raises: FileNotFoundError ''' self.logger.debug('Trying to find the file {file_name} inside the directory {lookup_dir}') result = None for item in lookup_dir.rglob('*'): if item.name == file_name: result = item break else: raise FileNotFoundError(file_name) self.logger.debug('File found: {result}') return result
[ "def", "_find_file", "(", "self", ",", "file_name", ":", "str", ",", "lookup_dir", ":", "Path", ")", "->", "Path", "or", "None", ":", "self", ".", "logger", ".", "debug", "(", "'Trying to find the file {file_name} inside the directory {lookup_dir}'", ")", "result"...
Find a file in a directory by name. Check subdirectories recursively. :param file_name: Name of the file :lookup_dir: Starting directory :returns: Path to the found file or None if the file was not found :raises: FileNotFoundError
[ "Find", "a", "file", "in", "a", "directory", "by", "name", ".", "Check", "subdirectories", "recursively", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L28-L51
train
55,148
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._sync_repo
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path: '''Clone a Git repository to the cache dir. If it has been cloned before, update it. :param repo_url: Repository URL :param revision: Revision: branch, commit hash, or tag :returns: Path to the cloned repository ''' repo_name = repo_url.split('/')[-1].rsplit('.', maxsplit=1)[0] repo_path = (self._cache_path / repo_name).resolve() self.logger.debug(f'Synchronizing with repo; URL: {repo_url}, revision: {revision}') try: self.logger.debug(f'Cloning repo {repo_url} to {repo_path}') run( f'git clone {repo_url} {repo_path}', shell=True, check=True, stdout=PIPE, stderr=STDOUT ) except CalledProcessError as exception: if repo_path.exists(): self.logger.debug('Repo already cloned; pulling from remote') try: run( 'git pull', cwd=repo_path, shell=True, check=True, stdout=PIPE, stderr=STDOUT ) except CalledProcessError as exception: self.logger.warning(str(exception)) else: self.logger.error(str(exception)) if revision: run( f'git checkout {revision}', cwd=repo_path, shell=True, check=True, stdout=PIPE, stderr=STDOUT ) return repo_path
python
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path: '''Clone a Git repository to the cache dir. If it has been cloned before, update it. :param repo_url: Repository URL :param revision: Revision: branch, commit hash, or tag :returns: Path to the cloned repository ''' repo_name = repo_url.split('/')[-1].rsplit('.', maxsplit=1)[0] repo_path = (self._cache_path / repo_name).resolve() self.logger.debug(f'Synchronizing with repo; URL: {repo_url}, revision: {revision}') try: self.logger.debug(f'Cloning repo {repo_url} to {repo_path}') run( f'git clone {repo_url} {repo_path}', shell=True, check=True, stdout=PIPE, stderr=STDOUT ) except CalledProcessError as exception: if repo_path.exists(): self.logger.debug('Repo already cloned; pulling from remote') try: run( 'git pull', cwd=repo_path, shell=True, check=True, stdout=PIPE, stderr=STDOUT ) except CalledProcessError as exception: self.logger.warning(str(exception)) else: self.logger.error(str(exception)) if revision: run( f'git checkout {revision}', cwd=repo_path, shell=True, check=True, stdout=PIPE, stderr=STDOUT ) return repo_path
[ "def", "_sync_repo", "(", "self", ",", "repo_url", ":", "str", ",", "revision", ":", "str", "or", "None", "=", "None", ")", "->", "Path", ":", "repo_name", "=", "repo_url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ".", "rsplit", "(", "'...
Clone a Git repository to the cache dir. If it has been cloned before, update it. :param repo_url: Repository URL :param revision: Revision: branch, commit hash, or tag :returns: Path to the cloned repository
[ "Clone", "a", "Git", "repository", "to", "the", "cache", "dir", ".", "If", "it", "has", "been", "cloned", "before", "update", "it", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L53-L108
train
55,149
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._shift_headings
def _shift_headings(self, content: str, shift: int) -> str: '''Shift Markdown headings in a string by a given value. The shift can be positive or negative. :param content: Markdown content :param shift: Heading shift :returns: Markdown content with headings shifted by ``shift`` ''' def _sub(heading): new_heading_level = len(heading.group('hashes')) + shift self.logger.debug(f'Shift heading level to {new_heading_level}, heading title: {heading.group("title")}') if new_heading_level <= 6: return f'{"#" * new_heading_level} {heading.group("title")}{heading.group("tail")}' else: self.logger.debug('New heading level is out of range, using bold paragraph text instead of heading') return f'**{heading.group("title")}**{heading.group("tail")}' return self._heading_pattern.sub(_sub, content)
python
def _shift_headings(self, content: str, shift: int) -> str: '''Shift Markdown headings in a string by a given value. The shift can be positive or negative. :param content: Markdown content :param shift: Heading shift :returns: Markdown content with headings shifted by ``shift`` ''' def _sub(heading): new_heading_level = len(heading.group('hashes')) + shift self.logger.debug(f'Shift heading level to {new_heading_level}, heading title: {heading.group("title")}') if new_heading_level <= 6: return f'{"#" * new_heading_level} {heading.group("title")}{heading.group("tail")}' else: self.logger.debug('New heading level is out of range, using bold paragraph text instead of heading') return f'**{heading.group("title")}**{heading.group("tail")}' return self._heading_pattern.sub(_sub, content)
[ "def", "_shift_headings", "(", "self", ",", "content", ":", "str", ",", "shift", ":", "int", ")", "->", "str", ":", "def", "_sub", "(", "heading", ")", ":", "new_heading_level", "=", "len", "(", "heading", ".", "group", "(", "'hashes'", ")", ")", "+"...
Shift Markdown headings in a string by a given value. The shift can be positive or negative. :param content: Markdown content :param shift: Heading shift :returns: Markdown content with headings shifted by ``shift``
[ "Shift", "Markdown", "headings", "in", "a", "string", "by", "a", "given", "value", ".", "The", "shift", "can", "be", "positive", "or", "negative", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L110-L133
train
55,150
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._cut_from_heading_to_heading
def _cut_from_heading_to_heading( self, content: str, from_heading: str, to_heading: str or None = None, options={} ) -> str: '''Cut part of Markdown string between two headings, set internal heading level, and remove top heading. If only the starting heading is defined, cut to the next heading of the same level. Heading shift and top heading elimination are optional. :param content: Markdown content :param from_heading: Starting heading :param to_heading: Ending heading (will not be incuded in the output) :param options: ``sethead``, ``nohead`` :returns: Part of the Markdown content between headings with internal headings adjusted ''' self.logger.debug(f'Cutting from heading: {from_heading}, to heading: {to_heading}, options: {options}') from_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{from_heading}\s*$', flags=re.MULTILINE) if not from_heading_pattern.findall(content): return '' from_heading_line = from_heading_pattern.findall(content)[0] from_heading_level = len(self._heading_pattern.match(from_heading_line).group('hashes')) self.logger.debug(f'From heading level: {from_heading_level}') result = from_heading_pattern.split(content)[1] if to_heading: to_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{to_heading}\s*$', flags=re.MULTILINE) else: to_heading_pattern = re.compile( rf'^\#{{1,{from_heading_level}}}[^\#]+?$', flags=re.MULTILINE ) result = to_heading_pattern.split(result)[0] if not options.get('nohead'): result = from_heading_line + result if options.get('sethead'): if options['sethead'] > 0: result = self._shift_headings( result, options['sethead'] - from_heading_level ) return result
python
def _cut_from_heading_to_heading( self, content: str, from_heading: str, to_heading: str or None = None, options={} ) -> str: '''Cut part of Markdown string between two headings, set internal heading level, and remove top heading. If only the starting heading is defined, cut to the next heading of the same level. Heading shift and top heading elimination are optional. :param content: Markdown content :param from_heading: Starting heading :param to_heading: Ending heading (will not be incuded in the output) :param options: ``sethead``, ``nohead`` :returns: Part of the Markdown content between headings with internal headings adjusted ''' self.logger.debug(f'Cutting from heading: {from_heading}, to heading: {to_heading}, options: {options}') from_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{from_heading}\s*$', flags=re.MULTILINE) if not from_heading_pattern.findall(content): return '' from_heading_line = from_heading_pattern.findall(content)[0] from_heading_level = len(self._heading_pattern.match(from_heading_line).group('hashes')) self.logger.debug(f'From heading level: {from_heading_level}') result = from_heading_pattern.split(content)[1] if to_heading: to_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{to_heading}\s*$', flags=re.MULTILINE) else: to_heading_pattern = re.compile( rf'^\#{{1,{from_heading_level}}}[^\#]+?$', flags=re.MULTILINE ) result = to_heading_pattern.split(result)[0] if not options.get('nohead'): result = from_heading_line + result if options.get('sethead'): if options['sethead'] > 0: result = self._shift_headings( result, options['sethead'] - from_heading_level ) return result
[ "def", "_cut_from_heading_to_heading", "(", "self", ",", "content", ":", "str", ",", "from_heading", ":", "str", ",", "to_heading", ":", "str", "or", "None", "=", "None", ",", "options", "=", "{", "}", ")", "->", "str", ":", "self", ".", "logger", ".",...
Cut part of Markdown string between two headings, set internal heading level, and remove top heading. If only the starting heading is defined, cut to the next heading of the same level. Heading shift and top heading elimination are optional. :param content: Markdown content :param from_heading: Starting heading :param to_heading: Ending heading (will not be incuded in the output) :param options: ``sethead``, ``nohead`` :returns: Part of the Markdown content between headings with internal headings adjusted
[ "Cut", "part", "of", "Markdown", "string", "between", "two", "headings", "set", "internal", "heading", "level", "and", "remove", "top", "heading", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L156-L214
train
55,151
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._cut_to_heading
def _cut_to_heading( self, content: str, to_heading: str or None = None, options={} ) -> str: '''Cut part of Markdown string from the start to a certain heading, set internal heading level, and remove top heading. If not heading is defined, the whole string is returned. Heading shift and top heading elimination are optional. :param content: Markdown content :param to_heading: Ending heading (will not be incuded in the output) :param options: ``sethead``, ``nohead`` :returns: Part of the Markdown content from the start to ``to_heading``, with internal headings adjusted ''' self.logger.debug(f'Cutting to heading: {to_heading}, options: {options}') content_buffer = StringIO(content) first_line = content_buffer.readline() if self._heading_pattern.fullmatch(first_line): from_heading_line = first_line from_heading_level = len(self._heading_pattern.match(from_heading_line).group('hashes')) result = content_buffer.read() else: from_heading_line = '' from_heading_level = self._find_top_heading_level(content) result = content self.logger.debug(f'From heading level: {from_heading_level}') if to_heading: to_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{to_heading}\s*$', flags=re.MULTILINE) result = to_heading_pattern.split(result)[0] if not options.get('nohead'): result = from_heading_line + result if options.get('sethead'): if options['sethead'] > 0: result = self._shift_headings( result, options['sethead'] - from_heading_level ) return result
python
def _cut_to_heading( self, content: str, to_heading: str or None = None, options={} ) -> str: '''Cut part of Markdown string from the start to a certain heading, set internal heading level, and remove top heading. If not heading is defined, the whole string is returned. Heading shift and top heading elimination are optional. :param content: Markdown content :param to_heading: Ending heading (will not be incuded in the output) :param options: ``sethead``, ``nohead`` :returns: Part of the Markdown content from the start to ``to_heading``, with internal headings adjusted ''' self.logger.debug(f'Cutting to heading: {to_heading}, options: {options}') content_buffer = StringIO(content) first_line = content_buffer.readline() if self._heading_pattern.fullmatch(first_line): from_heading_line = first_line from_heading_level = len(self._heading_pattern.match(from_heading_line).group('hashes')) result = content_buffer.read() else: from_heading_line = '' from_heading_level = self._find_top_heading_level(content) result = content self.logger.debug(f'From heading level: {from_heading_level}') if to_heading: to_heading_pattern = re.compile(r'^\#{1,6}\s+' + rf'{to_heading}\s*$', flags=re.MULTILINE) result = to_heading_pattern.split(result)[0] if not options.get('nohead'): result = from_heading_line + result if options.get('sethead'): if options['sethead'] > 0: result = self._shift_headings( result, options['sethead'] - from_heading_level ) return result
[ "def", "_cut_to_heading", "(", "self", ",", "content", ":", "str", ",", "to_heading", ":", "str", "or", "None", "=", "None", ",", "options", "=", "{", "}", ")", "->", "str", ":", "self", ".", "logger", ".", "debug", "(", "f'Cutting to heading: {to_headin...
Cut part of Markdown string from the start to a certain heading, set internal heading level, and remove top heading. If not heading is defined, the whole string is returned. Heading shift and top heading elimination are optional. :param content: Markdown content :param to_heading: Ending heading (will not be incuded in the output) :param options: ``sethead``, ``nohead`` :returns: Part of the Markdown content from the start to ``to_heading``, with internal headings adjusted
[ "Cut", "part", "of", "Markdown", "string", "from", "the", "start", "to", "a", "certain", "heading", "set", "internal", "heading", "level", "and", "remove", "top", "heading", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L216-L269
train
55,152
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._adjust_image_paths
def _adjust_image_paths(self, content: str, md_file_path: Path) -> str: '''Locate images referenced in a Markdown string and replace their paths with the absolute ones. :param content: Markdown content :param md_file_path: Path to the Markdown file containing the content :returns: Markdown content with absolute image paths ''' def _sub(image): image_caption = image.group('caption') image_path = md_file_path.parent / Path(image.group('path')) self.logger.debug( f'Updating image reference; user specified path: {image.group("path")}, ' + f'absolute path: {image_path}, caption: {image_caption}' ) return f'![{image_caption}]({image_path.absolute().as_posix()})' return self._image_pattern.sub(_sub, content)
python
def _adjust_image_paths(self, content: str, md_file_path: Path) -> str: '''Locate images referenced in a Markdown string and replace their paths with the absolute ones. :param content: Markdown content :param md_file_path: Path to the Markdown file containing the content :returns: Markdown content with absolute image paths ''' def _sub(image): image_caption = image.group('caption') image_path = md_file_path.parent / Path(image.group('path')) self.logger.debug( f'Updating image reference; user specified path: {image.group("path")}, ' + f'absolute path: {image_path}, caption: {image_caption}' ) return f'![{image_caption}]({image_path.absolute().as_posix()})' return self._image_pattern.sub(_sub, content)
[ "def", "_adjust_image_paths", "(", "self", ",", "content", ":", "str", ",", "md_file_path", ":", "Path", ")", "->", "str", ":", "def", "_sub", "(", "image", ")", ":", "image_caption", "=", "image", ".", "group", "(", "'caption'", ")", "image_path", "=", ...
Locate images referenced in a Markdown string and replace their paths with the absolute ones. :param content: Markdown content :param md_file_path: Path to the Markdown file containing the content :returns: Markdown content with absolute image paths
[ "Locate", "images", "referenced", "in", "a", "Markdown", "string", "and", "replace", "their", "paths", "with", "the", "absolute", "ones", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L271-L292
train
55,153
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._get_src_file_path
def _get_src_file_path(self, markdown_file_path: Path) -> Path: '''Translate the path of Markdown file that is located inside the temporary working directory into the path of the corresponding Markdown file that is located inside the source directory of Foliant project. :param markdown_file_path: Path to Markdown file that is located inside the temporary working directory :returns: Mapping of Markdown file path to the source directory ''' path_relative_to_working_dir = markdown_file_path.relative_to(self.working_dir.resolve()) self.logger.debug( 'Currently processed Markdown file path relative to working dir: ' + f'{path_relative_to_working_dir}' ) path_mapped_to_src_dir = ( self.project_path.resolve() / self.config['src_dir'] / path_relative_to_working_dir ) self.logger.debug( 'Currently processed Markdown file path mapped to source dir: ' + f'{path_mapped_to_src_dir}' ) return path_mapped_to_src_dir
python
def _get_src_file_path(self, markdown_file_path: Path) -> Path: '''Translate the path of Markdown file that is located inside the temporary working directory into the path of the corresponding Markdown file that is located inside the source directory of Foliant project. :param markdown_file_path: Path to Markdown file that is located inside the temporary working directory :returns: Mapping of Markdown file path to the source directory ''' path_relative_to_working_dir = markdown_file_path.relative_to(self.working_dir.resolve()) self.logger.debug( 'Currently processed Markdown file path relative to working dir: ' + f'{path_relative_to_working_dir}' ) path_mapped_to_src_dir = ( self.project_path.resolve() / self.config['src_dir'] / path_relative_to_working_dir ) self.logger.debug( 'Currently processed Markdown file path mapped to source dir: ' + f'{path_mapped_to_src_dir}' ) return path_mapped_to_src_dir
[ "def", "_get_src_file_path", "(", "self", ",", "markdown_file_path", ":", "Path", ")", "->", "Path", ":", "path_relative_to_working_dir", "=", "markdown_file_path", ".", "relative_to", "(", "self", ".", "working_dir", ".", "resolve", "(", ")", ")", "self", ".", ...
Translate the path of Markdown file that is located inside the temporary working directory into the path of the corresponding Markdown file that is located inside the source directory of Foliant project. :param markdown_file_path: Path to Markdown file that is located inside the temporary working directory :returns: Mapping of Markdown file path to the source directory
[ "Translate", "the", "path", "of", "Markdown", "file", "that", "is", "located", "inside", "the", "temporary", "working", "directory", "into", "the", "path", "of", "the", "corresponding", "Markdown", "file", "that", "is", "located", "inside", "the", "source", "d...
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L294-L322
train
55,154
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor._get_included_file_path
def _get_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path: '''Resolve user specified path to the local included file. :param user_specified_path: User specified string that represents the path to a local file :param current_processed_file_path: Path to the currently processed Markdown file that contains include statements :returns: Local path of the included file relative to the currently processed Markdown file ''' self.logger.debug(f'Currently processed Markdown file: {current_processed_file_path}') included_file_path = (current_processed_file_path.parent / user_specified_path).resolve() self.logger.debug(f'User-specified included file path: {included_file_path}') if ( self.working_dir.resolve() in current_processed_file_path.parents and self.working_dir.resolve() not in included_file_path.parents ): self.logger.debug( 'Currently processed file is located inside the working dir, ' + 'but included file is located outside the working dir. ' + 'So currently processed file path should be rewritten with the path of corresponding file ' + 'that is located inside the source dir' ) included_file_path = ( self._get_src_file_path(current_processed_file_path).parent / user_specified_path ).resolve() else: self.logger.debug( 'Using these paths without changes' ) self.logger.debug(f'Finally, included file path: {included_file_path}') return included_file_path
python
def _get_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path: '''Resolve user specified path to the local included file. :param user_specified_path: User specified string that represents the path to a local file :param current_processed_file_path: Path to the currently processed Markdown file that contains include statements :returns: Local path of the included file relative to the currently processed Markdown file ''' self.logger.debug(f'Currently processed Markdown file: {current_processed_file_path}') included_file_path = (current_processed_file_path.parent / user_specified_path).resolve() self.logger.debug(f'User-specified included file path: {included_file_path}') if ( self.working_dir.resolve() in current_processed_file_path.parents and self.working_dir.resolve() not in included_file_path.parents ): self.logger.debug( 'Currently processed file is located inside the working dir, ' + 'but included file is located outside the working dir. ' + 'So currently processed file path should be rewritten with the path of corresponding file ' + 'that is located inside the source dir' ) included_file_path = ( self._get_src_file_path(current_processed_file_path).parent / user_specified_path ).resolve() else: self.logger.debug( 'Using these paths without changes' ) self.logger.debug(f'Finally, included file path: {included_file_path}') return included_file_path
[ "def", "_get_included_file_path", "(", "self", ",", "user_specified_path", ":", "str", ",", "current_processed_file_path", ":", "Path", ")", "->", "Path", ":", "self", ".", "logger", ".", "debug", "(", "f'Currently processed Markdown file: {current_processed_file_path}'",...
Resolve user specified path to the local included file. :param user_specified_path: User specified string that represents the path to a local file :param current_processed_file_path: Path to the currently processed Markdown file that contains include statements :returns: Local path of the included file relative to the currently processed Markdown file
[ "Resolve", "user", "specified", "path", "to", "the", "local", "included", "file", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L324-L365
train
55,155
foliant-docs/foliantcontrib.includes
foliant/preprocessors/includes.py
Preprocessor.process_includes
def process_includes(self, markdown_file_path: Path, content: str) -> str: '''Replace all include statements with the respective file contents. :param markdown_file_path: Path to curently processed Markdown file :param content: Markdown content :returns: Markdown content with resolved includes ''' markdown_file_path = markdown_file_path.resolve() self.logger.debug(f'Processing Markdown file: {markdown_file_path}') processed_content = '' include_statement_pattern = re.compile( rf'((?<!\<)\<{"|".join(self.tags)}(?:\s[^\<\>]*)?\>.*?\<\/{"|".join(self.tags)}\>)', flags=re.DOTALL ) content_parts = include_statement_pattern.split(content) for content_part in content_parts: include_statement = self.pattern.fullmatch(content_part) if include_statement: body = self._tag_body_pattern.match(include_statement.group('body').strip()) options = self.get_options(include_statement.group('options')) self.logger.debug(f'Processing include statement; body: {body}, options: {options}') if body.group('repo'): repo = body.group('repo') repo_from_alias = self.options['aliases'].get(repo) revision = None if repo_from_alias: self.logger.debug(f'Alias found: {repo}, resolved as: {repo_from_alias}') if '#' in repo_from_alias: repo_url, revision = repo_from_alias.split('#', maxsplit=1) else: repo_url = repo_from_alias else: repo_url = repo if body.group('revision'): revision = body.group('revision') self.logger.debug(f'Highest priority revision specified in the include statement: {revision}') self.logger.debug(f'File in Git repository referenced; URL: {repo_url}, revision: {revision}') repo_path = self._sync_repo(repo_url, revision) self.logger.debug(f'Local path of the repo: {repo_path}') included_file_path = repo_path / body.group('path') self.logger.debug(f'Resolved path to the included file: {included_file_path}') processed_content_part = self._process_include( included_file_path, body.group('from_heading'), body.group('to_heading'), options ) else: self.logger.debug('Local file referenced') included_file_path = self._get_included_file_path(body.group('path'), markdown_file_path) self.logger.debug(f'Resolved path to the included file: {included_file_path}') processed_content_part = self._process_include( included_file_path, body.group('from_heading'), body.group('to_heading'), options ) if self.options['recursive'] and self.pattern.search(processed_content_part): self.logger.debug('Recursive call of include statements processing') processed_content_part = self.process_includes(included_file_path, processed_content_part) if options.get('inline'): self.logger.debug('Processing included content part as inline') processed_content_part = re.sub(r'\s+', ' ', processed_content_part).strip() else: processed_content_part = content_part processed_content += processed_content_part return processed_content
python
def process_includes(self, markdown_file_path: Path, content: str) -> str: '''Replace all include statements with the respective file contents. :param markdown_file_path: Path to curently processed Markdown file :param content: Markdown content :returns: Markdown content with resolved includes ''' markdown_file_path = markdown_file_path.resolve() self.logger.debug(f'Processing Markdown file: {markdown_file_path}') processed_content = '' include_statement_pattern = re.compile( rf'((?<!\<)\<{"|".join(self.tags)}(?:\s[^\<\>]*)?\>.*?\<\/{"|".join(self.tags)}\>)', flags=re.DOTALL ) content_parts = include_statement_pattern.split(content) for content_part in content_parts: include_statement = self.pattern.fullmatch(content_part) if include_statement: body = self._tag_body_pattern.match(include_statement.group('body').strip()) options = self.get_options(include_statement.group('options')) self.logger.debug(f'Processing include statement; body: {body}, options: {options}') if body.group('repo'): repo = body.group('repo') repo_from_alias = self.options['aliases'].get(repo) revision = None if repo_from_alias: self.logger.debug(f'Alias found: {repo}, resolved as: {repo_from_alias}') if '#' in repo_from_alias: repo_url, revision = repo_from_alias.split('#', maxsplit=1) else: repo_url = repo_from_alias else: repo_url = repo if body.group('revision'): revision = body.group('revision') self.logger.debug(f'Highest priority revision specified in the include statement: {revision}') self.logger.debug(f'File in Git repository referenced; URL: {repo_url}, revision: {revision}') repo_path = self._sync_repo(repo_url, revision) self.logger.debug(f'Local path of the repo: {repo_path}') included_file_path = repo_path / body.group('path') self.logger.debug(f'Resolved path to the included file: {included_file_path}') processed_content_part = self._process_include( included_file_path, body.group('from_heading'), body.group('to_heading'), options ) else: self.logger.debug('Local file referenced') included_file_path = self._get_included_file_path(body.group('path'), markdown_file_path) self.logger.debug(f'Resolved path to the included file: {included_file_path}') processed_content_part = self._process_include( included_file_path, body.group('from_heading'), body.group('to_heading'), options ) if self.options['recursive'] and self.pattern.search(processed_content_part): self.logger.debug('Recursive call of include statements processing') processed_content_part = self.process_includes(included_file_path, processed_content_part) if options.get('inline'): self.logger.debug('Processing included content part as inline') processed_content_part = re.sub(r'\s+', ' ', processed_content_part).strip() else: processed_content_part = content_part processed_content += processed_content_part return processed_content
[ "def", "process_includes", "(", "self", ",", "markdown_file_path", ":", "Path", ",", "content", ":", "str", ")", "->", "str", ":", "markdown_file_path", "=", "markdown_file_path", ".", "resolve", "(", ")", "self", ".", "logger", ".", "debug", "(", "f'Process...
Replace all include statements with the respective file contents. :param markdown_file_path: Path to curently processed Markdown file :param content: Markdown content :returns: Markdown content with resolved includes
[ "Replace", "all", "include", "statements", "with", "the", "respective", "file", "contents", "." ]
4bd89f6d287c9e21246d984c90ad05c2ccd24fcc
https://github.com/foliant-docs/foliantcontrib.includes/blob/4bd89f6d287c9e21246d984c90ad05c2ccd24fcc/foliant/preprocessors/includes.py#L416-L516
train
55,156
nimbusproject/dashi
dashi/bootstrap/__init__.py
get_logger
def get_logger(name, CFG=None): """set up logging for a service using the py 2.7 dictConfig """ logger = logging.getLogger(name) if CFG: # Make log directory if it doesn't exist for handler in CFG.get('handlers', {}).itervalues(): if 'filename' in handler: log_dir = os.path.dirname(handler['filename']) if not os.path.exists(log_dir): os.makedirs(log_dir) try: #TODO: This requires python 2.7 logging.config.dictConfig(CFG) except AttributeError: print >> sys.stderr, '"logging.config.dictConfig" doesn\'t seem to be supported in your python' raise return logger
python
def get_logger(name, CFG=None): """set up logging for a service using the py 2.7 dictConfig """ logger = logging.getLogger(name) if CFG: # Make log directory if it doesn't exist for handler in CFG.get('handlers', {}).itervalues(): if 'filename' in handler: log_dir = os.path.dirname(handler['filename']) if not os.path.exists(log_dir): os.makedirs(log_dir) try: #TODO: This requires python 2.7 logging.config.dictConfig(CFG) except AttributeError: print >> sys.stderr, '"logging.config.dictConfig" doesn\'t seem to be supported in your python' raise return logger
[ "def", "get_logger", "(", "name", ",", "CFG", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "if", "CFG", ":", "# Make log directory if it doesn't exist", "for", "handler", "in", "CFG", ".", "get", "(", "'handlers'", "...
set up logging for a service using the py 2.7 dictConfig
[ "set", "up", "logging", "for", "a", "service", "using", "the", "py", "2", ".", "7", "dictConfig" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/bootstrap/__init__.py#L238-L258
train
55,157
thewca/wca-regulations-compiler
wrc/parse/lexer.py
WCALexer.t_trailingwhitespace
def t_trailingwhitespace(self, token): ur'.+? \n' print "Error: trailing whitespace at line %s in text '%s'" % (token.lexer.lineno + 1, token.value[:-1]) token.lexer.lexerror = True token.lexer.skip(1)
python
def t_trailingwhitespace(self, token): ur'.+? \n' print "Error: trailing whitespace at line %s in text '%s'" % (token.lexer.lineno + 1, token.value[:-1]) token.lexer.lexerror = True token.lexer.skip(1)
[ "def", "t_trailingwhitespace", "(", "self", ",", "token", ")", ":", "print", "\"Error: trailing whitespace at line %s in text '%s'\"", "%", "(", "token", ".", "lexer", ".", "lineno", "+", "1", ",", "token", ".", "value", "[", ":", "-", "1", "]", ")", "token"...
ur'.+? \n
[ "ur", ".", "+", "?", "\\", "n" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/parse/lexer.py#L142-L146
train
55,158
frascoweb/frasco
frasco/views.py
exec_before_request_actions
def exec_before_request_actions(actions, **kwargs): """Execute actions in the "before" and "before_METHOD" groups """ groups = ("before", "before_" + flask.request.method.lower()) return execute_actions(actions, limit_groups=groups, **kwargs)
python
def exec_before_request_actions(actions, **kwargs): """Execute actions in the "before" and "before_METHOD" groups """ groups = ("before", "before_" + flask.request.method.lower()) return execute_actions(actions, limit_groups=groups, **kwargs)
[ "def", "exec_before_request_actions", "(", "actions", ",", "*", "*", "kwargs", ")", ":", "groups", "=", "(", "\"before\"", ",", "\"before_\"", "+", "flask", ".", "request", ".", "method", ".", "lower", "(", ")", ")", "return", "execute_actions", "(", "acti...
Execute actions in the "before" and "before_METHOD" groups
[ "Execute", "actions", "in", "the", "before", "and", "before_METHOD", "groups" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L14-L18
train
55,159
frascoweb/frasco
frasco/views.py
exec_after_request_actions
def exec_after_request_actions(actions, response, **kwargs): """Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context. """ current_context["response"] = response groups = ("after_" + flask.request.method.lower(), "after") try: rv = execute_actions(actions, limit_groups=groups, **kwargs) except ReturnValueException as e: rv = e.value if rv: return rv return response
python
def exec_after_request_actions(actions, response, **kwargs): """Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context. """ current_context["response"] = response groups = ("after_" + flask.request.method.lower(), "after") try: rv = execute_actions(actions, limit_groups=groups, **kwargs) except ReturnValueException as e: rv = e.value if rv: return rv return response
[ "def", "exec_after_request_actions", "(", "actions", ",", "response", ",", "*", "*", "kwargs", ")", ":", "current_context", "[", "\"response\"", "]", "=", "response", "groups", "=", "(", "\"after_\"", "+", "flask", ".", "request", ".", "method", ".", "lower"...
Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context.
[ "Executes", "actions", "of", "the", "after", "and", "after_METHOD", "groups", ".", "A", "response", "var", "will", "be", "injected", "in", "the", "current", "context", "." ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L28-L40
train
55,160
frascoweb/frasco
frasco/views.py
as_view
def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs): """Decorator to transform a function into a view class. Be warned that this will replace the function with the view class. """ def decorator(f): if url is not None: f = expose(url, methods=methods)(f) clsdict = {"name": name or f.__name__, "actions": getattr(f, "actions", None), "url_rules": url_rules or getattr(f, "urls", None)} if isinstance(f, WithActionsDecorator): f = f.func clsdict['func'] = f def constructor(self, **ctorkwargs): for k, v in kwargs.items(): if k not in ctorkwargs or ctorkwargs[k] is None: ctorkwargs[k] = v view_class.__init__(self, func=f, **ctorkwargs) clsdict["__init__"] = constructor return type(f.__name__, (view_class,), clsdict) return decorator
python
def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs): """Decorator to transform a function into a view class. Be warned that this will replace the function with the view class. """ def decorator(f): if url is not None: f = expose(url, methods=methods)(f) clsdict = {"name": name or f.__name__, "actions": getattr(f, "actions", None), "url_rules": url_rules or getattr(f, "urls", None)} if isinstance(f, WithActionsDecorator): f = f.func clsdict['func'] = f def constructor(self, **ctorkwargs): for k, v in kwargs.items(): if k not in ctorkwargs or ctorkwargs[k] is None: ctorkwargs[k] = v view_class.__init__(self, func=f, **ctorkwargs) clsdict["__init__"] = constructor return type(f.__name__, (view_class,), clsdict) return decorator
[ "def", "as_view", "(", "url", "=", "None", ",", "methods", "=", "None", ",", "view_class", "=", "ActionsView", ",", "name", "=", "None", ",", "url_rules", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if",...
Decorator to transform a function into a view class. Be warned that this will replace the function with the view class.
[ "Decorator", "to", "transform", "a", "function", "into", "a", "view", "class", ".", "Be", "warned", "that", "this", "will", "replace", "the", "function", "with", "the", "view", "class", "." ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L159-L184
train
55,161
frascoweb/frasco
frasco/views.py
RegistrableViewMixin.register
def register(self, target): """Registers url_rules on the blueprint """ for rule, options in self.url_rules: target.add_url_rule(rule, self.name, self.dispatch_request, **options)
python
def register(self, target): """Registers url_rules on the blueprint """ for rule, options in self.url_rules: target.add_url_rule(rule, self.name, self.dispatch_request, **options)
[ "def", "register", "(", "self", ",", "target", ")", ":", "for", "rule", ",", "options", "in", "self", ".", "url_rules", ":", "target", ".", "add_url_rule", "(", "rule", ",", "self", ".", "name", ",", "self", ".", "dispatch_request", ",", "*", "*", "o...
Registers url_rules on the blueprint
[ "Registers", "url_rules", "on", "the", "blueprint" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L89-L93
train
55,162
frascoweb/frasco
frasco/views.py
ViewContainerMixin.view
def view(self, *args, **kwargs): """Decorator to automatically apply as_view decorator and register it. """ def decorator(f): kwargs.setdefault("view_class", self.view_class) return self.add_view(as_view(*args, **kwargs)(f)) return decorator
python
def view(self, *args, **kwargs): """Decorator to automatically apply as_view decorator and register it. """ def decorator(f): kwargs.setdefault("view_class", self.view_class) return self.add_view(as_view(*args, **kwargs)(f)) return decorator
[ "def", "view", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "kwargs", ".", "setdefault", "(", "\"view_class\"", ",", "self", ".", "view_class", ")", "return", "self", ".", "add_view", "(", ...
Decorator to automatically apply as_view decorator and register it.
[ "Decorator", "to", "automatically", "apply", "as_view", "decorator", "and", "register", "it", "." ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L199-L205
train
55,163
frascoweb/frasco
frasco/views.py
ViewContainerMixin.add_action_view
def add_action_view(self, name, url, actions, **kwargs): """Creates an ActionsView instance and registers it. """ view = ActionsView(name, url=url, self_var=self, **kwargs) if isinstance(actions, dict): for group, actions in actions.iteritems(): view.actions.extend(load_actions(actions, group=group or None)) else: view.actions.extend(load_actions(actions)) self.add_view(view) return view
python
def add_action_view(self, name, url, actions, **kwargs): """Creates an ActionsView instance and registers it. """ view = ActionsView(name, url=url, self_var=self, **kwargs) if isinstance(actions, dict): for group, actions in actions.iteritems(): view.actions.extend(load_actions(actions, group=group or None)) else: view.actions.extend(load_actions(actions)) self.add_view(view) return view
[ "def", "add_action_view", "(", "self", ",", "name", ",", "url", ",", "actions", ",", "*", "*", "kwargs", ")", ":", "view", "=", "ActionsView", "(", "name", ",", "url", "=", "url", ",", "self_var", "=", "self", ",", "*", "*", "kwargs", ")", "if", ...
Creates an ActionsView instance and registers it.
[ "Creates", "an", "ActionsView", "instance", "and", "registers", "it", "." ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L207-L217
train
55,164
bryanwweber/thermohw
thermohw/convert_thermo_exam.py
process
def process(exam_num: int, time: str, date: str) -> None: """Process the exams in the exam_num folder for the time.""" prefix = Path(f"exams/exam-{exam_num}") problems = list(prefix.glob(f"exam-{exam_num}-{time}-[0-9].ipynb")) problems = sorted(problems, key=lambda k: k.stem[-1]) output_directory = (prefix / "output").resolve() fw = FilesWriter(build_directory=str(output_directory)) assignment_zip_name = output_directory / f"exam-{exam_num}-{time}.zip" solution_zip_name = output_directory / f"exam-{exam_num}-{time}-soln.zip" solution_pdfs: List[BytesIO] = [] exam_date_time = datetime.strptime(time + date, "%H%M%d-%b-%Y") res: Dict[str, Union[str, int]] = { "exam_num": exam_num, "time": exam_date_time.strftime("%I:%M %p"), "date": exam_date_time.strftime("%b. %d, %Y"), "delete_pymarkdown": True, } for problem in problems: res["unique_key"] = problem.stem problem_fname = str(problem.resolve()) if problem.stem.endswith("1"): assignment_nb, _ = sa_nb_exp.from_filename(problem_fname, resources=res) with ZipFile(assignment_zip_name, mode="a") as zip_file: zip_file.writestr(problem.name, assignment_nb) else: assignment_nb, _ = prob_nb_exp.from_filename(problem_fname, resources=res) with ZipFile(assignment_zip_name, mode="a") as zip_file: zip_file.writestr(problem.name, assignment_nb) solution_pdf, _ = solution_pdf_exp.from_filename(problem_fname, resources=res) solution_pdfs.append(BytesIO(solution_pdf)) solution_nb, _ = solution_nb_exp.from_filename(problem_fname, resources=res) with ZipFile(solution_zip_name, mode="a") as zip_file: zip_file.writestr(problem.name, solution_nb) resources: Dict[str, Any] = { "metadata": { "name": f"exam-{exam_num}-{time}-soln", "path": str(prefix), "modified_date": datetime.today().strftime("%B %d, %Y"), }, "output_extension": ".pdf", } fw.write( combine_pdf_as_bytes(solution_pdfs), resources, f"exam-{exam_num}-{time}-soln" )
python
def process(exam_num: int, time: str, date: str) -> None: """Process the exams in the exam_num folder for the time.""" prefix = Path(f"exams/exam-{exam_num}") problems = list(prefix.glob(f"exam-{exam_num}-{time}-[0-9].ipynb")) problems = sorted(problems, key=lambda k: k.stem[-1]) output_directory = (prefix / "output").resolve() fw = FilesWriter(build_directory=str(output_directory)) assignment_zip_name = output_directory / f"exam-{exam_num}-{time}.zip" solution_zip_name = output_directory / f"exam-{exam_num}-{time}-soln.zip" solution_pdfs: List[BytesIO] = [] exam_date_time = datetime.strptime(time + date, "%H%M%d-%b-%Y") res: Dict[str, Union[str, int]] = { "exam_num": exam_num, "time": exam_date_time.strftime("%I:%M %p"), "date": exam_date_time.strftime("%b. %d, %Y"), "delete_pymarkdown": True, } for problem in problems: res["unique_key"] = problem.stem problem_fname = str(problem.resolve()) if problem.stem.endswith("1"): assignment_nb, _ = sa_nb_exp.from_filename(problem_fname, resources=res) with ZipFile(assignment_zip_name, mode="a") as zip_file: zip_file.writestr(problem.name, assignment_nb) else: assignment_nb, _ = prob_nb_exp.from_filename(problem_fname, resources=res) with ZipFile(assignment_zip_name, mode="a") as zip_file: zip_file.writestr(problem.name, assignment_nb) solution_pdf, _ = solution_pdf_exp.from_filename(problem_fname, resources=res) solution_pdfs.append(BytesIO(solution_pdf)) solution_nb, _ = solution_nb_exp.from_filename(problem_fname, resources=res) with ZipFile(solution_zip_name, mode="a") as zip_file: zip_file.writestr(problem.name, solution_nb) resources: Dict[str, Any] = { "metadata": { "name": f"exam-{exam_num}-{time}-soln", "path": str(prefix), "modified_date": datetime.today().strftime("%B %d, %Y"), }, "output_extension": ".pdf", } fw.write( combine_pdf_as_bytes(solution_pdfs), resources, f"exam-{exam_num}-{time}-soln" )
[ "def", "process", "(", "exam_num", ":", "int", ",", "time", ":", "str", ",", "date", ":", "str", ")", "->", "None", ":", "prefix", "=", "Path", "(", "f\"exams/exam-{exam_num}\"", ")", "problems", "=", "list", "(", "prefix", ".", "glob", "(", "f\"exam-{...
Process the exams in the exam_num folder for the time.
[ "Process", "the", "exams", "in", "the", "exam_num", "folder", "for", "the", "time", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/convert_thermo_exam.py#L63-L118
train
55,165
bryanwweber/thermohw
thermohw/convert_thermo_exam.py
main
def main(argv: Optional[Sequence[str]] = None) -> None: """Parse arguments and process the exam assignment.""" parser = ArgumentParser(description="Convert Jupyter Notebook exams to PDFs") parser.add_argument( "--exam", type=int, required=True, help="Exam number to convert", dest="exam_num", ) parser.add_argument( "--time", type=str, required=True, help="Time of exam to convert" ) parser.add_argument( "--date", type=str, required=True, help="The date the exam will take place" ) args = parser.parse_args(argv) process(args.exam_num, args.time, args.date)
python
def main(argv: Optional[Sequence[str]] = None) -> None: """Parse arguments and process the exam assignment.""" parser = ArgumentParser(description="Convert Jupyter Notebook exams to PDFs") parser.add_argument( "--exam", type=int, required=True, help="Exam number to convert", dest="exam_num", ) parser.add_argument( "--time", type=str, required=True, help="Time of exam to convert" ) parser.add_argument( "--date", type=str, required=True, help="The date the exam will take place" ) args = parser.parse_args(argv) process(args.exam_num, args.time, args.date)
[ "def", "main", "(", "argv", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", "=", "None", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"Convert Jupyter Notebook exams to PDFs\"", ")", "parser", ".", "add_argument",...
Parse arguments and process the exam assignment.
[ "Parse", "arguments", "and", "process", "the", "exam", "assignment", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/convert_thermo_exam.py#L121-L138
train
55,166
oxalorg/dystic
dystic/marker.py
Marker.extract_meta
def extract_meta(self, text): """ Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text """ first_line = True metadata = [] content = [] metadata_parsed = False for line in text.split('\n'): if first_line: first_line = False if line.strip() != '---': raise MetaParseException('Invalid metadata') else: continue if line.strip() == '' and not metadata_parsed: continue if line.strip() == '---' and not metadata_parsed: # reached the last line metadata_parsed = True elif not metadata_parsed: metadata.append(line) else: content.append(line) content = '\n'.join(content) try: metadata = yaml.load('\n'.join(metadata)) except: raise content = text metadata = yaml.load('') return content, metadata
python
def extract_meta(self, text): """ Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text """ first_line = True metadata = [] content = [] metadata_parsed = False for line in text.split('\n'): if first_line: first_line = False if line.strip() != '---': raise MetaParseException('Invalid metadata') else: continue if line.strip() == '' and not metadata_parsed: continue if line.strip() == '---' and not metadata_parsed: # reached the last line metadata_parsed = True elif not metadata_parsed: metadata.append(line) else: content.append(line) content = '\n'.join(content) try: metadata = yaml.load('\n'.join(metadata)) except: raise content = text metadata = yaml.load('') return content, metadata
[ "def", "extract_meta", "(", "self", ",", "text", ")", ":", "first_line", "=", "True", "metadata", "=", "[", "]", "content", "=", "[", "]", "metadata_parsed", "=", "False", "for", "line", "in", "text", ".", "split", "(", "'\\n'", ")", ":", "if", "firs...
Takes input as the entire file. Reads the first yaml document as metadata. and the rest of the document as text
[ "Takes", "input", "as", "the", "entire", "file", ".", "Reads", "the", "first", "yaml", "document", "as", "metadata", ".", "and", "the", "rest", "of", "the", "document", "as", "text" ]
6f5a449158ec12fc1c9cc25d85e2f8adc27885db
https://github.com/oxalorg/dystic/blob/6f5a449158ec12fc1c9cc25d85e2f8adc27885db/dystic/marker.py#L42-L78
train
55,167
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.set_defaults
def set_defaults(self): """ Add each model entry with it's default """ for key, value in self.spec.items(): setattr(self, key.upper(), value.get("default", None))
python
def set_defaults(self): """ Add each model entry with it's default """ for key, value in self.spec.items(): setattr(self, key.upper(), value.get("default", None))
[ "def", "set_defaults", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "spec", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ".", "upper", "(", ")", ",", "value", ".", "get", "(", "\"default\"", ",", "None...
Add each model entry with it's default
[ "Add", "each", "model", "entry", "with", "it", "s", "default" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L70-L74
train
55,168
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.load_env
def load_env(self): """ Load the model fron environment variables """ for key, value in self.spec.items(): if value['type'] in (dict, list): envar = (self.env_prefix + "_" + key).upper() try: envvar = env.json(envar, default=getattr(self, key.upper(), value.get('default'))) except ConfigurationError as _err: #pragma: no cover print(_err) self.log.critical(f"Error parsing json from env var. {os.environ.get(envar)}") print(envar) raise else: envvar = env((self.env_prefix + "_" + key).upper(), default=getattr(self, key.upper(), value.get('default')), cast=value['type']) setattr(self, key.upper(), envvar)
python
def load_env(self): """ Load the model fron environment variables """ for key, value in self.spec.items(): if value['type'] in (dict, list): envar = (self.env_prefix + "_" + key).upper() try: envvar = env.json(envar, default=getattr(self, key.upper(), value.get('default'))) except ConfigurationError as _err: #pragma: no cover print(_err) self.log.critical(f"Error parsing json from env var. {os.environ.get(envar)}") print(envar) raise else: envvar = env((self.env_prefix + "_" + key).upper(), default=getattr(self, key.upper(), value.get('default')), cast=value['type']) setattr(self, key.upper(), envvar)
[ "def", "load_env", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "spec", ".", "items", "(", ")", ":", "if", "value", "[", "'type'", "]", "in", "(", "dict", ",", "list", ")", ":", "envar", "=", "(", "self", ".", "env_pref...
Load the model fron environment variables
[ "Load", "the", "model", "fron", "environment", "variables" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L76-L94
train
55,169
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.parse_args
def parse_args(self): """ Parse the cli args Returns: args (namespace): The args """ parser = ArgumentParser(description='', formatter_class=RawTextHelpFormatter) parser.add_argument("--generate", action="store", dest='generate', choices=['command', 'docker-run', 'docker-compose', 'ini', 'env', 'kubernetes', 'readme', 'drone-plugin'], help="Generate a template ") parser.add_argument("--settings", action="store", dest='settings', help="Specify a settings file. (ie settings.dev)") for key, value in self.spec.items(): if value['type'] in [str, int, float]: parser.add_argument(f"--{key.lower()}", action="store", dest=key, type=value['type'], choices=value.get("choices"), help=self.help(value)) elif value['type'] == bool: parser.add_argument(f"--{key.lower()}", action="store", dest=key, type=lambda x:bool(strtobool(x)), choices=value.get("choices"), help=self.help(value)) elif value['type'] == list: parser.add_argument(f"--{key.lower()}", action="store", dest=key, nargs='+', choices=value.get("choices"), help=self.help(value)) elif value['type'] == dict: parser.add_argument(f"--{key.lower()}", action="store", dest=key, type=json.loads, choices=value.get("choices"), help=self.help(value)) args, _unknown = parser.parse_known_args() return args
python
def parse_args(self): """ Parse the cli args Returns: args (namespace): The args """ parser = ArgumentParser(description='', formatter_class=RawTextHelpFormatter) parser.add_argument("--generate", action="store", dest='generate', choices=['command', 'docker-run', 'docker-compose', 'ini', 'env', 'kubernetes', 'readme', 'drone-plugin'], help="Generate a template ") parser.add_argument("--settings", action="store", dest='settings', help="Specify a settings file. (ie settings.dev)") for key, value in self.spec.items(): if value['type'] in [str, int, float]: parser.add_argument(f"--{key.lower()}", action="store", dest=key, type=value['type'], choices=value.get("choices"), help=self.help(value)) elif value['type'] == bool: parser.add_argument(f"--{key.lower()}", action="store", dest=key, type=lambda x:bool(strtobool(x)), choices=value.get("choices"), help=self.help(value)) elif value['type'] == list: parser.add_argument(f"--{key.lower()}", action="store", dest=key, nargs='+', choices=value.get("choices"), help=self.help(value)) elif value['type'] == dict: parser.add_argument(f"--{key.lower()}", action="store", dest=key, type=json.loads, choices=value.get("choices"), help=self.help(value)) args, _unknown = parser.parse_known_args() return args
[ "def", "parse_args", "(", "self", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "''", ",", "formatter_class", "=", "RawTextHelpFormatter", ")", "parser", ".", "add_argument", "(", "\"--generate\"", ",", "action", "=", "\"store\"", ",", "d...
Parse the cli args Returns: args (namespace): The args
[ "Parse", "the", "cli", "args" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L97-L133
train
55,170
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.add_args
def add_args(self, args): """ Add the args Args: args (namespace): The commandline args """ for key, value in vars(args).items(): if value is not None: setattr(self, key.upper(), value)
python
def add_args(self, args): """ Add the args Args: args (namespace): The commandline args """ for key, value in vars(args).items(): if value is not None: setattr(self, key.upper(), value)
[ "def", "add_args", "(", "self", ",", "args", ")", ":", "for", "key", ",", "value", "in", "vars", "(", "args", ")", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "setattr", "(", "self", ",", "key", ".", "upper", "(", ")",...
Add the args Args: args (namespace): The commandline args
[ "Add", "the", "args" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L135-L144
train
55,171
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.load_ini
def load_ini(self, ini_file): """ Load the contents from the ini file Args: ini_file (str): The file from which the settings should be loaded """ if ini_file and not os.path.exists(ini_file): self.log.critical(f"Settings file specified but not found. {ini_file}") sys.exit(1) if not ini_file: ini_file = f"{self.cwd}/settings.ini" if os.path.exists(ini_file): config = configparser.RawConfigParser(allow_no_value=True) config.read(ini_file) for key, value in self.spec.items(): entry = None if value['type'] == str: entry = config.get("settings", option=key.lower(), fallback=None) elif value['type'] == bool: entry = config.getboolean("settings", option=key.lower(), fallback=None) elif value['type'] == int: entry = config.getint("settings", option=key.lower(), fallback=None) elif value['type'] == float: entry = config.getfloat("settings", option=key.lower(), fallback=None) elif value['type'] in [list, dict]: entries = config.get("settings", option=key.lower(), fallback=None) if entries: try: entry = json.loads(entries) except json.decoder.JSONDecodeError as _err: #pragma: no cover self.log.critical(f"Error parsing json from ini file. {entries}") sys.exit(1) if entry is not None: setattr(self, key.upper(), entry)
python
def load_ini(self, ini_file): """ Load the contents from the ini file Args: ini_file (str): The file from which the settings should be loaded """ if ini_file and not os.path.exists(ini_file): self.log.critical(f"Settings file specified but not found. {ini_file}") sys.exit(1) if not ini_file: ini_file = f"{self.cwd}/settings.ini" if os.path.exists(ini_file): config = configparser.RawConfigParser(allow_no_value=True) config.read(ini_file) for key, value in self.spec.items(): entry = None if value['type'] == str: entry = config.get("settings", option=key.lower(), fallback=None) elif value['type'] == bool: entry = config.getboolean("settings", option=key.lower(), fallback=None) elif value['type'] == int: entry = config.getint("settings", option=key.lower(), fallback=None) elif value['type'] == float: entry = config.getfloat("settings", option=key.lower(), fallback=None) elif value['type'] in [list, dict]: entries = config.get("settings", option=key.lower(), fallback=None) if entries: try: entry = json.loads(entries) except json.decoder.JSONDecodeError as _err: #pragma: no cover self.log.critical(f"Error parsing json from ini file. {entries}") sys.exit(1) if entry is not None: setattr(self, key.upper(), entry)
[ "def", "load_ini", "(", "self", ",", "ini_file", ")", ":", "if", "ini_file", "and", "not", "os", ".", "path", ".", "exists", "(", "ini_file", ")", ":", "self", ".", "log", ".", "critical", "(", "f\"Settings file specified but not found. {ini_file}\"", ")", "...
Load the contents from the ini file Args: ini_file (str): The file from which the settings should be loaded
[ "Load", "the", "contents", "from", "the", "ini", "file" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L146-L180
train
55,172
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.check_required
def check_required(self): """ Check all required settings have been provided """ die = False for key, value in self.spec.items(): if not getattr(self, key.upper()) and value['required']: print(f"{key} is a required setting. " "Set via command-line params, env or file. " "For examples, try '--generate' or '--help'.") die = True if die: sys.exit(1)
python
def check_required(self): """ Check all required settings have been provided """ die = False for key, value in self.spec.items(): if not getattr(self, key.upper()) and value['required']: print(f"{key} is a required setting. " "Set via command-line params, env or file. " "For examples, try '--generate' or '--help'.") die = True if die: sys.exit(1)
[ "def", "check_required", "(", "self", ")", ":", "die", "=", "False", "for", "key", ",", "value", "in", "self", ".", "spec", ".", "items", "(", ")", ":", "if", "not", "getattr", "(", "self", ",", "key", ".", "upper", "(", ")", ")", "and", "value",...
Check all required settings have been provided
[ "Check", "all", "required", "settings", "have", "been", "provided" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L182-L193
train
55,173
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate
def generate(self): """ Generate sample settings """ otype = getattr(self, 'GENERATE') if otype: if otype == 'env': self.generate_env() elif otype == "command": self.generate_command() elif otype == "docker-run": self.generate_docker_run() elif otype == "docker-compose": self.generate_docker_compose() elif otype == "kubernetes": self.generate_kubernetes() elif otype == 'ini': self.generate_ini() elif otype == 'readme': self.generate_readme() elif otype == 'drone-plugin': self.generate_drone_plugin() sys.exit(0)
python
def generate(self): """ Generate sample settings """ otype = getattr(self, 'GENERATE') if otype: if otype == 'env': self.generate_env() elif otype == "command": self.generate_command() elif otype == "docker-run": self.generate_docker_run() elif otype == "docker-compose": self.generate_docker_compose() elif otype == "kubernetes": self.generate_kubernetes() elif otype == 'ini': self.generate_ini() elif otype == 'readme': self.generate_readme() elif otype == 'drone-plugin': self.generate_drone_plugin() sys.exit(0)
[ "def", "generate", "(", "self", ")", ":", "otype", "=", "getattr", "(", "self", ",", "'GENERATE'", ")", "if", "otype", ":", "if", "otype", "==", "'env'", ":", "self", ".", "generate_env", "(", ")", "elif", "otype", "==", "\"command\"", ":", "self", "...
Generate sample settings
[ "Generate", "sample", "settings" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L195-L217
train
55,174
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_env
def generate_env(self): """ Generate sample environment variables """ for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in (dict, list): value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = f"{self.spec[key].get('example', '')}" print(f"export {self.env_prefix}_{key.upper()}={value}")
python
def generate_env(self): """ Generate sample environment variables """ for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in (dict, list): value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = f"{self.spec[key].get('example', '')}" print(f"export {self.env_prefix}_{key.upper()}={value}")
[ "def", "generate_env", "(", "self", ")", ":", "for", "key", "in", "sorted", "(", "list", "(", "self", ".", "spec", ".", "keys", "(", ")", ")", ")", ":", "if", "self", ".", "spec", "[", "key", "]", "[", "'type'", "]", "in", "(", "dict", ",", "...
Generate sample environment variables
[ "Generate", "sample", "environment", "variables" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L220-L228
train
55,175
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_command
def generate_command(self): """ Generate a sample command """ example = [] example.append(f"{sys.argv[0]}") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] == list: value = " ".join(self.spec[key].get('example', '')) elif self.spec[key]['type'] == dict: value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = self.spec[key].get('example', '') string = f" --{key.lower()} {value}" example.append(string) print(" \\\n".join(example))
python
def generate_command(self): """ Generate a sample command """ example = [] example.append(f"{sys.argv[0]}") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] == list: value = " ".join(self.spec[key].get('example', '')) elif self.spec[key]['type'] == dict: value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = self.spec[key].get('example', '') string = f" --{key.lower()} {value}" example.append(string) print(" \\\n".join(example))
[ "def", "generate_command", "(", "self", ")", ":", "example", "=", "[", "]", "example", ".", "append", "(", "f\"{sys.argv[0]}\"", ")", "for", "key", "in", "sorted", "(", "list", "(", "self", ".", "spec", ".", "keys", "(", ")", ")", ")", ":", "if", "...
Generate a sample command
[ "Generate", "a", "sample", "command" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L230-L244
train
55,176
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_docker_run
def generate_docker_run(self): """ Generate a sample docker run """ example = [] example.append("docker run -it") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in (dict, list): value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = f"{self.spec[key].get('example', '')}" string = f" -e {self.env_prefix}_{key.upper()}={value}" example.append(string) example.append(" <container-name>") print(" \\\n".join(example))
python
def generate_docker_run(self): """ Generate a sample docker run """ example = [] example.append("docker run -it") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in (dict, list): value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = f"{self.spec[key].get('example', '')}" string = f" -e {self.env_prefix}_{key.upper()}={value}" example.append(string) example.append(" <container-name>") print(" \\\n".join(example))
[ "def", "generate_docker_run", "(", "self", ")", ":", "example", "=", "[", "]", "example", ".", "append", "(", "\"docker run -it\"", ")", "for", "key", "in", "sorted", "(", "list", "(", "self", ".", "spec", ".", "keys", "(", ")", ")", ")", ":", "if", ...
Generate a sample docker run
[ "Generate", "a", "sample", "docker", "run" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L246-L259
train
55,177
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_docker_compose
def generate_docker_compose(self): """ Generate a sample docker compose """ example = {} example['app'] = {} example['app']['environment'] = [] for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in (dict, list): value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = f"{self.spec[key].get('example', '')}" example['app']['environment'].append(f"{self.env_prefix}_{key.upper()}={value}") print(yaml.dump(example, default_flow_style=False))
python
def generate_docker_compose(self): """ Generate a sample docker compose """ example = {} example['app'] = {} example['app']['environment'] = [] for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in (dict, list): value = f"\'{json.dumps(self.spec[key].get('example', ''))}\'" else: value = f"{self.spec[key].get('example', '')}" example['app']['environment'].append(f"{self.env_prefix}_{key.upper()}={value}") print(yaml.dump(example, default_flow_style=False))
[ "def", "generate_docker_compose", "(", "self", ")", ":", "example", "=", "{", "}", "example", "[", "'app'", "]", "=", "{", "}", "example", "[", "'app'", "]", "[", "'environment'", "]", "=", "[", "]", "for", "key", "in", "sorted", "(", "list", "(", ...
Generate a sample docker compose
[ "Generate", "a", "sample", "docker", "compose" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L261-L273
train
55,178
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_ini
def generate_ini(self): """ Generate a sample ini """ example = [] example.append("[settings]") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in [list, dict]: value = json.dumps(self.spec[key].get('example', '')) else: value = self.spec[key].get('example', '') string = f"{key.lower()}={value}" example.append(string) print("\n".join(example))
python
def generate_ini(self): """ Generate a sample ini """ example = [] example.append("[settings]") for key in sorted(list(self.spec.keys())): if self.spec[key]['type'] in [list, dict]: value = json.dumps(self.spec[key].get('example', '')) else: value = self.spec[key].get('example', '') string = f"{key.lower()}={value}" example.append(string) print("\n".join(example))
[ "def", "generate_ini", "(", "self", ")", ":", "example", "=", "[", "]", "example", ".", "append", "(", "\"[settings]\"", ")", "for", "key", "in", "sorted", "(", "list", "(", "self", ".", "spec", ".", "keys", "(", ")", ")", ")", ":", "if", "self", ...
Generate a sample ini
[ "Generate", "a", "sample", "ini" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L275-L287
train
55,179
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_kubernetes
def generate_kubernetes(self): """ Generate a sample kubernetes """ example = {} example['spec'] = {} example['spec']['containers'] = [] example['spec']['containers'].append({"name": '', "image": '', "env": []}) for key, value in self.spec.items(): if value['type'] in (dict, list): kvalue = f"\'{json.dumps(value.get('example', ''))}\'" else: kvalue = f"{value.get('example', '')}" entry = {"name": f"{self.env_prefix}_{key.upper()}", "value": kvalue} example['spec']['containers'][0]['env'].append(entry) print(yaml.dump(example, default_flow_style=False))
python
def generate_kubernetes(self): """ Generate a sample kubernetes """ example = {} example['spec'] = {} example['spec']['containers'] = [] example['spec']['containers'].append({"name": '', "image": '', "env": []}) for key, value in self.spec.items(): if value['type'] in (dict, list): kvalue = f"\'{json.dumps(value.get('example', ''))}\'" else: kvalue = f"{value.get('example', '')}" entry = {"name": f"{self.env_prefix}_{key.upper()}", "value": kvalue} example['spec']['containers'][0]['env'].append(entry) print(yaml.dump(example, default_flow_style=False))
[ "def", "generate_kubernetes", "(", "self", ")", ":", "example", "=", "{", "}", "example", "[", "'spec'", "]", "=", "{", "}", "example", "[", "'spec'", "]", "[", "'containers'", "]", "=", "[", "]", "example", "[", "'spec'", "]", "[", "'containers'", "...
Generate a sample kubernetes
[ "Generate", "a", "sample", "kubernetes" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L289-L303
train
55,180
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_drone_plugin
def generate_drone_plugin(self): """ Generate a sample drone plugin configuration """ example = {} example['pipeline'] = {} example['pipeline']['appname'] = {} example['pipeline']['appname']['image'] = "" example['pipeline']['appname']['secrets'] = "" for key, value in self.spec.items(): if value['type'] in (dict, list): kvalue = f"\'{json.dumps(value.get('example', ''))}\'" else: kvalue = f"{value.get('example', '')}" example['pipeline']['appname'][key.lower()] = kvalue print(yaml.dump(example, default_flow_style=False))
python
def generate_drone_plugin(self): """ Generate a sample drone plugin configuration """ example = {} example['pipeline'] = {} example['pipeline']['appname'] = {} example['pipeline']['appname']['image'] = "" example['pipeline']['appname']['secrets'] = "" for key, value in self.spec.items(): if value['type'] in (dict, list): kvalue = f"\'{json.dumps(value.get('example', ''))}\'" else: kvalue = f"{value.get('example', '')}" example['pipeline']['appname'][key.lower()] = kvalue print(yaml.dump(example, default_flow_style=False))
[ "def", "generate_drone_plugin", "(", "self", ")", ":", "example", "=", "{", "}", "example", "[", "'pipeline'", "]", "=", "{", "}", "example", "[", "'pipeline'", "]", "[", "'appname'", "]", "=", "{", "}", "example", "[", "'pipeline'", "]", "[", "'appnam...
Generate a sample drone plugin configuration
[ "Generate", "a", "sample", "drone", "plugin", "configuration" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L305-L319
train
55,181
cidrblock/modelsettings
modelsettings/__init__.py
ModelSettings.generate_readme
def generate_readme(self): """ Generate a readme with all the generators """ print("## Examples of settings runtime params") print("### Command-line parameters") print("```") self.generate_command() print("```") print("### Environment variables") print("```") self.generate_env() print("```") print("### ini file") print("```") self.generate_ini() print("```") print("### docker run") print("```") self.generate_docker_run() print("```") print("### docker compose") print("```") self.generate_docker_compose() print("```") print("### kubernetes") print("```") self.generate_kubernetes() print("```") print("### drone plugin") print("```") self.generate_drone_plugin() print("```")
python
def generate_readme(self): """ Generate a readme with all the generators """ print("## Examples of settings runtime params") print("### Command-line parameters") print("```") self.generate_command() print("```") print("### Environment variables") print("```") self.generate_env() print("```") print("### ini file") print("```") self.generate_ini() print("```") print("### docker run") print("```") self.generate_docker_run() print("```") print("### docker compose") print("```") self.generate_docker_compose() print("```") print("### kubernetes") print("```") self.generate_kubernetes() print("```") print("### drone plugin") print("```") self.generate_drone_plugin() print("```")
[ "def", "generate_readme", "(", "self", ")", ":", "print", "(", "\"## Examples of settings runtime params\"", ")", "print", "(", "\"### Command-line parameters\"", ")", "print", "(", "\"```\"", ")", "self", ".", "generate_command", "(", ")", "print", "(", "\"```\"", ...
Generate a readme with all the generators
[ "Generate", "a", "readme", "with", "all", "the", "generators" ]
09763c111fb38b3ba7a13cc95ca59e4393fe75ba
https://github.com/cidrblock/modelsettings/blob/09763c111fb38b3ba7a13cc95ca59e4393fe75ba/modelsettings/__init__.py#L321-L352
train
55,182
Robpol86/Flask-Statics-Helper
flask_statics/resource_base.py
ResourceBase.file_exists
def file_exists(self, subdir, prefix, suffix): """Returns true if the resource file exists, else False. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string if the resource's directory structure is flat). prefix -- file name without the file extension. suffix -- file extension (if self.minify = True, includes .min before the extension). """ real_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, prefix + suffix) return os.path.exists(real_path)
python
def file_exists(self, subdir, prefix, suffix): """Returns true if the resource file exists, else False. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string if the resource's directory structure is flat). prefix -- file name without the file extension. suffix -- file extension (if self.minify = True, includes .min before the extension). """ real_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, prefix + suffix) return os.path.exists(real_path)
[ "def", "file_exists", "(", "self", ",", "subdir", ",", "prefix", ",", "suffix", ")", ":", "real_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "STATIC_DIR", ",", "self", ".", "DIR", ",", "subdir", ",", "prefix", "+", "suffix", ")", "...
Returns true if the resource file exists, else False. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string if the resource's directory structure is flat). prefix -- file name without the file extension. suffix -- file extension (if self.minify = True, includes .min before the extension).
[ "Returns", "true", "if", "the", "resource", "file", "exists", "else", "False", "." ]
b1771e65225f62b760b3ef841b710ff23ef6f83c
https://github.com/Robpol86/Flask-Statics-Helper/blob/b1771e65225f62b760b3ef841b710ff23ef6f83c/flask_statics/resource_base.py#L30-L40
train
55,183
Robpol86/Flask-Statics-Helper
flask_statics/resource_base.py
ResourceBase.add_css
def add_css(self, subdir, file_name_prefix): """Add a css file for this resource. If self.minify is True, checks if the .min.css file exists. If not, falls back to non-minified file. If that file also doesn't exist, IOError is raised. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string). file_name_prefix -- file name without the file extension. """ suffix_maxify = '.css' suffix_minify = '.min.css' if self.minify and self.file_exists(subdir, file_name_prefix, suffix_minify): self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_minify)) elif self.file_exists(subdir, file_name_prefix, suffix_maxify): self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_maxify)) else: file_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, file_name_prefix + suffix_maxify) raise IOError('Resource file not found: {0}'.format(file_path))
python
def add_css(self, subdir, file_name_prefix): """Add a css file for this resource. If self.minify is True, checks if the .min.css file exists. If not, falls back to non-minified file. If that file also doesn't exist, IOError is raised. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string). file_name_prefix -- file name without the file extension. """ suffix_maxify = '.css' suffix_minify = '.min.css' if self.minify and self.file_exists(subdir, file_name_prefix, suffix_minify): self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_minify)) elif self.file_exists(subdir, file_name_prefix, suffix_maxify): self.resources_css.append(posixpath.join(self.DIR, subdir, file_name_prefix + suffix_maxify)) else: file_path = os.path.join(self.STATIC_DIR, self.DIR, subdir, file_name_prefix + suffix_maxify) raise IOError('Resource file not found: {0}'.format(file_path))
[ "def", "add_css", "(", "self", ",", "subdir", ",", "file_name_prefix", ")", ":", "suffix_maxify", "=", "'.css'", "suffix_minify", "=", "'.min.css'", "if", "self", ".", "minify", "and", "self", ".", "file_exists", "(", "subdir", ",", "file_name_prefix", ",", ...
Add a css file for this resource. If self.minify is True, checks if the .min.css file exists. If not, falls back to non-minified file. If that file also doesn't exist, IOError is raised. Positional arguments: subdir -- sub directory name under the resource's main directory (e.g. css or js, or an empty string). file_name_prefix -- file name without the file extension.
[ "Add", "a", "css", "file", "for", "this", "resource", "." ]
b1771e65225f62b760b3ef841b710ff23ef6f83c
https://github.com/Robpol86/Flask-Statics-Helper/blob/b1771e65225f62b760b3ef841b710ff23ef6f83c/flask_statics/resource_base.py#L42-L60
train
55,184
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_pandas.py
read_dataframe_from_xls
def read_dataframe_from_xls(desired_type: Type[T], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ We register this method rather than the other because pandas guesses the encoding by itself. Also, it is easier to put a breakpoint and debug by trying various options to find the good one (in streaming mode you just have one try and then the stream is consumed) :param desired_type: :param file_path: :param encoding: :param logger: :param kwargs: :return: """ return pd.read_excel(file_path, **kwargs)
python
def read_dataframe_from_xls(desired_type: Type[T], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ We register this method rather than the other because pandas guesses the encoding by itself. Also, it is easier to put a breakpoint and debug by trying various options to find the good one (in streaming mode you just have one try and then the stream is consumed) :param desired_type: :param file_path: :param encoding: :param logger: :param kwargs: :return: """ return pd.read_excel(file_path, **kwargs)
[ "def", "read_dataframe_from_xls", "(", "desired_type", ":", "Type", "[", "T", "]", ",", "file_path", ":", "str", ",", "encoding", ":", "str", ",", "logger", ":", "Logger", ",", "*", "*", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "return", "pd",...
We register this method rather than the other because pandas guesses the encoding by itself. Also, it is easier to put a breakpoint and debug by trying various options to find the good one (in streaming mode you just have one try and then the stream is consumed) :param desired_type: :param file_path: :param encoding: :param logger: :param kwargs: :return:
[ "We", "register", "this", "method", "rather", "than", "the", "other", "because", "pandas", "guesses", "the", "encoding", "by", "itself", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_pandas.py#L25-L40
train
55,185
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_pandas.py
read_df_or_series_from_csv
def read_df_or_series_from_csv(desired_type: Type[pd.DataFrame], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ Helper method to read a dataframe from a csv file. By default this is well suited for a dataframe with headers in the first row, for example a parameter dataframe. :param desired_type: :param file_path: :param encoding: :param logger: :param kwargs: :return: """ if desired_type is pd.Series: # as recommended in http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.from_csv.html # and from http://stackoverflow.com/questions/15760856/how-to-read-a-pandas-series-from-a-csv-file # TODO there should be a way to decide between row-oriented (squeeze=True) and col-oriented (index_col=0) # note : squeeze=true only works for row-oriented, so we dont use it. We rather expect that a row-oriented # dataframe would be convertible to a series using the df to series converter below if 'index_col' not in kwargs.keys(): one_col_df = pd.read_csv(file_path, encoding=encoding, index_col=0, **kwargs) else: one_col_df = pd.read_csv(file_path, encoding=encoding, **kwargs) if one_col_df.shape[1] == 1: return one_col_df[one_col_df.columns[0]] else: raise Exception('Cannot build a series from this csv: it has more than two columns (one index + one value).' ' Probably the parsing chain $read_df_or_series_from_csv => single_row_or_col_df_to_series$' 'will work, though.') else: return pd.read_csv(file_path, encoding=encoding, **kwargs)
python
def read_df_or_series_from_csv(desired_type: Type[pd.DataFrame], file_path: str, encoding: str, logger: Logger, **kwargs) -> pd.DataFrame: """ Helper method to read a dataframe from a csv file. By default this is well suited for a dataframe with headers in the first row, for example a parameter dataframe. :param desired_type: :param file_path: :param encoding: :param logger: :param kwargs: :return: """ if desired_type is pd.Series: # as recommended in http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.from_csv.html # and from http://stackoverflow.com/questions/15760856/how-to-read-a-pandas-series-from-a-csv-file # TODO there should be a way to decide between row-oriented (squeeze=True) and col-oriented (index_col=0) # note : squeeze=true only works for row-oriented, so we dont use it. We rather expect that a row-oriented # dataframe would be convertible to a series using the df to series converter below if 'index_col' not in kwargs.keys(): one_col_df = pd.read_csv(file_path, encoding=encoding, index_col=0, **kwargs) else: one_col_df = pd.read_csv(file_path, encoding=encoding, **kwargs) if one_col_df.shape[1] == 1: return one_col_df[one_col_df.columns[0]] else: raise Exception('Cannot build a series from this csv: it has more than two columns (one index + one value).' ' Probably the parsing chain $read_df_or_series_from_csv => single_row_or_col_df_to_series$' 'will work, though.') else: return pd.read_csv(file_path, encoding=encoding, **kwargs)
[ "def", "read_df_or_series_from_csv", "(", "desired_type", ":", "Type", "[", "pd", ".", "DataFrame", "]", ",", "file_path", ":", "str", ",", "encoding", ":", "str", ",", "logger", ":", "Logger", ",", "*", "*", "kwargs", ")", "->", "pd", ".", "DataFrame", ...
Helper method to read a dataframe from a csv file. By default this is well suited for a dataframe with headers in the first row, for example a parameter dataframe. :param desired_type: :param file_path: :param encoding: :param logger: :param kwargs: :return:
[ "Helper", "method", "to", "read", "a", "dataframe", "from", "a", "csv", "file", ".", "By", "default", "this", "is", "well", "suited", "for", "a", "dataframe", "with", "headers", "in", "the", "first", "row", "for", "example", "a", "parameter", "dataframe", ...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_pandas.py#L43-L75
train
55,186
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_pandas.py
dict_to_df
def dict_to_df(desired_type: Type[T], dict_obj: Dict, logger: Logger, orient: str = None, **kwargs) -> pd.DataFrame: """ Helper method to convert a dictionary into a dataframe. It supports both simple key-value dicts as well as true table dicts. For this it uses pd.DataFrame constructor or pd.DataFrame.from_dict intelligently depending on the case. The orientation of the resulting dataframe can be configured, or left to default behaviour. Default orientation is different depending on the contents: * 'index' for 2-level dictionaries, in order to align as much as possible with the natural way to express rows in JSON * 'columns' for 1-level (simple key-value) dictionaries, so as to preserve the data types of the scalar values in the resulting dataframe columns if they are different :param desired_type: :param dict_obj: :param logger: :param orient: the orientation of the resulting dataframe. :param kwargs: :return: """ if len(dict_obj) > 0: first_val = dict_obj[next(iter(dict_obj))] if isinstance(first_val, dict) or isinstance(first_val, list): # --'full' table # default is index orientation orient = orient or 'index' # if orient is 'columns': # return pd.DataFrame(dict_obj) # else: return pd.DataFrame.from_dict(dict_obj, orient=orient) else: # --scalar > single-row or single-col # default is columns orientation orient = orient or 'columns' if orient is 'columns': return pd.DataFrame(dict_obj, index=[0]) else: res = pd.DataFrame.from_dict(dict_obj, orient=orient) res.index.name = 'key' return res.rename(columns={0: 'value'}) else: # for empty dictionaries, orientation does not matter # but maybe we should still create a column 'value' in this empty dataframe ? return pd.DataFrame.from_dict(dict_obj)
python
def dict_to_df(desired_type: Type[T], dict_obj: Dict, logger: Logger, orient: str = None, **kwargs) -> pd.DataFrame: """ Helper method to convert a dictionary into a dataframe. It supports both simple key-value dicts as well as true table dicts. For this it uses pd.DataFrame constructor or pd.DataFrame.from_dict intelligently depending on the case. The orientation of the resulting dataframe can be configured, or left to default behaviour. Default orientation is different depending on the contents: * 'index' for 2-level dictionaries, in order to align as much as possible with the natural way to express rows in JSON * 'columns' for 1-level (simple key-value) dictionaries, so as to preserve the data types of the scalar values in the resulting dataframe columns if they are different :param desired_type: :param dict_obj: :param logger: :param orient: the orientation of the resulting dataframe. :param kwargs: :return: """ if len(dict_obj) > 0: first_val = dict_obj[next(iter(dict_obj))] if isinstance(first_val, dict) or isinstance(first_val, list): # --'full' table # default is index orientation orient = orient or 'index' # if orient is 'columns': # return pd.DataFrame(dict_obj) # else: return pd.DataFrame.from_dict(dict_obj, orient=orient) else: # --scalar > single-row or single-col # default is columns orientation orient = orient or 'columns' if orient is 'columns': return pd.DataFrame(dict_obj, index=[0]) else: res = pd.DataFrame.from_dict(dict_obj, orient=orient) res.index.name = 'key' return res.rename(columns={0: 'value'}) else: # for empty dictionaries, orientation does not matter # but maybe we should still create a column 'value' in this empty dataframe ? return pd.DataFrame.from_dict(dict_obj)
[ "def", "dict_to_df", "(", "desired_type", ":", "Type", "[", "T", "]", ",", "dict_obj", ":", "Dict", ",", "logger", ":", "Logger", ",", "orient", ":", "str", "=", "None", ",", "*", "*", "kwargs", ")", "->", "pd", ".", "DataFrame", ":", "if", "len", ...
Helper method to convert a dictionary into a dataframe. It supports both simple key-value dicts as well as true table dicts. For this it uses pd.DataFrame constructor or pd.DataFrame.from_dict intelligently depending on the case. The orientation of the resulting dataframe can be configured, or left to default behaviour. Default orientation is different depending on the contents: * 'index' for 2-level dictionaries, in order to align as much as possible with the natural way to express rows in JSON * 'columns' for 1-level (simple key-value) dictionaries, so as to preserve the data types of the scalar values in the resulting dataframe columns if they are different :param desired_type: :param dict_obj: :param logger: :param orient: the orientation of the resulting dataframe. :param kwargs: :return:
[ "Helper", "method", "to", "convert", "a", "dictionary", "into", "a", "dataframe", ".", "It", "supports", "both", "simple", "key", "-", "value", "dicts", "as", "well", "as", "true", "table", "dicts", ".", "For", "this", "it", "uses", "pd", ".", "DataFrame...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_pandas.py#L100-L148
train
55,187
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_pandas.py
single_row_or_col_df_to_series
def single_row_or_col_df_to_series(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> pd.Series: """ Helper method to convert a dataframe with one row or one or two columns into a Series :param desired_type: :param single_col_df: :param logger: :param kwargs: :return: """ if single_rowcol_df.shape[0] == 1: # one row return single_rowcol_df.transpose()[0] elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex): # two columns but the index contains nothing but the row number : we can use the first column d = single_rowcol_df.set_index(single_rowcol_df.columns[0]) return d[d.columns[0]] elif single_rowcol_df.shape[1] == 1: # one column and one index d = single_rowcol_df return d[d.columns[0]] else: raise ValueError('Unable to convert provided dataframe to a series : ' 'expected exactly 1 row or 1 column, found : ' + str(single_rowcol_df.shape) + '')
python
def single_row_or_col_df_to_series(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> pd.Series: """ Helper method to convert a dataframe with one row or one or two columns into a Series :param desired_type: :param single_col_df: :param logger: :param kwargs: :return: """ if single_rowcol_df.shape[0] == 1: # one row return single_rowcol_df.transpose()[0] elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex): # two columns but the index contains nothing but the row number : we can use the first column d = single_rowcol_df.set_index(single_rowcol_df.columns[0]) return d[d.columns[0]] elif single_rowcol_df.shape[1] == 1: # one column and one index d = single_rowcol_df return d[d.columns[0]] else: raise ValueError('Unable to convert provided dataframe to a series : ' 'expected exactly 1 row or 1 column, found : ' + str(single_rowcol_df.shape) + '')
[ "def", "single_row_or_col_df_to_series", "(", "desired_type", ":", "Type", "[", "T", "]", ",", "single_rowcol_df", ":", "pd", ".", "DataFrame", ",", "logger", ":", "Logger", ",", "*", "*", "kwargs", ")", "->", "pd", ".", "Series", ":", "if", "single_rowcol...
Helper method to convert a dataframe with one row or one or two columns into a Series :param desired_type: :param single_col_df: :param logger: :param kwargs: :return:
[ "Helper", "method", "to", "convert", "a", "dataframe", "with", "one", "row", "or", "one", "or", "two", "columns", "into", "a", "Series" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_pandas.py#L156-L180
train
55,188
smarie/python-parsyfiles
parsyfiles/plugins_optional/support_for_pandas.py
single_row_or_col_df_to_dict
def single_row_or_col_df_to_dict(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> Dict[str, str]: """ Helper method to convert a dataframe with one row or one or two columns into a dictionary :param desired_type: :param single_rowcol_df: :param logger: :param kwargs: :return: """ if single_rowcol_df.shape[0] == 1: return single_rowcol_df.transpose()[0].to_dict() # return {col_name: single_rowcol_df[col_name][single_rowcol_df.index.values[0]] for col_name in single_rowcol_df.columns} elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex): # two columns but the index contains nothing but the row number : we can use the first column d = single_rowcol_df.set_index(single_rowcol_df.columns[0]) return d[d.columns[0]].to_dict() elif single_rowcol_df.shape[1] == 1: # one column and one index d = single_rowcol_df return d[d.columns[0]].to_dict() else: raise ValueError('Unable to convert provided dataframe to a parameters dictionary : ' 'expected exactly 1 row or 1 column, found : ' + str(single_rowcol_df.shape) + '')
python
def single_row_or_col_df_to_dict(desired_type: Type[T], single_rowcol_df: pd.DataFrame, logger: Logger, **kwargs)\ -> Dict[str, str]: """ Helper method to convert a dataframe with one row or one or two columns into a dictionary :param desired_type: :param single_rowcol_df: :param logger: :param kwargs: :return: """ if single_rowcol_df.shape[0] == 1: return single_rowcol_df.transpose()[0].to_dict() # return {col_name: single_rowcol_df[col_name][single_rowcol_df.index.values[0]] for col_name in single_rowcol_df.columns} elif single_rowcol_df.shape[1] == 2 and isinstance(single_rowcol_df.index, pd.RangeIndex): # two columns but the index contains nothing but the row number : we can use the first column d = single_rowcol_df.set_index(single_rowcol_df.columns[0]) return d[d.columns[0]].to_dict() elif single_rowcol_df.shape[1] == 1: # one column and one index d = single_rowcol_df return d[d.columns[0]].to_dict() else: raise ValueError('Unable to convert provided dataframe to a parameters dictionary : ' 'expected exactly 1 row or 1 column, found : ' + str(single_rowcol_df.shape) + '')
[ "def", "single_row_or_col_df_to_dict", "(", "desired_type", ":", "Type", "[", "T", "]", ",", "single_rowcol_df", ":", "pd", ".", "DataFrame", ",", "logger", ":", "Logger", ",", "*", "*", "kwargs", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "i...
Helper method to convert a dataframe with one row or one or two columns into a dictionary :param desired_type: :param single_rowcol_df: :param logger: :param kwargs: :return:
[ "Helper", "method", "to", "convert", "a", "dataframe", "with", "one", "row", "or", "one", "or", "two", "columns", "into", "a", "dictionary" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_pandas.py#L183-L207
train
55,189
mdickinson/refcycle
refcycle/directed_graph.py
DirectedGraph.full_subgraph
def full_subgraph(self, vertices): """ Return the subgraph of this graph whose vertices are the given ones and whose edges are all the edges of the original graph between those vertices. """ subgraph_vertices = {v for v in vertices} subgraph_edges = {edge for v in subgraph_vertices for edge in self._out_edges[v] if self._heads[edge] in subgraph_vertices} subgraph_heads = {edge: self._heads[edge] for edge in subgraph_edges} subgraph_tails = {edge: self._tails[edge] for edge in subgraph_edges} return DirectedGraph._raw( vertices=subgraph_vertices, edges=subgraph_edges, heads=subgraph_heads, tails=subgraph_tails, )
python
def full_subgraph(self, vertices): """ Return the subgraph of this graph whose vertices are the given ones and whose edges are all the edges of the original graph between those vertices. """ subgraph_vertices = {v for v in vertices} subgraph_edges = {edge for v in subgraph_vertices for edge in self._out_edges[v] if self._heads[edge] in subgraph_vertices} subgraph_heads = {edge: self._heads[edge] for edge in subgraph_edges} subgraph_tails = {edge: self._tails[edge] for edge in subgraph_edges} return DirectedGraph._raw( vertices=subgraph_vertices, edges=subgraph_edges, heads=subgraph_heads, tails=subgraph_tails, )
[ "def", "full_subgraph", "(", "self", ",", "vertices", ")", ":", "subgraph_vertices", "=", "{", "v", "for", "v", "in", "vertices", "}", "subgraph_edges", "=", "{", "edge", "for", "v", "in", "subgraph_vertices", "for", "edge", "in", "self", ".", "_out_edges"...
Return the subgraph of this graph whose vertices are the given ones and whose edges are all the edges of the original graph between those vertices.
[ "Return", "the", "subgraph", "of", "this", "graph", "whose", "vertices", "are", "the", "given", "ones", "and", "whose", "edges", "are", "all", "the", "edges", "of", "the", "original", "graph", "between", "those", "vertices", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/directed_graph.py#L96-L117
train
55,190
mdickinson/refcycle
refcycle/directed_graph.py
DirectedGraph._raw
def _raw(cls, vertices, edges, heads, tails): """ Private constructor for direct construction of a DirectedGraph from its consituents. """ self = object.__new__(cls) self._vertices = vertices self._edges = edges self._heads = heads self._tails = tails # For future use, map each vertex to its outward and inward edges. # These could be computed on demand instead of precomputed. self._out_edges = collections.defaultdict(set) self._in_edges = collections.defaultdict(set) for edge in self._edges: self._out_edges[self._tails[edge]].add(edge) self._in_edges[self._heads[edge]].add(edge) return self
python
def _raw(cls, vertices, edges, heads, tails): """ Private constructor for direct construction of a DirectedGraph from its consituents. """ self = object.__new__(cls) self._vertices = vertices self._edges = edges self._heads = heads self._tails = tails # For future use, map each vertex to its outward and inward edges. # These could be computed on demand instead of precomputed. self._out_edges = collections.defaultdict(set) self._in_edges = collections.defaultdict(set) for edge in self._edges: self._out_edges[self._tails[edge]].add(edge) self._in_edges[self._heads[edge]].add(edge) return self
[ "def", "_raw", "(", "cls", ",", "vertices", ",", "edges", ",", "heads", ",", "tails", ")", ":", "self", "=", "object", ".", "__new__", "(", "cls", ")", "self", ".", "_vertices", "=", "vertices", "self", ".", "_edges", "=", "edges", "self", ".", "_h...
Private constructor for direct construction of a DirectedGraph from its consituents.
[ "Private", "constructor", "for", "direct", "construction", "of", "a", "DirectedGraph", "from", "its", "consituents", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/directed_graph.py#L124-L143
train
55,191
mdickinson/refcycle
refcycle/directed_graph.py
DirectedGraph.from_out_edges
def from_out_edges(cls, vertices, edge_mapper): """ Create a DirectedGraph from a collection of vertices and a mapping giving the vertices that each vertex is connected to. """ vertices = set(vertices) edges = set() heads = {} tails = {} # Number the edges arbitrarily. edge_identifier = itertools.count() for tail in vertices: for head in edge_mapper[tail]: edge = next(edge_identifier) edges.add(edge) heads[edge] = head tails[edge] = tail return cls._raw( vertices=vertices, edges=edges, heads=heads, tails=tails, )
python
def from_out_edges(cls, vertices, edge_mapper): """ Create a DirectedGraph from a collection of vertices and a mapping giving the vertices that each vertex is connected to. """ vertices = set(vertices) edges = set() heads = {} tails = {} # Number the edges arbitrarily. edge_identifier = itertools.count() for tail in vertices: for head in edge_mapper[tail]: edge = next(edge_identifier) edges.add(edge) heads[edge] = head tails[edge] = tail return cls._raw( vertices=vertices, edges=edges, heads=heads, tails=tails, )
[ "def", "from_out_edges", "(", "cls", ",", "vertices", ",", "edge_mapper", ")", ":", "vertices", "=", "set", "(", "vertices", ")", "edges", "=", "set", "(", ")", "heads", "=", "{", "}", "tails", "=", "{", "}", "# Number the edges arbitrarily.", "edge_identi...
Create a DirectedGraph from a collection of vertices and a mapping giving the vertices that each vertex is connected to.
[ "Create", "a", "DirectedGraph", "from", "a", "collection", "of", "vertices", "and", "a", "mapping", "giving", "the", "vertices", "that", "each", "vertex", "is", "connected", "to", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/directed_graph.py#L146-L171
train
55,192
mdickinson/refcycle
refcycle/directed_graph.py
DirectedGraph.from_edge_pairs
def from_edge_pairs(cls, vertices, edge_pairs): """ Create a DirectedGraph from a collection of vertices and a collection of pairs giving links between the vertices. """ vertices = set(vertices) edges = set() heads = {} tails = {} # Number the edges arbitrarily. edge_identifier = itertools.count() for tail, head in edge_pairs: edge = next(edge_identifier) edges.add(edge) heads[edge] = head tails[edge] = tail return cls._raw( vertices=vertices, edges=edges, heads=heads, tails=tails, )
python
def from_edge_pairs(cls, vertices, edge_pairs): """ Create a DirectedGraph from a collection of vertices and a collection of pairs giving links between the vertices. """ vertices = set(vertices) edges = set() heads = {} tails = {} # Number the edges arbitrarily. edge_identifier = itertools.count() for tail, head in edge_pairs: edge = next(edge_identifier) edges.add(edge) heads[edge] = head tails[edge] = tail return cls._raw( vertices=vertices, edges=edges, heads=heads, tails=tails, )
[ "def", "from_edge_pairs", "(", "cls", ",", "vertices", ",", "edge_pairs", ")", ":", "vertices", "=", "set", "(", "vertices", ")", "edges", "=", "set", "(", ")", "heads", "=", "{", "}", "tails", "=", "{", "}", "# Number the edges arbitrarily.", "edge_identi...
Create a DirectedGraph from a collection of vertices and a collection of pairs giving links between the vertices.
[ "Create", "a", "DirectedGraph", "from", "a", "collection", "of", "vertices", "and", "a", "collection", "of", "pairs", "giving", "links", "between", "the", "vertices", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/directed_graph.py#L174-L198
train
55,193
mdickinson/refcycle
refcycle/directed_graph.py
DirectedGraph.annotated
def annotated(self): """ Return an AnnotatedGraph with the same structure as this graph. """ annotated_vertices = { vertex: AnnotatedVertex( id=vertex_id, annotation=six.text_type(vertex), ) for vertex_id, vertex in zip(itertools.count(), self.vertices) } annotated_edges = [ AnnotatedEdge( id=edge_id, annotation=six.text_type(edge), head=annotated_vertices[self.head(edge)].id, tail=annotated_vertices[self.tail(edge)].id, ) for edge_id, edge in zip(itertools.count(), self.edges) ] return AnnotatedGraph( vertices=annotated_vertices.values(), edges=annotated_edges, )
python
def annotated(self): """ Return an AnnotatedGraph with the same structure as this graph. """ annotated_vertices = { vertex: AnnotatedVertex( id=vertex_id, annotation=six.text_type(vertex), ) for vertex_id, vertex in zip(itertools.count(), self.vertices) } annotated_edges = [ AnnotatedEdge( id=edge_id, annotation=six.text_type(edge), head=annotated_vertices[self.head(edge)].id, tail=annotated_vertices[self.tail(edge)].id, ) for edge_id, edge in zip(itertools.count(), self.edges) ] return AnnotatedGraph( vertices=annotated_vertices.values(), edges=annotated_edges, )
[ "def", "annotated", "(", "self", ")", ":", "annotated_vertices", "=", "{", "vertex", ":", "AnnotatedVertex", "(", "id", "=", "vertex_id", ",", "annotation", "=", "six", ".", "text_type", "(", "vertex", ")", ",", ")", "for", "vertex_id", ",", "vertex", "i...
Return an AnnotatedGraph with the same structure as this graph.
[ "Return", "an", "AnnotatedGraph", "with", "the", "same", "structure", "as", "this", "graph", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/directed_graph.py#L200-L227
train
55,194
evansde77/dockerstache
src/dockerstache/dotfile.py
Dotfile.load
def load(self): """ read dotfile and populate self opts will override the dotfile settings, make sure everything is synced in both opts and this object """ if self.exists(): with open(self.dot_file, 'r') as handle: self.update(json.load(handle)) if self.options['context'] is not None: self['context'] = self.options['context'] else: self.options['context'] = self['context'] if self.options['defaults'] is not None: self['defaults'] = self.options['defaults'] else: self.options['defaults'] = self['defaults'] if self.options['output'] is not None: self['output'] = self.options['output'] if self.options.get('inclusive', False): self['inclusive'] = True if self.options.get('exclude', []): self['exclude'].extend(self.options['exclude']) if self['output'] is None: self['output'] = os.path.join(os.getcwd(), 'dockerstache-output') self['output_path'] = self.abs_output_dir() self['input_path'] = self.abs_input_dir() if self['context'] is not None: self['context_path'] = absolute_path(self['context']) if self['defaults'] is not None: self['defaults_path'] = absolute_path(self['defaults'])
python
def load(self): """ read dotfile and populate self opts will override the dotfile settings, make sure everything is synced in both opts and this object """ if self.exists(): with open(self.dot_file, 'r') as handle: self.update(json.load(handle)) if self.options['context'] is not None: self['context'] = self.options['context'] else: self.options['context'] = self['context'] if self.options['defaults'] is not None: self['defaults'] = self.options['defaults'] else: self.options['defaults'] = self['defaults'] if self.options['output'] is not None: self['output'] = self.options['output'] if self.options.get('inclusive', False): self['inclusive'] = True if self.options.get('exclude', []): self['exclude'].extend(self.options['exclude']) if self['output'] is None: self['output'] = os.path.join(os.getcwd(), 'dockerstache-output') self['output_path'] = self.abs_output_dir() self['input_path'] = self.abs_input_dir() if self['context'] is not None: self['context_path'] = absolute_path(self['context']) if self['defaults'] is not None: self['defaults_path'] = absolute_path(self['defaults'])
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "exists", "(", ")", ":", "with", "open", "(", "self", ".", "dot_file", ",", "'r'", ")", "as", "handle", ":", "self", ".", "update", "(", "json", ".", "load", "(", "handle", ")", ")", "if"...
read dotfile and populate self opts will override the dotfile settings, make sure everything is synced in both opts and this object
[ "read", "dotfile", "and", "populate", "self", "opts", "will", "override", "the", "dotfile", "settings", "make", "sure", "everything", "is", "synced", "in", "both", "opts", "and", "this", "object" ]
929c102e9fffde322dbf17f8e69533a00976aacb
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L91-L126
train
55,195
evansde77/dockerstache
src/dockerstache/dotfile.py
Dotfile.env_dictionary
def env_dictionary(self): """ convert the options to this script into an env var dictionary for pre and post scripts """ none_to_str = lambda x: str(x) if x else "" return {"DOCKERSTACHE_{}".format(k.upper()): none_to_str(v) for k, v in six.iteritems(self)}
python
def env_dictionary(self): """ convert the options to this script into an env var dictionary for pre and post scripts """ none_to_str = lambda x: str(x) if x else "" return {"DOCKERSTACHE_{}".format(k.upper()): none_to_str(v) for k, v in six.iteritems(self)}
[ "def", "env_dictionary", "(", "self", ")", ":", "none_to_str", "=", "lambda", "x", ":", "str", "(", "x", ")", "if", "x", "else", "\"\"", "return", "{", "\"DOCKERSTACHE_{}\"", ".", "format", "(", "k", ".", "upper", "(", ")", ")", ":", "none_to_str", "...
convert the options to this script into an env var dictionary for pre and post scripts
[ "convert", "the", "options", "to", "this", "script", "into", "an", "env", "var", "dictionary", "for", "pre", "and", "post", "scripts" ]
929c102e9fffde322dbf17f8e69533a00976aacb
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L152-L158
train
55,196
evansde77/dockerstache
src/dockerstache/dotfile.py
Dotfile.pre_script
def pre_script(self): """ execute the pre script if it is defined """ if self['pre_script'] is None: return LOGGER.info("Executing pre script: {}".format(self['pre_script'])) cmd = self['pre_script'] execute_command(self.abs_input_dir(), cmd, self.env_dictionary()) LOGGER.info("Pre Script completed")
python
def pre_script(self): """ execute the pre script if it is defined """ if self['pre_script'] is None: return LOGGER.info("Executing pre script: {}".format(self['pre_script'])) cmd = self['pre_script'] execute_command(self.abs_input_dir(), cmd, self.env_dictionary()) LOGGER.info("Pre Script completed")
[ "def", "pre_script", "(", "self", ")", ":", "if", "self", "[", "'pre_script'", "]", "is", "None", ":", "return", "LOGGER", ".", "info", "(", "\"Executing pre script: {}\"", ".", "format", "(", "self", "[", "'pre_script'", "]", ")", ")", "cmd", "=", "self...
execute the pre script if it is defined
[ "execute", "the", "pre", "script", "if", "it", "is", "defined" ]
929c102e9fffde322dbf17f8e69533a00976aacb
https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/dotfile.py#L160-L169
train
55,197
wdbm/propyte
propyte.py
say_tmp_filepath
def say_tmp_filepath( text = None, preference_program = "festival" ): """ Say specified text to a temporary file and return the filepath. """ filepath = shijian.tmp_filepath() + ".wav" say( text = text, preference_program = preference_program, filepath = filepath ) return filepath
python
def say_tmp_filepath( text = None, preference_program = "festival" ): """ Say specified text to a temporary file and return the filepath. """ filepath = shijian.tmp_filepath() + ".wav" say( text = text, preference_program = preference_program, filepath = filepath ) return filepath
[ "def", "say_tmp_filepath", "(", "text", "=", "None", ",", "preference_program", "=", "\"festival\"", ")", ":", "filepath", "=", "shijian", ".", "tmp_filepath", "(", ")", "+", "\".wav\"", "say", "(", "text", "=", "text", ",", "preference_program", "=", "prefe...
Say specified text to a temporary file and return the filepath.
[ "Say", "specified", "text", "to", "a", "temporary", "file", "and", "return", "the", "filepath", "." ]
0375a267c49e80223627331c8edbe13dfe9fd116
https://github.com/wdbm/propyte/blob/0375a267c49e80223627331c8edbe13dfe9fd116/propyte.py#L483-L496
train
55,198
aaronbassett/django-GNU-Terry-Pratchett
gnu_terry_pratchett/decorators.py
clacks_overhead
def clacks_overhead(fn): """ A Django view decorator that will add the `X-Clacks-Overhead` header. Usage: @clacks_overhead def my_view(request): return my_response """ @wraps(fn) def _wrapped(*args, **kw): response = fn(*args, **kw) response['X-Clacks-Overhead'] = 'GNU Terry Pratchett' return response return _wrapped
python
def clacks_overhead(fn): """ A Django view decorator that will add the `X-Clacks-Overhead` header. Usage: @clacks_overhead def my_view(request): return my_response """ @wraps(fn) def _wrapped(*args, **kw): response = fn(*args, **kw) response['X-Clacks-Overhead'] = 'GNU Terry Pratchett' return response return _wrapped
[ "def", "clacks_overhead", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "_wrapped", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "response", "=", "fn", "(", "*", "args", ",", "*", "*", "kw", ")", "response", "[", "'X-Clacks-Overhe...
A Django view decorator that will add the `X-Clacks-Overhead` header. Usage: @clacks_overhead def my_view(request): return my_response
[ "A", "Django", "view", "decorator", "that", "will", "add", "the", "X", "-", "Clacks", "-", "Overhead", "header", "." ]
3292af0d93c0e97515fce3ca513ec7eda1ba7c20
https://github.com/aaronbassett/django-GNU-Terry-Pratchett/blob/3292af0d93c0e97515fce3ca513ec7eda1ba7c20/gnu_terry_pratchett/decorators.py#L4-L21
train
55,199