repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
alexdej/puzpy
puz.py
restore
def restore(s, t): """ s is the source string, it can contain '.' t is the target, it's smaller than s by the number of '.'s in s Each char in s is replaced by the corresponding char in t, jumping over '.'s in s. >>> restore('ABC.DEF', 'XYZABC') 'XYZ.ABC' """ t = (c for c in t) return ''.join(next(t) if not is_blacksquare(c) else c for c in s)
python
def restore(s, t): t = (c for c in t) return ''.join(next(t) if not is_blacksquare(c) else c for c in s)
[ "def", "restore", "(", "s", ",", "t", ")", ":", "t", "=", "(", "c", "for", "c", "in", "t", ")", "return", "''", ".", "join", "(", "next", "(", "t", ")", "if", "not", "is_blacksquare", "(", "c", ")", "else", "c", "for", "c", "in", "s", ")" ]
s is the source string, it can contain '.' t is the target, it's smaller than s by the number of '.'s in s Each char in s is replaced by the corresponding char in t, jumping over '.'s in s. >>> restore('ABC.DEF', 'XYZABC') 'XYZ.ABC'
[ "s", "is", "the", "source", "string", "it", "can", "contain", ".", "t", "is", "the", "target", "it", "s", "smaller", "than", "s", "by", "the", "number", "of", ".", "s", "in", "s" ]
train
https://github.com/alexdej/puzpy/blob/8906ab899845d1200ac3411b4c2a2067cffa15d7/puz.py#L696-L708
instacart/ahab
ahab/__init__.py
Ahab.default
def default(event, data): """The default handler prints basic event info.""" messages = defaultdict(lambda: 'Avast:') messages['start'] = 'Thar she blows!' messages['tag'] = 'Thar she blows!' messages['stop'] = 'Away into the depths:' messages['destroy'] = 'Away into the depths:' messages['delete'] = 'Away into the depths:' status = get_status(event) message = messages[status] + ' %s/%s' log.info(message, status, get_id(event)) log.debug('"data": %s', form_json(data))
python
def default(event, data): messages = defaultdict(lambda: 'Avast:') messages['start'] = 'Thar she blows!' messages['tag'] = 'Thar she blows!' messages['stop'] = 'Away into the depths:' messages['destroy'] = 'Away into the depths:' messages['delete'] = 'Away into the depths:' status = get_status(event) message = messages[status] + ' %s/%s' log.info(message, status, get_id(event)) log.debug('"data": %s', form_json(data))
[ "def", "default", "(", "event", ",", "data", ")", ":", "messages", "=", "defaultdict", "(", "lambda", ":", "'Avast:'", ")", "messages", "[", "'start'", "]", "=", "'Thar she blows!'", "messages", "[", "'tag'", "]", "=", "'Thar she blows!'", "messages", "[", "'stop'", "]", "=", "'Away into the depths:'", "messages", "[", "'destroy'", "]", "=", "'Away into the depths:'", "messages", "[", "'delete'", "]", "=", "'Away into the depths:'", "status", "=", "get_status", "(", "event", ")", "message", "=", "messages", "[", "status", "]", "+", "' %s/%s'", "log", ".", "info", "(", "message", ",", "status", ",", "get_id", "(", "event", ")", ")", "log", ".", "debug", "(", "'\"data\": %s'", ",", "form_json", "(", "data", ")", ")" ]
The default handler prints basic event info.
[ "The", "default", "handler", "prints", "basic", "event", "info", "." ]
train
https://github.com/instacart/ahab/blob/da85dc6d89f5d0c49d3a26a25ea3710c7881b150/ahab/__init__.py#L58-L69
instacart/ahab
examples/nathook.py
table
def table(tab): """Access IPTables transactionally in a uniform way. Ensures all access is done without autocommit and that only the outer most task commits, and also ensures we refresh once and commit once. """ global open_tables if tab in open_tables: yield open_tables[tab] else: open_tables[tab] = iptc.Table(tab) open_tables[tab].refresh() open_tables[tab].autocommit = False yield open_tables[tab] open_tables[tab].commit() del open_tables[tab]
python
def table(tab): global open_tables if tab in open_tables: yield open_tables[tab] else: open_tables[tab] = iptc.Table(tab) open_tables[tab].refresh() open_tables[tab].autocommit = False yield open_tables[tab] open_tables[tab].commit() del open_tables[tab]
[ "def", "table", "(", "tab", ")", ":", "global", "open_tables", "if", "tab", "in", "open_tables", ":", "yield", "open_tables", "[", "tab", "]", "else", ":", "open_tables", "[", "tab", "]", "=", "iptc", ".", "Table", "(", "tab", ")", "open_tables", "[", "tab", "]", ".", "refresh", "(", ")", "open_tables", "[", "tab", "]", ".", "autocommit", "=", "False", "yield", "open_tables", "[", "tab", "]", "open_tables", "[", "tab", "]", ".", "commit", "(", ")", "del", "open_tables", "[", "tab", "]" ]
Access IPTables transactionally in a uniform way. Ensures all access is done without autocommit and that only the outer most task commits, and also ensures we refresh once and commit once.
[ "Access", "IPTables", "transactionally", "in", "a", "uniform", "way", "." ]
train
https://github.com/instacart/ahab/blob/da85dc6d89f5d0c49d3a26a25ea3710c7881b150/examples/nathook.py#L124-L139
hotdoc/hotdoc
hotdoc/utils/signals.py
Signal.connect
def connect(self, slot, *extra_args): """ @slot: The method to be called on signal emission Connects to @slot """ slot = Slot(slot, *extra_args) self._functions.add(slot)
python
def connect(self, slot, *extra_args): slot = Slot(slot, *extra_args) self._functions.add(slot)
[ "def", "connect", "(", "self", ",", "slot", ",", "*", "extra_args", ")", ":", "slot", "=", "Slot", "(", "slot", ",", "*", "extra_args", ")", "self", ".", "_functions", ".", "add", "(", "slot", ")" ]
@slot: The method to be called on signal emission Connects to @slot
[ "@slot", ":", "The", "method", "to", "be", "called", "on", "signal", "emission" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/signals.py#L85-L92
hotdoc/hotdoc
hotdoc/utils/signals.py
Signal.connect_after
def connect_after(self, slot, *extra_args): """ @slot: The method to be called at last stage of signal emission Connects to the signal after the signals has been handled by other connect callbacks. """ slot = Slot(slot, *extra_args) self._after_functions.add(slot)
python
def connect_after(self, slot, *extra_args): slot = Slot(slot, *extra_args) self._after_functions.add(slot)
[ "def", "connect_after", "(", "self", ",", "slot", ",", "*", "extra_args", ")", ":", "slot", "=", "Slot", "(", "slot", ",", "*", "extra_args", ")", "self", ".", "_after_functions", ".", "add", "(", "slot", ")" ]
@slot: The method to be called at last stage of signal emission Connects to the signal after the signals has been handled by other connect callbacks.
[ "@slot", ":", "The", "method", "to", "be", "called", "at", "last", "stage", "of", "signal", "emission" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/signals.py#L94-L102
hotdoc/hotdoc
hotdoc/utils/signals.py
Signal.disconnect
def disconnect(self, slot, *extra_args): """ Disconnect @slot from the signal """ slot = Slot(slot, *extra_args) if slot in self._functions: self._functions.remove(slot) elif slot in self._after_functions: self._after_functions.remove(slot)
python
def disconnect(self, slot, *extra_args): slot = Slot(slot, *extra_args) if slot in self._functions: self._functions.remove(slot) elif slot in self._after_functions: self._after_functions.remove(slot)
[ "def", "disconnect", "(", "self", ",", "slot", ",", "*", "extra_args", ")", ":", "slot", "=", "Slot", "(", "slot", ",", "*", "extra_args", ")", "if", "slot", "in", "self", ".", "_functions", ":", "self", ".", "_functions", ".", "remove", "(", "slot", ")", "elif", "slot", "in", "self", ".", "_after_functions", ":", "self", ".", "_after_functions", ".", "remove", "(", "slot", ")" ]
Disconnect @slot from the signal
[ "Disconnect" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/signals.py#L104-L112
hotdoc/hotdoc
hotdoc/core/formatter.py
_download_progress_cb
def _download_progress_cb(blocknum, blocksize, totalsize): """Banana Banana""" readsofar = blocknum * blocksize if totalsize > 0: percent = readsofar * 1e2 / totalsize msg = "\r%5.1f%% %*d / %d" % ( percent, len(str(totalsize)), readsofar, totalsize) print(msg) if readsofar >= totalsize: # near the end print("\n") else: # total size is unknown print("read %d\n" % (readsofar,))
python
def _download_progress_cb(blocknum, blocksize, totalsize): readsofar = blocknum * blocksize if totalsize > 0: percent = readsofar * 1e2 / totalsize msg = "\r%5.1f%% %*d / %d" % ( percent, len(str(totalsize)), readsofar, totalsize) print(msg) if readsofar >= totalsize: print("\n") else: print("read %d\n" % (readsofar,))
[ "def", "_download_progress_cb", "(", "blocknum", ",", "blocksize", ",", "totalsize", ")", ":", "readsofar", "=", "blocknum", "*", "blocksize", "if", "totalsize", ">", "0", ":", "percent", "=", "readsofar", "*", "1e2", "/", "totalsize", "msg", "=", "\"\\r%5.1f%% %*d / %d\"", "%", "(", "percent", ",", "len", "(", "str", "(", "totalsize", ")", ")", ",", "readsofar", ",", "totalsize", ")", "print", "(", "msg", ")", "if", "readsofar", ">=", "totalsize", ":", "# near the end", "print", "(", "\"\\n\"", ")", "else", ":", "# total size is unknown", "print", "(", "\"read %d\\n\"", "%", "(", "readsofar", ",", ")", ")" ]
Banana Banana
[ "Banana", "Banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L99-L110
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.format_symbol
def format_symbol(self, symbol, link_resolver): """ Format a symbols.Symbol """ if not symbol: return '' if isinstance(symbol, FieldSymbol): return '' # pylint: disable=unused-variable out = self._format_symbol(symbol) template = self.get_template('symbol_wrapper.html') return template.render( {'symbol': symbol, 'formatted_doc': out})
python
def format_symbol(self, symbol, link_resolver): if not symbol: return '' if isinstance(symbol, FieldSymbol): return '' out = self._format_symbol(symbol) template = self.get_template('symbol_wrapper.html') return template.render( {'symbol': symbol, 'formatted_doc': out})
[ "def", "format_symbol", "(", "self", ",", "symbol", ",", "link_resolver", ")", ":", "if", "not", "symbol", ":", "return", "''", "if", "isinstance", "(", "symbol", ",", "FieldSymbol", ")", ":", "return", "''", "# pylint: disable=unused-variable", "out", "=", "self", ".", "_format_symbol", "(", "symbol", ")", "template", "=", "self", ".", "get_template", "(", "'symbol_wrapper.html'", ")", "return", "template", ".", "render", "(", "{", "'symbol'", ":", "symbol", ",", "'formatted_doc'", ":", "out", "}", ")" ]
Format a symbols.Symbol
[ "Format", "a", "symbols", ".", "Symbol" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L219-L235
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.copy_assets
def copy_assets(self, assets_path): """Banana banana """ if not os.path.exists(assets_path): os.mkdir(assets_path) extra_files = self._get_extra_files() for ex_files in Formatter.get_extra_files_signal(self): extra_files.extend(ex_files) for src, dest in extra_files: dest = os.path.join(assets_path, dest) destdir = os.path.dirname(dest) if not os.path.exists(destdir): os.makedirs(destdir) if os.path.isfile(src): shutil.copy(src, dest) elif os.path.isdir(src): recursive_overwrite(src, dest)
python
def copy_assets(self, assets_path): if not os.path.exists(assets_path): os.mkdir(assets_path) extra_files = self._get_extra_files() for ex_files in Formatter.get_extra_files_signal(self): extra_files.extend(ex_files) for src, dest in extra_files: dest = os.path.join(assets_path, dest) destdir = os.path.dirname(dest) if not os.path.exists(destdir): os.makedirs(destdir) if os.path.isfile(src): shutil.copy(src, dest) elif os.path.isdir(src): recursive_overwrite(src, dest)
[ "def", "copy_assets", "(", "self", ",", "assets_path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "assets_path", ")", ":", "os", ".", "mkdir", "(", "assets_path", ")", "extra_files", "=", "self", ".", "_get_extra_files", "(", ")", "for", "ex_files", "in", "Formatter", ".", "get_extra_files_signal", "(", "self", ")", ":", "extra_files", ".", "extend", "(", "ex_files", ")", "for", "src", ",", "dest", "in", "extra_files", ":", "dest", "=", "os", ".", "path", ".", "join", "(", "assets_path", ",", "dest", ")", "destdir", "=", "os", ".", "path", ".", "dirname", "(", "dest", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "destdir", ")", ":", "os", ".", "makedirs", "(", "destdir", ")", "if", "os", ".", "path", ".", "isfile", "(", "src", ")", ":", "shutil", ".", "copy", "(", "src", ",", "dest", ")", "elif", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "recursive_overwrite", "(", "src", ",", "dest", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L269-L289
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.format_page
def format_page(self, page): """ Banana banana """ self.formatting_page_signal(self, page) return self._format_page(page)
python
def format_page(self, page): self.formatting_page_signal(self, page) return self._format_page(page)
[ "def", "format_page", "(", "self", ",", "page", ")", ":", "self", ".", "formatting_page_signal", "(", "self", ",", "page", ")", "return", "self", ".", "_format_page", "(", "page", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L298-L303
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.write_out
def write_out(self, page, xml_subpages, output): """Banana banana """ # pylint: disable=missing-docstring def subpages(_): return xml_subpages namespace = etree.FunctionNamespace('uri:hotdoc') namespace['subpages'] = subpages html_output = os.path.join(output, 'html') rel_path = os.path.join(self.get_output_folder(page), page.link.ref) cached_path = os.path.join(self.__cache_dir, rel_path) full_path = os.path.join(html_output, rel_path) if not os.path.exists(os.path.dirname(full_path)): os.makedirs(os.path.dirname(full_path)) with open(cached_path, 'r', encoding='utf-8') as _: doc_root = etree.HTML(_.read()) self.__validate_html(self.extension.project, page, doc_root) self.writing_page_signal(self, page, full_path, doc_root) with open(full_path, 'w', encoding='utf-8') as _: transformed = str(self.__page_transform(doc_root)) _.write('<!DOCTYPE html>\n%s' % transformed)
python
def write_out(self, page, xml_subpages, output): def subpages(_): return xml_subpages namespace = etree.FunctionNamespace('uri:hotdoc') namespace['subpages'] = subpages html_output = os.path.join(output, 'html') rel_path = os.path.join(self.get_output_folder(page), page.link.ref) cached_path = os.path.join(self.__cache_dir, rel_path) full_path = os.path.join(html_output, rel_path) if not os.path.exists(os.path.dirname(full_path)): os.makedirs(os.path.dirname(full_path)) with open(cached_path, 'r', encoding='utf-8') as _: doc_root = etree.HTML(_.read()) self.__validate_html(self.extension.project, page, doc_root) self.writing_page_signal(self, page, full_path, doc_root) with open(full_path, 'w', encoding='utf-8') as _: transformed = str(self.__page_transform(doc_root)) _.write('<!DOCTYPE html>\n%s' % transformed)
[ "def", "write_out", "(", "self", ",", "page", ",", "xml_subpages", ",", "output", ")", ":", "# pylint: disable=missing-docstring", "def", "subpages", "(", "_", ")", ":", "return", "xml_subpages", "namespace", "=", "etree", ".", "FunctionNamespace", "(", "'uri:hotdoc'", ")", "namespace", "[", "'subpages'", "]", "=", "subpages", "html_output", "=", "os", ".", "path", ".", "join", "(", "output", ",", "'html'", ")", "rel_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "get_output_folder", "(", "page", ")", ",", "page", ".", "link", ".", "ref", ")", "cached_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__cache_dir", ",", "rel_path", ")", "full_path", "=", "os", ".", "path", ".", "join", "(", "html_output", ",", "rel_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "full_path", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "full_path", ")", ")", "with", "open", "(", "cached_path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "_", ":", "doc_root", "=", "etree", ".", "HTML", "(", "_", ".", "read", "(", ")", ")", "self", ".", "__validate_html", "(", "self", ".", "extension", ".", "project", ",", "page", ",", "doc_root", ")", "self", ".", "writing_page_signal", "(", "self", ",", "page", ",", "full_path", ",", "doc_root", ")", "with", "open", "(", "full_path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "_", ":", "transformed", "=", "str", "(", "self", ".", "__page_transform", "(", "doc_root", ")", ")", "_", ".", "write", "(", "'<!DOCTYPE html>\\n%s'", "%", "transformed", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L462-L487
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.cache_page
def cache_page(self, page): """ Banana banana """ full_path = os.path.join(self.__cache_dir, self.get_output_folder(page), page.link.ref) os.makedirs(os.path.dirname(full_path), exist_ok=True) with open(full_path, 'w', encoding='utf-8') as _: _.write(page.detailed_description) page.cached_paths.add(full_path)
python
def cache_page(self, page): full_path = os.path.join(self.__cache_dir, self.get_output_folder(page), page.link.ref) os.makedirs(os.path.dirname(full_path), exist_ok=True) with open(full_path, 'w', encoding='utf-8') as _: _.write(page.detailed_description) page.cached_paths.add(full_path)
[ "def", "cache_page", "(", "self", ",", "page", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "__cache_dir", ",", "self", ".", "get_output_folder", "(", "page", ")", ",", "page", ".", "link", ".", "ref", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "full_path", ")", ",", "exist_ok", "=", "True", ")", "with", "open", "(", "full_path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "_", ":", "_", ".", "write", "(", "page", ".", "detailed_description", ")", "page", ".", "cached_paths", ".", "add", "(", "full_path", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L489-L500
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.prepare_page_attributes
def prepare_page_attributes(self, page): """ Banana banana """ self._current_page = page page.output_attrs['html']['scripts'] = OrderedSet() page.output_attrs['html']['stylesheets'] = OrderedSet() page.output_attrs['html']['extra_html'] = [] page.output_attrs['html']['edit_button'] = '' page.output_attrs['html']['extra_footer_html'] = [] if Formatter.add_anchors: page.output_attrs['html']['scripts'].add( os.path.join(HERE, 'assets', 'css.escape.js'))
python
def prepare_page_attributes(self, page): self._current_page = page page.output_attrs['html']['scripts'] = OrderedSet() page.output_attrs['html']['stylesheets'] = OrderedSet() page.output_attrs['html']['extra_html'] = [] page.output_attrs['html']['edit_button'] = '' page.output_attrs['html']['extra_footer_html'] = [] if Formatter.add_anchors: page.output_attrs['html']['scripts'].add( os.path.join(HERE, 'assets', 'css.escape.js'))
[ "def", "prepare_page_attributes", "(", "self", ",", "page", ")", ":", "self", ".", "_current_page", "=", "page", "page", ".", "output_attrs", "[", "'html'", "]", "[", "'scripts'", "]", "=", "OrderedSet", "(", ")", "page", ".", "output_attrs", "[", "'html'", "]", "[", "'stylesheets'", "]", "=", "OrderedSet", "(", ")", "page", ".", "output_attrs", "[", "'html'", "]", "[", "'extra_html'", "]", "=", "[", "]", "page", ".", "output_attrs", "[", "'html'", "]", "[", "'edit_button'", "]", "=", "''", "page", ".", "output_attrs", "[", "'html'", "]", "[", "'extra_footer_html'", "]", "=", "[", "]", "if", "Formatter", ".", "add_anchors", ":", "page", ".", "output_attrs", "[", "'html'", "]", "[", "'scripts'", "]", ".", "add", "(", "os", ".", "path", ".", "join", "(", "HERE", ",", "'assets'", ",", "'css.escape.js'", ")", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L642-L654
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.parse_toplevel_config
def parse_toplevel_config(self, config): """Parse @config to setup @self state.""" if not Formatter.initialized: html_theme = config.get('html_theme', 'default') if html_theme != 'default': uri = urllib.parse.urlparse(html_theme) if not uri.scheme: html_theme = config.get_path('html_theme') debug("Using theme located at %s" % html_theme) elif uri.scheme.startswith('http'): html_theme = self.__download_theme(uri) if html_theme == 'default': default_theme = os.path.join(HERE, os.pardir, 'hotdoc_bootstrap_theme', 'dist') html_theme = os.path.abspath(default_theme) debug("Using default theme") theme_meta_path = os.path.join(html_theme, 'theme.json') if os.path.exists(theme_meta_path): with open(theme_meta_path, 'r') as _: Formatter.theme_meta = json.loads(_.read()) searchpath = [] self.__load_theme_templates(searchpath, HERE) Formatter.theme_path = html_theme if html_theme: self.__load_theme_templates(searchpath, html_theme) Formatter.extra_theme_path = config.get_path('html_extra_theme') if Formatter.extra_theme_path: self.__load_theme_templates(searchpath, Formatter.extra_theme_path) Formatter.engine = Engine( loader=FileLoader(searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()]) Formatter.engine.global_vars.update({'e': html.escape}) Formatter.initialized = True
python
def parse_toplevel_config(self, config): if not Formatter.initialized: html_theme = config.get('html_theme', 'default') if html_theme != 'default': uri = urllib.parse.urlparse(html_theme) if not uri.scheme: html_theme = config.get_path('html_theme') debug("Using theme located at %s" % html_theme) elif uri.scheme.startswith('http'): html_theme = self.__download_theme(uri) if html_theme == 'default': default_theme = os.path.join(HERE, os.pardir, 'hotdoc_bootstrap_theme', 'dist') html_theme = os.path.abspath(default_theme) debug("Using default theme") theme_meta_path = os.path.join(html_theme, 'theme.json') if os.path.exists(theme_meta_path): with open(theme_meta_path, 'r') as _: Formatter.theme_meta = json.loads(_.read()) searchpath = [] self.__load_theme_templates(searchpath, HERE) Formatter.theme_path = html_theme if html_theme: self.__load_theme_templates(searchpath, html_theme) Formatter.extra_theme_path = config.get_path('html_extra_theme') if Formatter.extra_theme_path: self.__load_theme_templates(searchpath, Formatter.extra_theme_path) Formatter.engine = Engine( loader=FileLoader(searchpath, encoding='UTF-8'), extensions=[CoreExtension(), CodeExtension()]) Formatter.engine.global_vars.update({'e': html.escape}) Formatter.initialized = True
[ "def", "parse_toplevel_config", "(", "self", ",", "config", ")", ":", "if", "not", "Formatter", ".", "initialized", ":", "html_theme", "=", "config", ".", "get", "(", "'html_theme'", ",", "'default'", ")", "if", "html_theme", "!=", "'default'", ":", "uri", "=", "urllib", ".", "parse", ".", "urlparse", "(", "html_theme", ")", "if", "not", "uri", ".", "scheme", ":", "html_theme", "=", "config", ".", "get_path", "(", "'html_theme'", ")", "debug", "(", "\"Using theme located at %s\"", "%", "html_theme", ")", "elif", "uri", ".", "scheme", ".", "startswith", "(", "'http'", ")", ":", "html_theme", "=", "self", ".", "__download_theme", "(", "uri", ")", "if", "html_theme", "==", "'default'", ":", "default_theme", "=", "os", ".", "path", ".", "join", "(", "HERE", ",", "os", ".", "pardir", ",", "'hotdoc_bootstrap_theme'", ",", "'dist'", ")", "html_theme", "=", "os", ".", "path", ".", "abspath", "(", "default_theme", ")", "debug", "(", "\"Using default theme\"", ")", "theme_meta_path", "=", "os", ".", "path", ".", "join", "(", "html_theme", ",", "'theme.json'", ")", "if", "os", ".", "path", ".", "exists", "(", "theme_meta_path", ")", ":", "with", "open", "(", "theme_meta_path", ",", "'r'", ")", "as", "_", ":", "Formatter", ".", "theme_meta", "=", "json", ".", "loads", "(", "_", ".", "read", "(", ")", ")", "searchpath", "=", "[", "]", "self", ".", "__load_theme_templates", "(", "searchpath", ",", "HERE", ")", "Formatter", ".", "theme_path", "=", "html_theme", "if", "html_theme", ":", "self", ".", "__load_theme_templates", "(", "searchpath", ",", "html_theme", ")", "Formatter", ".", "extra_theme_path", "=", "config", ".", "get_path", "(", "'html_extra_theme'", ")", "if", "Formatter", ".", "extra_theme_path", ":", "self", ".", "__load_theme_templates", "(", "searchpath", ",", "Formatter", ".", "extra_theme_path", ")", "Formatter", ".", "engine", "=", "Engine", "(", "loader", "=", "FileLoader", "(", "searchpath", ",", "encoding", "=", "'UTF-8'", ")", ",", "extensions", "=", "[", "CoreExtension", "(", ")", ",", "CodeExtension", "(", ")", "]", ")", "Formatter", ".", "engine", ".", "global_vars", ".", "update", "(", "{", "'e'", ":", "html", ".", "escape", "}", ")", "Formatter", ".", "initialized", "=", "True" ]
Parse @config to setup @self state.
[ "Parse" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L1049-L1092
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.parse_config
def parse_config(self, config): """Banana banana """ self.add_anchors = bool(config.get("html_add_anchors")) self.number_headings = bool(config.get("html_number_headings")) self._docstring_formatter.parse_config(config)
python
def parse_config(self, config): self.add_anchors = bool(config.get("html_add_anchors")) self.number_headings = bool(config.get("html_number_headings")) self._docstring_formatter.parse_config(config)
[ "def", "parse_config", "(", "self", ",", "config", ")", ":", "self", ".", "add_anchors", "=", "bool", "(", "config", ".", "get", "(", "\"html_add_anchors\"", ")", ")", "self", ".", "number_headings", "=", "bool", "(", "config", ".", "get", "(", "\"html_number_headings\"", ")", ")", "self", ".", "_docstring_formatter", ".", "parse_config", "(", "config", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L1100-L1105
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.format_navigation
def format_navigation(self, project): """Banana banana """ try: template = self.get_template('site_navigation.html') except IOError: return None return template.render({'project': project})
python
def format_navigation(self, project): try: template = self.get_template('site_navigation.html') except IOError: return None return template.render({'project': project})
[ "def", "format_navigation", "(", "self", ",", "project", ")", ":", "try", ":", "template", "=", "self", ".", "get_template", "(", "'site_navigation.html'", ")", "except", "IOError", ":", "return", "None", "return", "template", ".", "render", "(", "{", "'project'", ":", "project", "}", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L1107-L1115
hotdoc/hotdoc
hotdoc/core/formatter.py
Formatter.format_subpages
def format_subpages(self, page, subpages): """Banana banana """ if not subpages: return None try: template = self.get_template('subpages.html') except IOError: return None ret = etree.XML(template.render({'page': page, 'subpages': subpages})) assets = ret.xpath('.//*[@src]') for asset in assets: self.__lookup_asset(asset, self.extension.project, page) return ret
python
def format_subpages(self, page, subpages): if not subpages: return None try: template = self.get_template('subpages.html') except IOError: return None ret = etree.XML(template.render({'page': page, 'subpages': subpages})) assets = ret.xpath('.//*[@src]') for asset in assets: self.__lookup_asset(asset, self.extension.project, page) return ret
[ "def", "format_subpages", "(", "self", ",", "page", ",", "subpages", ")", ":", "if", "not", "subpages", ":", "return", "None", "try", ":", "template", "=", "self", ".", "get_template", "(", "'subpages.html'", ")", "except", "IOError", ":", "return", "None", "ret", "=", "etree", ".", "XML", "(", "template", ".", "render", "(", "{", "'page'", ":", "page", ",", "'subpages'", ":", "subpages", "}", ")", ")", "assets", "=", "ret", ".", "xpath", "(", "'.//*[@src]'", ")", "for", "asset", "in", "assets", ":", "self", ".", "__lookup_asset", "(", "asset", ",", "self", ".", "extension", ".", "project", ",", "page", ")", "return", "ret" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L1117-L1134
hotdoc/hotdoc
hotdoc/run_hotdoc.py
check_path
def check_path(init_dir, name): """ Banana banana """ path = os.path.join(init_dir, name) if os.path.exists(path): error('setup-issue', '%s already exists' % path) return path
python
def check_path(init_dir, name): path = os.path.join(init_dir, name) if os.path.exists(path): error('setup-issue', '%s already exists' % path) return path
[ "def", "check_path", "(", "init_dir", ",", "name", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "error", "(", "'setup-issue'", ",", "'%s already exists'", "%", "path", ")", "return", "path" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/run_hotdoc.py#L177-L184
hotdoc/hotdoc
hotdoc/run_hotdoc.py
create_default_layout
def create_default_layout(config): """ Banana banana """ project_name = config.get('project_name') project_version = config.get('project_version') if not project_name or not project_version: error('setup-issue', '--project-name and --project-version must be specified') init_dir = config.get_path('init_dir') if not init_dir: init_dir = config.get_invoke_dir() else: if os.path.exists(init_dir) and not os.path.isdir(init_dir): error('setup-issue', 'Init directory exists but is not a directory: %s' % init_dir) sitemap_path = check_path(init_dir, 'sitemap.txt') conf_path = check_path(init_dir, 'hotdoc.json') md_folder_path = check_path(init_dir, 'markdown_files') assets_folder_path = check_path(init_dir, 'assets') check_path(init_dir, 'built_doc') cat_path = os.path.join(assets_folder_path, 'cat.gif') os.makedirs(init_dir) os.makedirs(assets_folder_path) os.makedirs(md_folder_path) with open(sitemap_path, 'w') as _: _.write('index.md\n') with open(conf_path, 'w') as _: _.write(json.dumps({'project_name': project_name, 'project_version': project_version, 'sitemap': 'sitemap.txt', 'index': os.path.join('markdown_files', 'index.md'), 'output': 'built_doc', 'extra_assets': ['assets']}, indent=4)) with open(os.path.join(md_folder_path, 'index.md'), 'w') as _: _.write('# %s\n' % project_name.capitalize()) try: get_cat(cat_path) _.write("\nIt's dangerous to go alone, take this\n") _.write('\n![](assets/cat.gif)') except: # pylint: disable=bare-except pass
python
def create_default_layout(config): project_name = config.get('project_name') project_version = config.get('project_version') if not project_name or not project_version: error('setup-issue', '--project-name and --project-version must be specified') init_dir = config.get_path('init_dir') if not init_dir: init_dir = config.get_invoke_dir() else: if os.path.exists(init_dir) and not os.path.isdir(init_dir): error('setup-issue', 'Init directory exists but is not a directory: %s' % init_dir) sitemap_path = check_path(init_dir, 'sitemap.txt') conf_path = check_path(init_dir, 'hotdoc.json') md_folder_path = check_path(init_dir, 'markdown_files') assets_folder_path = check_path(init_dir, 'assets') check_path(init_dir, 'built_doc') cat_path = os.path.join(assets_folder_path, 'cat.gif') os.makedirs(init_dir) os.makedirs(assets_folder_path) os.makedirs(md_folder_path) with open(sitemap_path, 'w') as _: _.write('index.md\n') with open(conf_path, 'w') as _: _.write(json.dumps({'project_name': project_name, 'project_version': project_version, 'sitemap': 'sitemap.txt', 'index': os.path.join('markdown_files', 'index.md'), 'output': 'built_doc', 'extra_assets': ['assets']}, indent=4)) with open(os.path.join(md_folder_path, 'index.md'), 'w') as _: _.write(' try: get_cat(cat_path) _.write("\nIt's dangerous to go alone, take this\n") _.write('\n![](assets/cat.gif)') except: pass
[ "def", "create_default_layout", "(", "config", ")", ":", "project_name", "=", "config", ".", "get", "(", "'project_name'", ")", "project_version", "=", "config", ".", "get", "(", "'project_version'", ")", "if", "not", "project_name", "or", "not", "project_version", ":", "error", "(", "'setup-issue'", ",", "'--project-name and --project-version must be specified'", ")", "init_dir", "=", "config", ".", "get_path", "(", "'init_dir'", ")", "if", "not", "init_dir", ":", "init_dir", "=", "config", ".", "get_invoke_dir", "(", ")", "else", ":", "if", "os", ".", "path", ".", "exists", "(", "init_dir", ")", "and", "not", "os", ".", "path", ".", "isdir", "(", "init_dir", ")", ":", "error", "(", "'setup-issue'", ",", "'Init directory exists but is not a directory: %s'", "%", "init_dir", ")", "sitemap_path", "=", "check_path", "(", "init_dir", ",", "'sitemap.txt'", ")", "conf_path", "=", "check_path", "(", "init_dir", ",", "'hotdoc.json'", ")", "md_folder_path", "=", "check_path", "(", "init_dir", ",", "'markdown_files'", ")", "assets_folder_path", "=", "check_path", "(", "init_dir", ",", "'assets'", ")", "check_path", "(", "init_dir", ",", "'built_doc'", ")", "cat_path", "=", "os", ".", "path", ".", "join", "(", "assets_folder_path", ",", "'cat.gif'", ")", "os", ".", "makedirs", "(", "init_dir", ")", "os", ".", "makedirs", "(", "assets_folder_path", ")", "os", ".", "makedirs", "(", "md_folder_path", ")", "with", "open", "(", "sitemap_path", ",", "'w'", ")", "as", "_", ":", "_", ".", "write", "(", "'index.md\\n'", ")", "with", "open", "(", "conf_path", ",", "'w'", ")", "as", "_", ":", "_", ".", "write", "(", "json", ".", "dumps", "(", "{", "'project_name'", ":", "project_name", ",", "'project_version'", ":", "project_version", ",", "'sitemap'", ":", "'sitemap.txt'", ",", "'index'", ":", "os", ".", "path", ".", "join", "(", "'markdown_files'", ",", "'index.md'", ")", ",", "'output'", ":", "'built_doc'", ",", "'extra_assets'", ":", "[", "'assets'", "]", "}", ",", "indent", "=", "4", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "md_folder_path", ",", "'index.md'", ")", ",", "'w'", ")", "as", "_", ":", "_", ".", "write", "(", "'# %s\\n'", "%", "project_name", ".", "capitalize", "(", ")", ")", "try", ":", "get_cat", "(", "cat_path", ")", "_", ".", "write", "(", "\"\\nIt's dangerous to go alone, take this\\n\"", ")", "_", ".", "write", "(", "'\\n![](assets/cat.gif)'", ")", "except", ":", "# pylint: disable=bare-except", "pass" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/run_hotdoc.py#L187-L237
hotdoc/hotdoc
hotdoc/run_hotdoc.py
execute_command
def execute_command(parser, config, ext_classes): """ Banana banana """ res = 0 cmd = config.get('command') get_private_folder = config.get('get_private_folder', False) if cmd == 'help': parser.print_help() elif cmd == 'run' or get_private_folder: # git.mk backward compat app = Application(ext_classes) try: app.parse_config(config) if get_private_folder: print(app.private_folder) return res res = app.run() except HotdocException: res = len(Logger.get_issues()) except Exception: # pylint: disable=broad-except print("An unknown error happened while building the documentation" " and hotdoc cannot recover from it. Please report " "a bug with this error message and the steps to " "reproduce it") traceback.print_exc() res = 1 finally: app.finalize() elif cmd == 'init': try: create_default_layout(config) except HotdocException: res = 1 elif cmd == 'conf': config.dump(conf_file=config.get('output_conf_file', None)) elif cmd is None: if config.get('version'): print(VERSION) elif config.get('makefile_path'): here = os.path.dirname(__file__) path = os.path.join(here, 'utils', 'hotdoc.mk') print(os.path.abspath(path)) elif config.get('get_conf_path'): key = config.get('get_conf_path') path = config.get_path(key, rel_to_cwd=True) if path is not None: print(path) elif config.get('get_conf_key'): key = config.get('get_conf_key') value = config.get(key, None) if value is not None: print(value) else: parser.print_usage() else: parser.print_usage() return res
python
def execute_command(parser, config, ext_classes): res = 0 cmd = config.get('command') get_private_folder = config.get('get_private_folder', False) if cmd == 'help': parser.print_help() elif cmd == 'run' or get_private_folder: app = Application(ext_classes) try: app.parse_config(config) if get_private_folder: print(app.private_folder) return res res = app.run() except HotdocException: res = len(Logger.get_issues()) except Exception: print("An unknown error happened while building the documentation" " and hotdoc cannot recover from it. Please report " "a bug with this error message and the steps to " "reproduce it") traceback.print_exc() res = 1 finally: app.finalize() elif cmd == 'init': try: create_default_layout(config) except HotdocException: res = 1 elif cmd == 'conf': config.dump(conf_file=config.get('output_conf_file', None)) elif cmd is None: if config.get('version'): print(VERSION) elif config.get('makefile_path'): here = os.path.dirname(__file__) path = os.path.join(here, 'utils', 'hotdoc.mk') print(os.path.abspath(path)) elif config.get('get_conf_path'): key = config.get('get_conf_path') path = config.get_path(key, rel_to_cwd=True) if path is not None: print(path) elif config.get('get_conf_key'): key = config.get('get_conf_key') value = config.get(key, None) if value is not None: print(value) else: parser.print_usage() else: parser.print_usage() return res
[ "def", "execute_command", "(", "parser", ",", "config", ",", "ext_classes", ")", ":", "res", "=", "0", "cmd", "=", "config", ".", "get", "(", "'command'", ")", "get_private_folder", "=", "config", ".", "get", "(", "'get_private_folder'", ",", "False", ")", "if", "cmd", "==", "'help'", ":", "parser", ".", "print_help", "(", ")", "elif", "cmd", "==", "'run'", "or", "get_private_folder", ":", "# git.mk backward compat", "app", "=", "Application", "(", "ext_classes", ")", "try", ":", "app", ".", "parse_config", "(", "config", ")", "if", "get_private_folder", ":", "print", "(", "app", ".", "private_folder", ")", "return", "res", "res", "=", "app", ".", "run", "(", ")", "except", "HotdocException", ":", "res", "=", "len", "(", "Logger", ".", "get_issues", "(", ")", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "print", "(", "\"An unknown error happened while building the documentation\"", "\" and hotdoc cannot recover from it. Please report \"", "\"a bug with this error message and the steps to \"", "\"reproduce it\"", ")", "traceback", ".", "print_exc", "(", ")", "res", "=", "1", "finally", ":", "app", ".", "finalize", "(", ")", "elif", "cmd", "==", "'init'", ":", "try", ":", "create_default_layout", "(", "config", ")", "except", "HotdocException", ":", "res", "=", "1", "elif", "cmd", "==", "'conf'", ":", "config", ".", "dump", "(", "conf_file", "=", "config", ".", "get", "(", "'output_conf_file'", ",", "None", ")", ")", "elif", "cmd", "is", "None", ":", "if", "config", ".", "get", "(", "'version'", ")", ":", "print", "(", "VERSION", ")", "elif", "config", ".", "get", "(", "'makefile_path'", ")", ":", "here", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "path", "=", "os", ".", "path", ".", "join", "(", "here", ",", "'utils'", ",", "'hotdoc.mk'", ")", "print", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "elif", "config", ".", "get", "(", "'get_conf_path'", ")", ":", "key", "=", "config", ".", "get", "(", "'get_conf_path'", ")", "path", "=", "config", ".", "get_path", "(", "key", ",", "rel_to_cwd", "=", "True", ")", "if", "path", "is", "not", "None", ":", "print", "(", "path", ")", "elif", "config", ".", "get", "(", "'get_conf_key'", ")", ":", "key", "=", "config", ".", "get", "(", "'get_conf_key'", ")", "value", "=", "config", ".", "get", "(", "key", ",", "None", ")", "if", "value", "is", "not", "None", ":", "print", "(", "value", ")", "else", ":", "parser", ".", "print_usage", "(", ")", "else", ":", "parser", ".", "print_usage", "(", ")", "return", "res" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/run_hotdoc.py#L242-L301
hotdoc/hotdoc
hotdoc/run_hotdoc.py
run
def run(args): """ Banana banana """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False) parser.add_argument("--extra-extension-path", action="append", default=[], dest="extra_extension_path", help="An extra extension path to use") parser.add_argument('--conf-file', help='Path to the config file', dest='conf_file') tmpargs, _args = parser.parse_known_args(args) json_conf = None if tmpargs.conf_file: json_conf = load_config_json(tmpargs.conf_file) tmpargs.extra_extension_path += json_conf.get('extra_extension_path', []) # We only get these once, doing this now means all # installed extensions will show up as Configurable subclasses. try: ext_classes = get_extension_classes( sort=True, extra_extension_paths=tmpargs.extra_extension_path) except HotdocException: return 1 parser.add_argument('command', action="store", choices=('run', 'conf', 'init', 'help'), nargs="?") parser.add_argument('--output-conf-file', help='Path where to save the updated conf' ' file', dest='output_conf_file') parser.add_argument('--init-dir', help='Directory to initialize', dest='init_dir') parser.add_argument('--version', help="Print version and exit", action="store_true") parser.add_argument('--makefile-path', help="Print path to includable " "Makefile and exit", action="store_true") parser.add_argument("--get-conf-key", action="store", help="print the value for a configuration " "key") parser.add_argument("--get-conf-path", action="store", help="print the value for a configuration " "path") parser.add_argument("--get-private-folder", action="store_true", help="get the path to hotdoc's private " "folder") parser.add_argument("--has-extension", action="append", dest="has_extensions", default=[], help="Check if a given extension is available") parser.add_argument("--list-extensions", action="store_true", dest="list_extensions", help="Print " "available extensions") parser.add_argument("-", action="store_true", help="Separator to allow finishing a list" " of arguments before a command", dest="whatever") add_args_methods = set() for klass in all_subclasses(Configurable): if klass.add_arguments not in add_args_methods: klass.add_arguments(parser) add_args_methods.add(klass.add_arguments) known_args, _ = parser.parse_known_args(args) defaults = {} actual_args = {} for key, value in list(dict(vars(known_args)).items()): if value != parser.get_default(key): actual_args[key] = value if parser.get_default(key) is not None: defaults[key] = value if known_args.has_extensions: res = 0 for extension_name in known_args.has_extensions: found = False for klass in ext_classes: if klass.extension_name == extension_name: found = True print("Extension '%s'... FOUND." % extension_name) if not found: print("Extension '%s'... NOT FOUND." % extension_name) res = 1 return res if known_args.list_extensions: print("Extensions:") extensions = [e.extension_name for e in ext_classes] for extension in sorted(extensions): print(" - %s " % extension) return 0 if known_args.command != 'init': conf_file = actual_args.get('conf_file') if conf_file is None and os.path.exists('hotdoc.json'): conf_file = 'hotdoc.json' else: conf_file = '' config = Config(command_line_args=actual_args, conf_file=conf_file, defaults=defaults, json_conf=json_conf) Logger.parse_config(config) return execute_command(parser, config, ext_classes)
python
def run(args): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False) parser.add_argument("--extra-extension-path", action="append", default=[], dest="extra_extension_path", help="An extra extension path to use") parser.add_argument('--conf-file', help='Path to the config file', dest='conf_file') tmpargs, _args = parser.parse_known_args(args) json_conf = None if tmpargs.conf_file: json_conf = load_config_json(tmpargs.conf_file) tmpargs.extra_extension_path += json_conf.get('extra_extension_path', []) try: ext_classes = get_extension_classes( sort=True, extra_extension_paths=tmpargs.extra_extension_path) except HotdocException: return 1 parser.add_argument('command', action="store", choices=('run', 'conf', 'init', 'help'), nargs="?") parser.add_argument('--output-conf-file', help='Path where to save the updated conf' ' file', dest='output_conf_file') parser.add_argument('--init-dir', help='Directory to initialize', dest='init_dir') parser.add_argument('--version', help="Print version and exit", action="store_true") parser.add_argument('--makefile-path', help="Print path to includable " "Makefile and exit", action="store_true") parser.add_argument("--get-conf-key", action="store", help="print the value for a configuration " "key") parser.add_argument("--get-conf-path", action="store", help="print the value for a configuration " "path") parser.add_argument("--get-private-folder", action="store_true", help="get the path to hotdoc's private " "folder") parser.add_argument("--has-extension", action="append", dest="has_extensions", default=[], help="Check if a given extension is available") parser.add_argument("--list-extensions", action="store_true", dest="list_extensions", help="Print " "available extensions") parser.add_argument("-", action="store_true", help="Separator to allow finishing a list" " of arguments before a command", dest="whatever") add_args_methods = set() for klass in all_subclasses(Configurable): if klass.add_arguments not in add_args_methods: klass.add_arguments(parser) add_args_methods.add(klass.add_arguments) known_args, _ = parser.parse_known_args(args) defaults = {} actual_args = {} for key, value in list(dict(vars(known_args)).items()): if value != parser.get_default(key): actual_args[key] = value if parser.get_default(key) is not None: defaults[key] = value if known_args.has_extensions: res = 0 for extension_name in known_args.has_extensions: found = False for klass in ext_classes: if klass.extension_name == extension_name: found = True print("Extension '%s'... FOUND." % extension_name) if not found: print("Extension '%s'... NOT FOUND." % extension_name) res = 1 return res if known_args.list_extensions: print("Extensions:") extensions = [e.extension_name for e in ext_classes] for extension in sorted(extensions): print(" - %s " % extension) return 0 if known_args.command != 'init': conf_file = actual_args.get('conf_file') if conf_file is None and os.path.exists('hotdoc.json'): conf_file = 'hotdoc.json' else: conf_file = '' config = Config(command_line_args=actual_args, conf_file=conf_file, defaults=defaults, json_conf=json_conf) Logger.parse_config(config) return execute_command(parser, config, ext_classes)
[ "def", "run", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "\"--extra-extension-path\"", ",", "action", "=", "\"append\"", ",", "default", "=", "[", "]", ",", "dest", "=", "\"extra_extension_path\"", ",", "help", "=", "\"An extra extension path to use\"", ")", "parser", ".", "add_argument", "(", "'--conf-file'", ",", "help", "=", "'Path to the config file'", ",", "dest", "=", "'conf_file'", ")", "tmpargs", ",", "_args", "=", "parser", ".", "parse_known_args", "(", "args", ")", "json_conf", "=", "None", "if", "tmpargs", ".", "conf_file", ":", "json_conf", "=", "load_config_json", "(", "tmpargs", ".", "conf_file", ")", "tmpargs", ".", "extra_extension_path", "+=", "json_conf", ".", "get", "(", "'extra_extension_path'", ",", "[", "]", ")", "# We only get these once, doing this now means all", "# installed extensions will show up as Configurable subclasses.", "try", ":", "ext_classes", "=", "get_extension_classes", "(", "sort", "=", "True", ",", "extra_extension_paths", "=", "tmpargs", ".", "extra_extension_path", ")", "except", "HotdocException", ":", "return", "1", "parser", ".", "add_argument", "(", "'command'", ",", "action", "=", "\"store\"", ",", "choices", "=", "(", "'run'", ",", "'conf'", ",", "'init'", ",", "'help'", ")", ",", "nargs", "=", "\"?\"", ")", "parser", ".", "add_argument", "(", "'--output-conf-file'", ",", "help", "=", "'Path where to save the updated conf'", "' file'", ",", "dest", "=", "'output_conf_file'", ")", "parser", ".", "add_argument", "(", "'--init-dir'", ",", "help", "=", "'Directory to initialize'", ",", "dest", "=", "'init_dir'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "help", "=", "\"Print version and exit\"", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_argument", "(", "'--makefile-path'", ",", "help", "=", "\"Print path to includable \"", "\"Makefile and exit\"", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_argument", "(", "\"--get-conf-key\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"print the value for a configuration \"", "\"key\"", ")", "parser", ".", "add_argument", "(", "\"--get-conf-path\"", ",", "action", "=", "\"store\"", ",", "help", "=", "\"print the value for a configuration \"", "\"path\"", ")", "parser", ".", "add_argument", "(", "\"--get-private-folder\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"get the path to hotdoc's private \"", "\"folder\"", ")", "parser", ".", "add_argument", "(", "\"--has-extension\"", ",", "action", "=", "\"append\"", ",", "dest", "=", "\"has_extensions\"", ",", "default", "=", "[", "]", ",", "help", "=", "\"Check if a given extension is available\"", ")", "parser", ".", "add_argument", "(", "\"--list-extensions\"", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"list_extensions\"", ",", "help", "=", "\"Print \"", "\"available extensions\"", ")", "parser", ".", "add_argument", "(", "\"-\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Separator to allow finishing a list\"", "\" of arguments before a command\"", ",", "dest", "=", "\"whatever\"", ")", "add_args_methods", "=", "set", "(", ")", "for", "klass", "in", "all_subclasses", "(", "Configurable", ")", ":", "if", "klass", ".", "add_arguments", "not", "in", "add_args_methods", ":", "klass", ".", "add_arguments", "(", "parser", ")", "add_args_methods", ".", "add", "(", "klass", ".", "add_arguments", ")", "known_args", ",", "_", "=", "parser", ".", "parse_known_args", "(", "args", ")", "defaults", "=", "{", "}", "actual_args", "=", "{", "}", "for", "key", ",", "value", "in", "list", "(", "dict", "(", "vars", "(", "known_args", ")", ")", ".", "items", "(", ")", ")", ":", "if", "value", "!=", "parser", ".", "get_default", "(", "key", ")", ":", "actual_args", "[", "key", "]", "=", "value", "if", "parser", ".", "get_default", "(", "key", ")", "is", "not", "None", ":", "defaults", "[", "key", "]", "=", "value", "if", "known_args", ".", "has_extensions", ":", "res", "=", "0", "for", "extension_name", "in", "known_args", ".", "has_extensions", ":", "found", "=", "False", "for", "klass", "in", "ext_classes", ":", "if", "klass", ".", "extension_name", "==", "extension_name", ":", "found", "=", "True", "print", "(", "\"Extension '%s'... FOUND.\"", "%", "extension_name", ")", "if", "not", "found", ":", "print", "(", "\"Extension '%s'... NOT FOUND.\"", "%", "extension_name", ")", "res", "=", "1", "return", "res", "if", "known_args", ".", "list_extensions", ":", "print", "(", "\"Extensions:\"", ")", "extensions", "=", "[", "e", ".", "extension_name", "for", "e", "in", "ext_classes", "]", "for", "extension", "in", "sorted", "(", "extensions", ")", ":", "print", "(", "\" - %s \"", "%", "extension", ")", "return", "0", "if", "known_args", ".", "command", "!=", "'init'", ":", "conf_file", "=", "actual_args", ".", "get", "(", "'conf_file'", ")", "if", "conf_file", "is", "None", "and", "os", ".", "path", ".", "exists", "(", "'hotdoc.json'", ")", ":", "conf_file", "=", "'hotdoc.json'", "else", ":", "conf_file", "=", "''", "config", "=", "Config", "(", "command_line_args", "=", "actual_args", ",", "conf_file", "=", "conf_file", ",", "defaults", "=", "defaults", ",", "json_conf", "=", "json_conf", ")", "Logger", ".", "parse_config", "(", "config", ")", "return", "execute_command", "(", "parser", ",", "config", ",", "ext_classes", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/run_hotdoc.py#L307-L424
hotdoc/hotdoc
hotdoc/run_hotdoc.py
Application.run
def run(self): """ Banana banana """ res = 0 self.project.setup() self.__retrieve_all_projects(self.project) self.link_resolver.get_link_signal.connect_after(self.__get_link_cb) self.project.format(self.link_resolver, self.output) self.project.write_out(self.output) # Generating an XML sitemap makes no sense without a hostname if self.hostname: self.project.write_seo_sitemap(self.hostname, self.output) self.link_resolver.get_link_signal.disconnect(self.__get_link_cb) self.formatted_signal(self) self.__persist() return res
python
def run(self): res = 0 self.project.setup() self.__retrieve_all_projects(self.project) self.link_resolver.get_link_signal.connect_after(self.__get_link_cb) self.project.format(self.link_resolver, self.output) self.project.write_out(self.output) if self.hostname: self.project.write_seo_sitemap(self.hostname, self.output) self.link_resolver.get_link_signal.disconnect(self.__get_link_cb) self.formatted_signal(self) self.__persist() return res
[ "def", "run", "(", "self", ")", ":", "res", "=", "0", "self", ".", "project", ".", "setup", "(", ")", "self", ".", "__retrieve_all_projects", "(", "self", ".", "project", ")", "self", ".", "link_resolver", ".", "get_link_signal", ".", "connect_after", "(", "self", ".", "__get_link_cb", ")", "self", ".", "project", ".", "format", "(", "self", ".", "link_resolver", ",", "self", ".", "output", ")", "self", ".", "project", ".", "write_out", "(", "self", ".", "output", ")", "# Generating an XML sitemap makes no sense without a hostname", "if", "self", ".", "hostname", ":", "self", ".", "project", ".", "write_seo_sitemap", "(", "self", ".", "hostname", ",", "self", ".", "output", ")", "self", ".", "link_resolver", ".", "get_link_signal", ".", "disconnect", "(", "self", ".", "__get_link_cb", ")", "self", ".", "formatted_signal", "(", "self", ")", "self", ".", "__persist", "(", ")", "return", "res" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/run_hotdoc.py#L103-L125
hotdoc/hotdoc
hotdoc/core/database.py
Database.add_comment
def add_comment(self, comment): """ Add a comment to the database. Args: comment (hotdoc.core.Comment): comment to add """ if not comment: return self.__comments[comment.name] = comment self.comment_added_signal(self, comment)
python
def add_comment(self, comment): if not comment: return self.__comments[comment.name] = comment self.comment_added_signal(self, comment)
[ "def", "add_comment", "(", "self", ",", "comment", ")", ":", "if", "not", "comment", ":", "return", "self", ".", "__comments", "[", "comment", ".", "name", "]", "=", "comment", "self", ".", "comment_added_signal", "(", "self", ",", "comment", ")" ]
Add a comment to the database. Args: comment (hotdoc.core.Comment): comment to add
[ "Add", "a", "comment", "to", "the", "database", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/database.py#L77-L88
hotdoc/hotdoc
hotdoc/core/database.py
Database.get_comment
def get_comment(self, name): """ Banana banana """ comment = self.__comments.get(name) if comment: return comment aliases = self.__get_aliases(name) for alias in aliases: comment = self.__comments.get(alias) if comment: return comment return None
python
def get_comment(self, name): comment = self.__comments.get(name) if comment: return comment aliases = self.__get_aliases(name) for alias in aliases: comment = self.__comments.get(alias) if comment: return comment return None
[ "def", "get_comment", "(", "self", ",", "name", ")", ":", "comment", "=", "self", ".", "__comments", ".", "get", "(", "name", ")", "if", "comment", ":", "return", "comment", "aliases", "=", "self", ".", "__get_aliases", "(", "name", ")", "for", "alias", "in", "aliases", ":", "comment", "=", "self", ".", "__comments", ".", "get", "(", "alias", ")", "if", "comment", ":", "return", "comment", "return", "None" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/database.py#L90-L105
hotdoc/hotdoc
hotdoc/core/database.py
Database.create_symbol
def create_symbol(self, type_, **kwargs): """ Banana banana """ unique_name = kwargs.get('unique_name') if not unique_name: unique_name = kwargs.get('display_name') kwargs['unique_name'] = unique_name filename = kwargs.get('filename') if filename: filename = os.path.abspath(filename) kwargs['filename'] = os.path.abspath(filename) if unique_name in self.__symbols: warn('symbol-redefined', "%s(unique_name=%s, filename=%s, project=%s)" " has already been defined: %s" % (type_.__name__, unique_name, filename, kwargs.get('project_name'), self.get_symbol(unique_name))) return None aliases = kwargs.pop('aliases', []) for alias in aliases: self.create_symbol(ProxySymbol, unique_name=alias, target=unique_name) symbol = type_() debug('Created symbol with unique name %s' % unique_name, 'symbols') for key, value in list(kwargs.items()): setattr(symbol, key, value) self.__symbols[unique_name] = symbol for alias in aliases: self.__symbols[alias] = symbol self.__aliases[unique_name] = aliases return symbol
python
def create_symbol(self, type_, **kwargs): unique_name = kwargs.get('unique_name') if not unique_name: unique_name = kwargs.get('display_name') kwargs['unique_name'] = unique_name filename = kwargs.get('filename') if filename: filename = os.path.abspath(filename) kwargs['filename'] = os.path.abspath(filename) if unique_name in self.__symbols: warn('symbol-redefined', "%s(unique_name=%s, filename=%s, project=%s)" " has already been defined: %s" % (type_.__name__, unique_name, filename, kwargs.get('project_name'), self.get_symbol(unique_name))) return None aliases = kwargs.pop('aliases', []) for alias in aliases: self.create_symbol(ProxySymbol, unique_name=alias, target=unique_name) symbol = type_() debug('Created symbol with unique name %s' % unique_name, 'symbols') for key, value in list(kwargs.items()): setattr(symbol, key, value) self.__symbols[unique_name] = symbol for alias in aliases: self.__symbols[alias] = symbol self.__aliases[unique_name] = aliases return symbol
[ "def", "create_symbol", "(", "self", ",", "type_", ",", "*", "*", "kwargs", ")", ":", "unique_name", "=", "kwargs", ".", "get", "(", "'unique_name'", ")", "if", "not", "unique_name", ":", "unique_name", "=", "kwargs", ".", "get", "(", "'display_name'", ")", "kwargs", "[", "'unique_name'", "]", "=", "unique_name", "filename", "=", "kwargs", ".", "get", "(", "'filename'", ")", "if", "filename", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "kwargs", "[", "'filename'", "]", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "unique_name", "in", "self", ".", "__symbols", ":", "warn", "(", "'symbol-redefined'", ",", "\"%s(unique_name=%s, filename=%s, project=%s)\"", "\" has already been defined: %s\"", "%", "(", "type_", ".", "__name__", ",", "unique_name", ",", "filename", ",", "kwargs", ".", "get", "(", "'project_name'", ")", ",", "self", ".", "get_symbol", "(", "unique_name", ")", ")", ")", "return", "None", "aliases", "=", "kwargs", ".", "pop", "(", "'aliases'", ",", "[", "]", ")", "for", "alias", "in", "aliases", ":", "self", ".", "create_symbol", "(", "ProxySymbol", ",", "unique_name", "=", "alias", ",", "target", "=", "unique_name", ")", "symbol", "=", "type_", "(", ")", "debug", "(", "'Created symbol with unique name %s'", "%", "unique_name", ",", "'symbols'", ")", "for", "key", ",", "value", "in", "list", "(", "kwargs", ".", "items", "(", ")", ")", ":", "setattr", "(", "symbol", ",", "key", ",", "value", ")", "self", ".", "__symbols", "[", "unique_name", "]", "=", "symbol", "for", "alias", "in", "aliases", ":", "self", ".", "__symbols", "[", "alias", "]", "=", "symbol", "self", ".", "__aliases", "[", "unique_name", "]", "=", "aliases", "return", "symbol" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/database.py#L107-L146
hotdoc/hotdoc
hotdoc/core/database.py
Database.persist
def persist(self): """ Banana banana """ os.makedirs(self.__symbol_folder, exist_ok=True) os.makedirs(self.__aliases_folder, exist_ok=True) os.makedirs(self.__comments_folder, exist_ok=True) for name, sym in self.__symbols.items(): with open(self.__get_pickle_path(self.__symbol_folder, name, True), 'wb') as _: pickle.dump(sym, _) for name, aliases in self.__aliases.items(): if aliases: with open(self.__get_pickle_path(self.__aliases_folder, name, True), 'wb') as _: pickle.dump(aliases, _) for name, comment in self.__comments.items(): if comment: with open(self.__get_pickle_path(self.__comments_folder, name, True), 'wb') as _: pickle.dump(comment, _)
python
def persist(self): os.makedirs(self.__symbol_folder, exist_ok=True) os.makedirs(self.__aliases_folder, exist_ok=True) os.makedirs(self.__comments_folder, exist_ok=True) for name, sym in self.__symbols.items(): with open(self.__get_pickle_path(self.__symbol_folder, name, True), 'wb') as _: pickle.dump(sym, _) for name, aliases in self.__aliases.items(): if aliases: with open(self.__get_pickle_path(self.__aliases_folder, name, True), 'wb') as _: pickle.dump(aliases, _) for name, comment in self.__comments.items(): if comment: with open(self.__get_pickle_path(self.__comments_folder, name, True), 'wb') as _: pickle.dump(comment, _)
[ "def", "persist", "(", "self", ")", ":", "os", ".", "makedirs", "(", "self", ".", "__symbol_folder", ",", "exist_ok", "=", "True", ")", "os", ".", "makedirs", "(", "self", ".", "__aliases_folder", ",", "exist_ok", "=", "True", ")", "os", ".", "makedirs", "(", "self", ".", "__comments_folder", ",", "exist_ok", "=", "True", ")", "for", "name", ",", "sym", "in", "self", ".", "__symbols", ".", "items", "(", ")", ":", "with", "open", "(", "self", ".", "__get_pickle_path", "(", "self", ".", "__symbol_folder", ",", "name", ",", "True", ")", ",", "'wb'", ")", "as", "_", ":", "pickle", ".", "dump", "(", "sym", ",", "_", ")", "for", "name", ",", "aliases", "in", "self", ".", "__aliases", ".", "items", "(", ")", ":", "if", "aliases", ":", "with", "open", "(", "self", ".", "__get_pickle_path", "(", "self", ".", "__aliases_folder", ",", "name", ",", "True", ")", ",", "'wb'", ")", "as", "_", ":", "pickle", ".", "dump", "(", "aliases", ",", "_", ")", "for", "name", ",", "comment", "in", "self", ".", "__comments", ".", "items", "(", ")", ":", "if", "comment", ":", "with", "open", "(", "self", ".", "__get_pickle_path", "(", "self", ".", "__comments_folder", ",", "name", ",", "True", ")", ",", "'wb'", ")", "as", "_", ":", "pickle", ".", "dump", "(", "comment", ",", "_", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/database.py#L155-L172
hotdoc/hotdoc
hotdoc/utils/utils.py
splitall
def splitall(path): """ Splits path in its components: foo/bar, /foo/bar and /foo/bar/ will all return ['foo', 'bar'] """ head, tail = os.path.split(os.path.normpath(path)) components = [] while tail: components.insert(0, tail) head, tail = os.path.split(head) return components
python
def splitall(path): head, tail = os.path.split(os.path.normpath(path)) components = [] while tail: components.insert(0, tail) head, tail = os.path.split(head) return components
[ "def", "splitall", "(", "path", ")", ":", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "normpath", "(", "path", ")", ")", "components", "=", "[", "]", "while", "tail", ":", "components", ".", "insert", "(", "0", ",", "tail", ")", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "head", ")", "return", "components" ]
Splits path in its components: foo/bar, /foo/bar and /foo/bar/ will all return ['foo', 'bar']
[ "Splits", "path", "in", "its", "components", ":", "foo", "/", "bar", "/", "foo", "/", "bar", "and", "/", "foo", "/", "bar", "/", "will", "all", "return", "[", "foo", "bar", "]" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L46-L57
hotdoc/hotdoc
hotdoc/utils/utils.py
recursive_overwrite
def recursive_overwrite(src, dest, ignore=None): """ Banana banana """ if os.path.islink(src): linkto = os.readlink(src) if os.path.exists(dest): os.remove(dest) symlink(linkto, dest) elif os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) if ignore is not None: ignored = ignore(src, files) else: ignored = set() for _ in files: if _ not in ignored: recursive_overwrite(os.path.join(src, _), os.path.join(dest, _), ignore) else: shutil.copyfile(src, dest)
python
def recursive_overwrite(src, dest, ignore=None): if os.path.islink(src): linkto = os.readlink(src) if os.path.exists(dest): os.remove(dest) symlink(linkto, dest) elif os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) if ignore is not None: ignored = ignore(src, files) else: ignored = set() for _ in files: if _ not in ignored: recursive_overwrite(os.path.join(src, _), os.path.join(dest, _), ignore) else: shutil.copyfile(src, dest)
[ "def", "recursive_overwrite", "(", "src", ",", "dest", ",", "ignore", "=", "None", ")", ":", "if", "os", ".", "path", ".", "islink", "(", "src", ")", ":", "linkto", "=", "os", ".", "readlink", "(", "src", ")", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "os", ".", "remove", "(", "dest", ")", "symlink", "(", "linkto", ",", "dest", ")", "elif", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest", ")", ":", "os", ".", "makedirs", "(", "dest", ")", "files", "=", "os", ".", "listdir", "(", "src", ")", "if", "ignore", "is", "not", "None", ":", "ignored", "=", "ignore", "(", "src", ",", "files", ")", "else", ":", "ignored", "=", "set", "(", ")", "for", "_", "in", "files", ":", "if", "_", "not", "in", "ignored", ":", "recursive_overwrite", "(", "os", ".", "path", ".", "join", "(", "src", ",", "_", ")", ",", "os", ".", "path", ".", "join", "(", "dest", ",", "_", ")", ",", "ignore", ")", "else", ":", "shutil", ".", "copyfile", "(", "src", ",", "dest", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L60-L83
hotdoc/hotdoc
hotdoc/utils/utils.py
flatten_list
def flatten_list(list_): """ Banana banana """ res = [] for elem in list_: if isinstance(elem, list): res.extend(flatten_list(elem)) else: res.append(elem) return res
python
def flatten_list(list_): res = [] for elem in list_: if isinstance(elem, list): res.extend(flatten_list(elem)) else: res.append(elem) return res
[ "def", "flatten_list", "(", "list_", ")", ":", "res", "=", "[", "]", "for", "elem", "in", "list_", ":", "if", "isinstance", "(", "elem", ",", "list", ")", ":", "res", ".", "extend", "(", "flatten_list", "(", "elem", ")", ")", "else", ":", "res", ".", "append", "(", "elem", ")", "return", "res" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L103-L115
hotdoc/hotdoc
hotdoc/utils/utils.py
__get_extra_extension_classes
def __get_extra_extension_classes(paths): """ Banana banana """ extra_classes = [] wset = pkg_resources.WorkingSet([]) distributions, _ = wset.find_plugins(pkg_resources.Environment(paths)) for dist in distributions: sys.path.append(dist.location) wset.add(dist) for entry_point in wset.iter_entry_points(group='hotdoc.extensions', name='get_extension_classes'): try: activation_function = entry_point.load() classes = activation_function() # pylint: disable=broad-except except Exception as exc: info("Failed to load %s %s" % (entry_point.module_name, exc)) debug(traceback.format_exc()) continue for klass in classes: extra_classes.append(klass) return extra_classes
python
def __get_extra_extension_classes(paths): extra_classes = [] wset = pkg_resources.WorkingSet([]) distributions, _ = wset.find_plugins(pkg_resources.Environment(paths)) for dist in distributions: sys.path.append(dist.location) wset.add(dist) for entry_point in wset.iter_entry_points(group='hotdoc.extensions', name='get_extension_classes'): try: activation_function = entry_point.load() classes = activation_function() except Exception as exc: info("Failed to load %s %s" % (entry_point.module_name, exc)) debug(traceback.format_exc()) continue for klass in classes: extra_classes.append(klass) return extra_classes
[ "def", "__get_extra_extension_classes", "(", "paths", ")", ":", "extra_classes", "=", "[", "]", "wset", "=", "pkg_resources", ".", "WorkingSet", "(", "[", "]", ")", "distributions", ",", "_", "=", "wset", ".", "find_plugins", "(", "pkg_resources", ".", "Environment", "(", "paths", ")", ")", "for", "dist", "in", "distributions", ":", "sys", ".", "path", ".", "append", "(", "dist", ".", "location", ")", "wset", ".", "add", "(", "dist", ")", "for", "entry_point", "in", "wset", ".", "iter_entry_points", "(", "group", "=", "'hotdoc.extensions'", ",", "name", "=", "'get_extension_classes'", ")", ":", "try", ":", "activation_function", "=", "entry_point", ".", "load", "(", ")", "classes", "=", "activation_function", "(", ")", "# pylint: disable=broad-except", "except", "Exception", "as", "exc", ":", "info", "(", "\"Failed to load %s %s\"", "%", "(", "entry_point", ".", "module_name", ",", "exc", ")", ")", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "continue", "for", "klass", "in", "classes", ":", "extra_classes", ".", "append", "(", "klass", ")", "return", "extra_classes" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L128-L154
hotdoc/hotdoc
hotdoc/utils/utils.py
get_extension_classes
def get_extension_classes(sort, extra_extension_paths=None): """ Banana banana """ all_classes = {} deps_map = {} for entry_point in pkg_resources.iter_entry_points( group='hotdoc.extensions', name='get_extension_classes'): if entry_point.module_name == 'hotdoc_c_extension.extensions': continue try: activation_function = entry_point.load() classes = activation_function() # pylint: disable=broad-except except Exception as exc: info("Failed to load %s" % entry_point.module_name, exc) debug(traceback.format_exc()) continue for klass in classes: all_classes[klass.extension_name] = klass if extra_extension_paths: for klass in __get_extra_extension_classes(extra_extension_paths): all_classes[klass.extension_name] = klass klass_list = list(all_classes.values()) if not sort: return klass_list for i, klass in enumerate(klass_list): deps = klass.get_dependencies() topodeps = set() for dep in deps: if dep.dependency_name not in all_classes: if dep.optional: continue else: error("setup-issue", "Missing dependency %s for %s" % (dep.dependency_name, klass.extension_name)) if dep.is_upstream: topodeps.add( klass_list.index(all_classes[dep.dependency_name])) deps_map[i] = topodeps sorted_class_indices = toposort_flatten(deps_map) sorted_classes = [klass_list[i] for i in sorted_class_indices] return sorted_classes
python
def get_extension_classes(sort, extra_extension_paths=None): all_classes = {} deps_map = {} for entry_point in pkg_resources.iter_entry_points( group='hotdoc.extensions', name='get_extension_classes'): if entry_point.module_name == 'hotdoc_c_extension.extensions': continue try: activation_function = entry_point.load() classes = activation_function() except Exception as exc: info("Failed to load %s" % entry_point.module_name, exc) debug(traceback.format_exc()) continue for klass in classes: all_classes[klass.extension_name] = klass if extra_extension_paths: for klass in __get_extra_extension_classes(extra_extension_paths): all_classes[klass.extension_name] = klass klass_list = list(all_classes.values()) if not sort: return klass_list for i, klass in enumerate(klass_list): deps = klass.get_dependencies() topodeps = set() for dep in deps: if dep.dependency_name not in all_classes: if dep.optional: continue else: error("setup-issue", "Missing dependency %s for %s" % (dep.dependency_name, klass.extension_name)) if dep.is_upstream: topodeps.add( klass_list.index(all_classes[dep.dependency_name])) deps_map[i] = topodeps sorted_class_indices = toposort_flatten(deps_map) sorted_classes = [klass_list[i] for i in sorted_class_indices] return sorted_classes
[ "def", "get_extension_classes", "(", "sort", ",", "extra_extension_paths", "=", "None", ")", ":", "all_classes", "=", "{", "}", "deps_map", "=", "{", "}", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "'hotdoc.extensions'", ",", "name", "=", "'get_extension_classes'", ")", ":", "if", "entry_point", ".", "module_name", "==", "'hotdoc_c_extension.extensions'", ":", "continue", "try", ":", "activation_function", "=", "entry_point", ".", "load", "(", ")", "classes", "=", "activation_function", "(", ")", "# pylint: disable=broad-except", "except", "Exception", "as", "exc", ":", "info", "(", "\"Failed to load %s\"", "%", "entry_point", ".", "module_name", ",", "exc", ")", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "continue", "for", "klass", "in", "classes", ":", "all_classes", "[", "klass", ".", "extension_name", "]", "=", "klass", "if", "extra_extension_paths", ":", "for", "klass", "in", "__get_extra_extension_classes", "(", "extra_extension_paths", ")", ":", "all_classes", "[", "klass", ".", "extension_name", "]", "=", "klass", "klass_list", "=", "list", "(", "all_classes", ".", "values", "(", ")", ")", "if", "not", "sort", ":", "return", "klass_list", "for", "i", ",", "klass", "in", "enumerate", "(", "klass_list", ")", ":", "deps", "=", "klass", ".", "get_dependencies", "(", ")", "topodeps", "=", "set", "(", ")", "for", "dep", "in", "deps", ":", "if", "dep", ".", "dependency_name", "not", "in", "all_classes", ":", "if", "dep", ".", "optional", ":", "continue", "else", ":", "error", "(", "\"setup-issue\"", ",", "\"Missing dependency %s for %s\"", "%", "(", "dep", ".", "dependency_name", ",", "klass", ".", "extension_name", ")", ")", "if", "dep", ".", "is_upstream", ":", "topodeps", ".", "add", "(", "klass_list", ".", "index", "(", "all_classes", "[", "dep", ".", "dependency_name", "]", ")", ")", "deps_map", "[", "i", "]", "=", "topodeps", "sorted_class_indices", "=", "toposort_flatten", "(", "deps_map", ")", "sorted_classes", "=", "[", "klass_list", "[", "i", "]", "for", "i", "in", "sorted_class_indices", "]", "return", "sorted_classes" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L159-L209
hotdoc/hotdoc
hotdoc/utils/utils.py
touch
def touch(fname): """ Mimics the `touch` command Busy loops until the mtime has actually been changed, use for tests only """ orig_mtime = get_mtime(fname) while get_mtime(fname) == orig_mtime: pathlib.Path(fname).touch()
python
def touch(fname): orig_mtime = get_mtime(fname) while get_mtime(fname) == orig_mtime: pathlib.Path(fname).touch()
[ "def", "touch", "(", "fname", ")", ":", "orig_mtime", "=", "get_mtime", "(", "fname", ")", "while", "get_mtime", "(", "fname", ")", "==", "orig_mtime", ":", "pathlib", ".", "Path", "(", "fname", ")", ".", "touch", "(", ")" ]
Mimics the `touch` command Busy loops until the mtime has actually been changed, use for tests only
[ "Mimics", "the", "touch", "command" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L306-L314
hotdoc/hotdoc
hotdoc/utils/utils.py
dedent
def dedent(line): """ Banana banana """ indentation = 0 for char in line: if char not in ' \t': break indentation += 1 if char == '\t': indentation = _round8(indentation) if indentation % 8 != 0: raise IndentError(column=indentation) return indentation // 8, line.strip()
python
def dedent(line): indentation = 0 for char in line: if char not in ' \t': break indentation += 1 if char == '\t': indentation = _round8(indentation) if indentation % 8 != 0: raise IndentError(column=indentation) return indentation // 8, line.strip()
[ "def", "dedent", "(", "line", ")", ":", "indentation", "=", "0", "for", "char", "in", "line", ":", "if", "char", "not", "in", "' \\t'", ":", "break", "indentation", "+=", "1", "if", "char", "==", "'\\t'", ":", "indentation", "=", "_round8", "(", "indentation", ")", "if", "indentation", "%", "8", "!=", "0", ":", "raise", "IndentError", "(", "column", "=", "indentation", ")", "return", "indentation", "//", "8", ",", "line", ".", "strip", "(", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L328-L343
hotdoc/hotdoc
hotdoc/utils/utils.py
id_from_text
def id_from_text(text, add_hash=False): """ Banana banana """ id_ = text.strip().lower() # No unicode in urls id_ = id_.encode('ascii', errors='ignore').decode() id_ = re.sub(r"[^\w\s]", '', id_) id_ = re.sub(r"\s+", '-', id_) if add_hash: return '#%s' % id_ return id_
python
def id_from_text(text, add_hash=False): id_ = text.strip().lower() id_ = id_.encode('ascii', errors='ignore').decode() id_ = re.sub(r"[^\w\s]", '', id_) id_ = re.sub(r"\s+", '-', id_) if add_hash: return ' return id_
[ "def", "id_from_text", "(", "text", ",", "add_hash", "=", "False", ")", ":", "id_", "=", "text", ".", "strip", "(", ")", ".", "lower", "(", ")", "# No unicode in urls", "id_", "=", "id_", ".", "encode", "(", "'ascii'", ",", "errors", "=", "'ignore'", ")", ".", "decode", "(", ")", "id_", "=", "re", ".", "sub", "(", "r\"[^\\w\\s]\"", ",", "''", ",", "id_", ")", "id_", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "'-'", ",", "id_", ")", "if", "add_hash", ":", "return", "'#%s'", "%", "id_", "return", "id_" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L355-L368
hotdoc/hotdoc
hotdoc/utils/utils.py
OrderedSet.discard
def discard(self, key): """ Banana banana """ if key in self.map: key, prev, nxt = self.map.pop(key) prev[2] = nxt nxt[1] = prev
python
def discard(self, key): if key in self.map: key, prev, nxt = self.map.pop(key) prev[2] = nxt nxt[1] = prev
[ "def", "discard", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "map", ":", "key", ",", "prev", ",", "nxt", "=", "self", ".", "map", ".", "pop", "(", "key", ")", "prev", "[", "2", "]", "=", "nxt", "nxt", "[", "1", "]", "=", "prev" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/utils.py#L261-L268
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.debug
def debug(self, message, domain=None): """ Shortcut function for `utils.loggable.debug` Args: message: see `utils.loggable.debug` domain: see `utils.loggable.debug` """ if domain is None: domain = self.extension_name debug(message, domain)
python
def debug(self, message, domain=None): if domain is None: domain = self.extension_name debug(message, domain)
[ "def", "debug", "(", "self", ",", "message", ",", "domain", "=", "None", ")", ":", "if", "domain", "is", "None", ":", "domain", "=", "self", ".", "extension_name", "debug", "(", "message", ",", "domain", ")" ]
Shortcut function for `utils.loggable.debug` Args: message: see `utils.loggable.debug` domain: see `utils.loggable.debug`
[ "Shortcut", "function", "for", "utils", ".", "loggable", ".", "debug" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L148-L158
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.info
def info(self, message, domain=None): """ Shortcut function for `utils.loggable.info` Args: message: see `utils.loggable.info` domain: see `utils.loggable.info` """ if domain is None: domain = self.extension_name info(message, domain)
python
def info(self, message, domain=None): if domain is None: domain = self.extension_name info(message, domain)
[ "def", "info", "(", "self", ",", "message", ",", "domain", "=", "None", ")", ":", "if", "domain", "is", "None", ":", "domain", "=", "self", ".", "extension_name", "info", "(", "message", ",", "domain", ")" ]
Shortcut function for `utils.loggable.info` Args: message: see `utils.loggable.info` domain: see `utils.loggable.info`
[ "Shortcut", "function", "for", "utils", ".", "loggable", ".", "info" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L160-L170
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.parse_config
def parse_config(self, config): """ Override this, making sure to chain up first, if your extension adds its own custom command line arguments, or you want to do any further processing on the automatically added arguments. The default implementation will set attributes on the extension: - 'sources': a set of absolute paths to source files for this extension - 'index': absolute path to the index for this extension Additionally, it will set an attribute for each argument added with `Extension.add_path_argument` or `Extension.add_paths_argument`, with the extension's `Extension.argument_prefix` stripped, and dashes changed to underscores. Args: config: a `config.Config` instance """ prefix = self.argument_prefix self.sources = config.get_sources(prefix) self.smart_sources = [ self._get_smart_filename(s) for s in self.sources] self.index = config.get_index(prefix) self.source_roots = OrderedSet( config.get_paths('%s_source_roots' % prefix)) for arg, dest in list(self.paths_arguments.items()): val = config.get_paths(arg) setattr(self, dest, val) for arg, dest in list(self.path_arguments.items()): val = config.get_path(arg) setattr(self, dest, val) self.formatter.parse_config(config)
python
def parse_config(self, config): prefix = self.argument_prefix self.sources = config.get_sources(prefix) self.smart_sources = [ self._get_smart_filename(s) for s in self.sources] self.index = config.get_index(prefix) self.source_roots = OrderedSet( config.get_paths('%s_source_roots' % prefix)) for arg, dest in list(self.paths_arguments.items()): val = config.get_paths(arg) setattr(self, dest, val) for arg, dest in list(self.path_arguments.items()): val = config.get_path(arg) setattr(self, dest, val) self.formatter.parse_config(config)
[ "def", "parse_config", "(", "self", ",", "config", ")", ":", "prefix", "=", "self", ".", "argument_prefix", "self", ".", "sources", "=", "config", ".", "get_sources", "(", "prefix", ")", "self", ".", "smart_sources", "=", "[", "self", ".", "_get_smart_filename", "(", "s", ")", "for", "s", "in", "self", ".", "sources", "]", "self", ".", "index", "=", "config", ".", "get_index", "(", "prefix", ")", "self", ".", "source_roots", "=", "OrderedSet", "(", "config", ".", "get_paths", "(", "'%s_source_roots'", "%", "prefix", ")", ")", "for", "arg", ",", "dest", "in", "list", "(", "self", ".", "paths_arguments", ".", "items", "(", ")", ")", ":", "val", "=", "config", ".", "get_paths", "(", "arg", ")", "setattr", "(", "self", ",", "dest", ",", "val", ")", "for", "arg", ",", "dest", "in", "list", "(", "self", ".", "path_arguments", ".", "items", "(", ")", ")", ":", "val", "=", "config", ".", "get_path", "(", "arg", ")", "setattr", "(", "self", ",", "dest", ",", "val", ")", "self", ".", "formatter", ".", "parse_config", "(", "config", ")" ]
Override this, making sure to chain up first, if your extension adds its own custom command line arguments, or you want to do any further processing on the automatically added arguments. The default implementation will set attributes on the extension: - 'sources': a set of absolute paths to source files for this extension - 'index': absolute path to the index for this extension Additionally, it will set an attribute for each argument added with `Extension.add_path_argument` or `Extension.add_paths_argument`, with the extension's `Extension.argument_prefix` stripped, and dashes changed to underscores. Args: config: a `config.Config` instance
[ "Override", "this", "making", "sure", "to", "chain", "up", "first", "if", "your", "extension", "adds", "its", "own", "custom", "command", "line", "arguments", "or", "you", "want", "to", "do", "any", "further", "processing", "on", "the", "automatically", "added", "arguments", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L403-L437
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.add_attrs
def add_attrs(self, symbol, **kwargs): """ Helper for setting symbol extension attributes """ for key, val in kwargs.items(): symbol.add_extension_attribute(self.extension_name, key, val)
python
def add_attrs(self, symbol, **kwargs): for key, val in kwargs.items(): symbol.add_extension_attribute(self.extension_name, key, val)
[ "def", "add_attrs", "(", "self", ",", "symbol", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "symbol", ".", "add_extension_attribute", "(", "self", ".", "extension_name", ",", "key", ",", "val", ")" ]
Helper for setting symbol extension attributes
[ "Helper", "for", "setting", "symbol", "extension", "attributes" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L439-L444
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.get_attr
def get_attr(self, symbol, attrname): """ Helper for getting symbol extension attributes """ return symbol.extension_attributes.get(self.extension_name, {}).get( attrname, None)
python
def get_attr(self, symbol, attrname): return symbol.extension_attributes.get(self.extension_name, {}).get( attrname, None)
[ "def", "get_attr", "(", "self", ",", "symbol", ",", "attrname", ")", ":", "return", "symbol", ".", "extension_attributes", ".", "get", "(", "self", ".", "extension_name", ",", "{", "}", ")", ".", "get", "(", "attrname", ",", "None", ")" ]
Helper for getting symbol extension attributes
[ "Helper", "for", "getting", "symbol", "extension", "attributes" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L446-L451
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.add_index_argument
def add_index_argument(cls, group): """ Subclasses may call this to add an index argument. Args: group: arparse.ArgumentGroup, the extension argument group prefix: str, arguments have to be namespaced """ prefix = cls.argument_prefix group.add_argument( '--%s-index' % prefix, action="store", dest="%s_index" % prefix, help=("Name of the %s root markdown file, can be None" % ( cls.extension_name)))
python
def add_index_argument(cls, group): prefix = cls.argument_prefix group.add_argument( '--%s-index' % prefix, action="store", dest="%s_index" % prefix, help=("Name of the %s root markdown file, can be None" % ( cls.extension_name)))
[ "def", "add_index_argument", "(", "cls", ",", "group", ")", ":", "prefix", "=", "cls", ".", "argument_prefix", "group", ".", "add_argument", "(", "'--%s-index'", "%", "prefix", ",", "action", "=", "\"store\"", ",", "dest", "=", "\"%s_index\"", "%", "prefix", ",", "help", "=", "(", "\"Name of the %s root markdown file, can be None\"", "%", "(", "cls", ".", "extension_name", ")", ")", ")" ]
Subclasses may call this to add an index argument. Args: group: arparse.ArgumentGroup, the extension argument group prefix: str, arguments have to be namespaced
[ "Subclasses", "may", "call", "this", "to", "add", "an", "index", "argument", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L479-L493
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.add_sources_argument
def add_sources_argument(cls, group, allow_filters=True, prefix=None, add_root_paths=False): """ Subclasses may call this to add sources and source_filters arguments. Args: group: arparse.ArgumentGroup, the extension argument group allow_filters: bool, Whether the extension wishes to expose a source_filters argument. prefix: str, arguments have to be namespaced. """ prefix = prefix or cls.argument_prefix group.add_argument("--%s-sources" % prefix, action="store", nargs="+", dest="%s_sources" % prefix.replace('-', '_'), help="%s source files to parse" % prefix) if allow_filters: group.add_argument("--%s-source-filters" % prefix, action="store", nargs="+", dest="%s_source_filters" % prefix.replace( '-', '_'), help="%s source files to ignore" % prefix) if add_root_paths: group.add_argument("--%s-source-roots" % prefix, action="store", nargs="+", dest="%s_source_roots" % prefix.replace( '-', '_'), help="%s source root directories allowing files " "to be referenced relatively to those" % prefix)
python
def add_sources_argument(cls, group, allow_filters=True, prefix=None, add_root_paths=False): prefix = prefix or cls.argument_prefix group.add_argument("--%s-sources" % prefix, action="store", nargs="+", dest="%s_sources" % prefix.replace('-', '_'), help="%s source files to parse" % prefix) if allow_filters: group.add_argument("--%s-source-filters" % prefix, action="store", nargs="+", dest="%s_source_filters" % prefix.replace( '-', '_'), help="%s source files to ignore" % prefix) if add_root_paths: group.add_argument("--%s-source-roots" % prefix, action="store", nargs="+", dest="%s_source_roots" % prefix.replace( '-', '_'), help="%s source root directories allowing files " "to be referenced relatively to those" % prefix)
[ "def", "add_sources_argument", "(", "cls", ",", "group", ",", "allow_filters", "=", "True", ",", "prefix", "=", "None", ",", "add_root_paths", "=", "False", ")", ":", "prefix", "=", "prefix", "or", "cls", ".", "argument_prefix", "group", ".", "add_argument", "(", "\"--%s-sources\"", "%", "prefix", ",", "action", "=", "\"store\"", ",", "nargs", "=", "\"+\"", ",", "dest", "=", "\"%s_sources\"", "%", "prefix", ".", "replace", "(", "'-'", ",", "'_'", ")", ",", "help", "=", "\"%s source files to parse\"", "%", "prefix", ")", "if", "allow_filters", ":", "group", ".", "add_argument", "(", "\"--%s-source-filters\"", "%", "prefix", ",", "action", "=", "\"store\"", ",", "nargs", "=", "\"+\"", ",", "dest", "=", "\"%s_source_filters\"", "%", "prefix", ".", "replace", "(", "'-'", ",", "'_'", ")", ",", "help", "=", "\"%s source files to ignore\"", "%", "prefix", ")", "if", "add_root_paths", ":", "group", ".", "add_argument", "(", "\"--%s-source-roots\"", "%", "prefix", ",", "action", "=", "\"store\"", ",", "nargs", "=", "\"+\"", ",", "dest", "=", "\"%s_source_roots\"", "%", "prefix", ".", "replace", "(", "'-'", ",", "'_'", ")", ",", "help", "=", "\"%s source root directories allowing files \"", "\"to be referenced relatively to those\"", "%", "prefix", ")" ]
Subclasses may call this to add sources and source_filters arguments. Args: group: arparse.ArgumentGroup, the extension argument group allow_filters: bool, Whether the extension wishes to expose a source_filters argument. prefix: str, arguments have to be namespaced.
[ "Subclasses", "may", "call", "this", "to", "add", "sources", "and", "source_filters", "arguments", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L496-L526
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.add_path_argument
def add_path_argument(cls, group, argname, dest=None, help_=None): """ Subclasses may call this to expose a path argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `dest` argument of `argparse.ArgumentParser.add_argument`, will be namespaced. help_: str, similar to the `help` argument of `argparse.ArgumentParser.add_argument`. """ prefixed = '%s-%s' % (cls.argument_prefix, argname) if dest is None: dest = prefixed.replace('-', '_') final_dest = dest[len(cls.argument_prefix) + 1:] else: final_dest = dest dest = '%s_%s' % (cls.argument_prefix, dest) group.add_argument('--%s' % prefixed, action='store', dest=dest, help=help_) cls.path_arguments[dest] = final_dest
python
def add_path_argument(cls, group, argname, dest=None, help_=None): prefixed = '%s-%s' % (cls.argument_prefix, argname) if dest is None: dest = prefixed.replace('-', '_') final_dest = dest[len(cls.argument_prefix) + 1:] else: final_dest = dest dest = '%s_%s' % (cls.argument_prefix, dest) group.add_argument('--%s' % prefixed, action='store', dest=dest, help=help_) cls.path_arguments[dest] = final_dest
[ "def", "add_path_argument", "(", "cls", ",", "group", ",", "argname", ",", "dest", "=", "None", ",", "help_", "=", "None", ")", ":", "prefixed", "=", "'%s-%s'", "%", "(", "cls", ".", "argument_prefix", ",", "argname", ")", "if", "dest", "is", "None", ":", "dest", "=", "prefixed", ".", "replace", "(", "'-'", ",", "'_'", ")", "final_dest", "=", "dest", "[", "len", "(", "cls", ".", "argument_prefix", ")", "+", "1", ":", "]", "else", ":", "final_dest", "=", "dest", "dest", "=", "'%s_%s'", "%", "(", "cls", ".", "argument_prefix", ",", "dest", ")", "group", ".", "add_argument", "(", "'--%s'", "%", "prefixed", ",", "action", "=", "'store'", ",", "dest", "=", "dest", ",", "help", "=", "help_", ")", "cls", ".", "path_arguments", "[", "dest", "]", "=", "final_dest" ]
Subclasses may call this to expose a path argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `dest` argument of `argparse.ArgumentParser.add_argument`, will be namespaced. help_: str, similar to the `help` argument of `argparse.ArgumentParser.add_argument`.
[ "Subclasses", "may", "call", "this", "to", "expose", "a", "path", "argument", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L529-L551
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.add_paths_argument
def add_paths_argument(cls, group, argname, dest=None, help_=None): """ Subclasses may call this to expose a paths argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `dest` argument of `argparse.ArgumentParser.add_argument`, will be namespaced. help_: str, similar to the `help` argument of `argparse.ArgumentParser.add_argument`. """ prefixed = '%s-%s' % (cls.argument_prefix, argname) if dest is None: dest = prefixed.replace('-', '_') final_dest = dest[len(cls.argument_prefix) + 1:] else: final_dest = dest dest = '%s_%s' % (cls.argument_prefix, dest) group.add_argument('--%s' % prefixed, action='store', nargs='+', dest=dest, help=help_) cls.paths_arguments[dest] = final_dest
python
def add_paths_argument(cls, group, argname, dest=None, help_=None): prefixed = '%s-%s' % (cls.argument_prefix, argname) if dest is None: dest = prefixed.replace('-', '_') final_dest = dest[len(cls.argument_prefix) + 1:] else: final_dest = dest dest = '%s_%s' % (cls.argument_prefix, dest) group.add_argument('--%s' % prefixed, action='store', nargs='+', dest=dest, help=help_) cls.paths_arguments[dest] = final_dest
[ "def", "add_paths_argument", "(", "cls", ",", "group", ",", "argname", ",", "dest", "=", "None", ",", "help_", "=", "None", ")", ":", "prefixed", "=", "'%s-%s'", "%", "(", "cls", ".", "argument_prefix", ",", "argname", ")", "if", "dest", "is", "None", ":", "dest", "=", "prefixed", ".", "replace", "(", "'-'", ",", "'_'", ")", "final_dest", "=", "dest", "[", "len", "(", "cls", ".", "argument_prefix", ")", "+", "1", ":", "]", "else", ":", "final_dest", "=", "dest", "dest", "=", "'%s_%s'", "%", "(", "cls", ".", "argument_prefix", ",", "dest", ")", "group", ".", "add_argument", "(", "'--%s'", "%", "prefixed", ",", "action", "=", "'store'", ",", "nargs", "=", "'+'", ",", "dest", "=", "dest", ",", "help", "=", "help_", ")", "cls", ".", "paths_arguments", "[", "dest", "]", "=", "final_dest" ]
Subclasses may call this to expose a paths argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `dest` argument of `argparse.ArgumentParser.add_argument`, will be namespaced. help_: str, similar to the `help` argument of `argparse.ArgumentParser.add_argument`.
[ "Subclasses", "may", "call", "this", "to", "expose", "a", "paths", "argument", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L554-L576
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.create_symbol
def create_symbol(self, *args, **kwargs): """ Extensions that discover and create instances of `symbols.Symbol` should do this through this method, as it will keep an index of these which can be used when generating a "naive index". See `database.Database.create_symbol` for more information. Args: args: see `database.Database.create_symbol` kwargs: see `database.Database.create_symbol` Returns: symbols.Symbol: the created symbol, or `None`. """ if not kwargs.get('project_name'): kwargs['project_name'] = self.project.project_name sym = self.app.database.create_symbol(*args, **kwargs) if sym: # pylint: disable=unidiomatic-typecheck if type(sym) != Symbol: self._created_symbols[sym.filename].add(sym.unique_name) return sym
python
def create_symbol(self, *args, **kwargs): if not kwargs.get('project_name'): kwargs['project_name'] = self.project.project_name sym = self.app.database.create_symbol(*args, **kwargs) if sym: if type(sym) != Symbol: self._created_symbols[sym.filename].add(sym.unique_name) return sym
[ "def", "create_symbol", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "get", "(", "'project_name'", ")", ":", "kwargs", "[", "'project_name'", "]", "=", "self", ".", "project", ".", "project_name", "sym", "=", "self", ".", "app", ".", "database", ".", "create_symbol", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "sym", ":", "# pylint: disable=unidiomatic-typecheck", "if", "type", "(", "sym", ")", "!=", "Symbol", ":", "self", ".", "_created_symbols", "[", "sym", ".", "filename", "]", ".", "add", "(", "sym", ".", "unique_name", ")", "return", "sym" ]
Extensions that discover and create instances of `symbols.Symbol` should do this through this method, as it will keep an index of these which can be used when generating a "naive index". See `database.Database.create_symbol` for more information. Args: args: see `database.Database.create_symbol` kwargs: see `database.Database.create_symbol` Returns: symbols.Symbol: the created symbol, or `None`.
[ "Extensions", "that", "discover", "and", "create", "instances", "of", "symbols", ".", "Symbol", "should", "do", "this", "through", "this", "method", "as", "it", "will", "keep", "an", "index", "of", "these", "which", "can", "be", "used", "when", "generating", "a", "naive", "index", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L584-L609
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.format_page
def format_page(self, page, link_resolver, output): """ Called by `project.Project.format_page`, to leave full control to extensions over the formatting of the pages they are responsible of. Args: page: tree.Page, the page to format. link_resolver: links.LinkResolver, object responsible for resolving links potentially mentioned in `page` output: str, path to the output directory. """ debug('Formatting page %s' % page.link.ref, 'formatting') if output: actual_output = os.path.join(output, 'html') if not os.path.exists(actual_output): os.makedirs(actual_output) else: actual_output = None page.format(self.formatter, link_resolver, actual_output)
python
def format_page(self, page, link_resolver, output): debug('Formatting page %s' % page.link.ref, 'formatting') if output: actual_output = os.path.join(output, 'html') if not os.path.exists(actual_output): os.makedirs(actual_output) else: actual_output = None page.format(self.formatter, link_resolver, actual_output)
[ "def", "format_page", "(", "self", ",", "page", ",", "link_resolver", ",", "output", ")", ":", "debug", "(", "'Formatting page %s'", "%", "page", ".", "link", ".", "ref", ",", "'formatting'", ")", "if", "output", ":", "actual_output", "=", "os", ".", "path", ".", "join", "(", "output", ",", "'html'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "actual_output", ")", ":", "os", ".", "makedirs", "(", "actual_output", ")", "else", ":", "actual_output", "=", "None", "page", ".", "format", "(", "self", ".", "formatter", ",", "link_resolver", ",", "actual_output", ")" ]
Called by `project.Project.format_page`, to leave full control to extensions over the formatting of the pages they are responsible of. Args: page: tree.Page, the page to format. link_resolver: links.LinkResolver, object responsible for resolving links potentially mentioned in `page` output: str, path to the output directory.
[ "Called", "by", "project", ".", "Project", ".", "format_page", "to", "leave", "full", "control", "to", "extensions", "over", "the", "formatting", "of", "the", "pages", "they", "are", "responsible", "of", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L646-L668
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.write_out_sitemap
def write_out_sitemap(self, opath): """ Banana banana """ if opath not in self.written_out_sitemaps: Extension.formatted_sitemap = self.formatter.format_navigation( self.app.project) if Extension.formatted_sitemap: escaped_sitemap = Extension.formatted_sitemap.replace( '\\', '\\\\').replace('"', '\\"').replace('\n', '') js_wrapper = 'sitemap_downloaded_cb("%s");' % escaped_sitemap with open(opath, 'w') as _: _.write(js_wrapper) self.written_out_sitemaps.add(opath)
python
def write_out_sitemap(self, opath): if opath not in self.written_out_sitemaps: Extension.formatted_sitemap = self.formatter.format_navigation( self.app.project) if Extension.formatted_sitemap: escaped_sitemap = Extension.formatted_sitemap.replace( '\\', '\\\\').replace('"', '\\"').replace('\n', '') js_wrapper = 'sitemap_downloaded_cb("%s");' % escaped_sitemap with open(opath, 'w') as _: _.write(js_wrapper) self.written_out_sitemaps.add(opath)
[ "def", "write_out_sitemap", "(", "self", ",", "opath", ")", ":", "if", "opath", "not", "in", "self", ".", "written_out_sitemaps", ":", "Extension", ".", "formatted_sitemap", "=", "self", ".", "formatter", ".", "format_navigation", "(", "self", ".", "app", ".", "project", ")", "if", "Extension", ".", "formatted_sitemap", ":", "escaped_sitemap", "=", "Extension", ".", "formatted_sitemap", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", "js_wrapper", "=", "'sitemap_downloaded_cb(\"%s\");'", "%", "escaped_sitemap", "with", "open", "(", "opath", ",", "'w'", ")", "as", "_", ":", "_", ".", "write", "(", "js_wrapper", ")", "self", ".", "written_out_sitemaps", ".", "add", "(", "opath", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L670-L684
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.write_out_page
def write_out_page(self, output, page): """ Banana banana """ subpages = OrderedDict({}) all_pages = self.project.tree.get_pages() subpage_names = self.get_subpages_sorted(all_pages, page) for pagename in subpage_names: proj = self.project.subprojects.get(pagename) if not proj: cpage = all_pages[pagename] sub_formatter = self.project.extensions[ cpage.extension_name].formatter else: cpage = proj.tree.root sub_formatter = proj.extensions[cpage.extension_name].formatter subpage_link, _ = cpage.link.get_link(self.app.link_resolver) prefix = sub_formatter.get_output_folder(cpage) if prefix: subpage_link = '%s/%s' % (prefix, subpage_link) subpages[subpage_link] = cpage html_subpages = self.formatter.format_subpages(page, subpages) js_dir = os.path.join(output, 'html', 'assets', 'js') if not os.path.exists(js_dir): os.makedirs(js_dir) sm_path = os.path.join(js_dir, 'sitemap.js') self.write_out_sitemap(sm_path) self.formatter.write_out(page, html_subpages, output)
python
def write_out_page(self, output, page): subpages = OrderedDict({}) all_pages = self.project.tree.get_pages() subpage_names = self.get_subpages_sorted(all_pages, page) for pagename in subpage_names: proj = self.project.subprojects.get(pagename) if not proj: cpage = all_pages[pagename] sub_formatter = self.project.extensions[ cpage.extension_name].formatter else: cpage = proj.tree.root sub_formatter = proj.extensions[cpage.extension_name].formatter subpage_link, _ = cpage.link.get_link(self.app.link_resolver) prefix = sub_formatter.get_output_folder(cpage) if prefix: subpage_link = '%s/%s' % (prefix, subpage_link) subpages[subpage_link] = cpage html_subpages = self.formatter.format_subpages(page, subpages) js_dir = os.path.join(output, 'html', 'assets', 'js') if not os.path.exists(js_dir): os.makedirs(js_dir) sm_path = os.path.join(js_dir, 'sitemap.js') self.write_out_sitemap(sm_path) self.formatter.write_out(page, html_subpages, output)
[ "def", "write_out_page", "(", "self", ",", "output", ",", "page", ")", ":", "subpages", "=", "OrderedDict", "(", "{", "}", ")", "all_pages", "=", "self", ".", "project", ".", "tree", ".", "get_pages", "(", ")", "subpage_names", "=", "self", ".", "get_subpages_sorted", "(", "all_pages", ",", "page", ")", "for", "pagename", "in", "subpage_names", ":", "proj", "=", "self", ".", "project", ".", "subprojects", ".", "get", "(", "pagename", ")", "if", "not", "proj", ":", "cpage", "=", "all_pages", "[", "pagename", "]", "sub_formatter", "=", "self", ".", "project", ".", "extensions", "[", "cpage", ".", "extension_name", "]", ".", "formatter", "else", ":", "cpage", "=", "proj", ".", "tree", ".", "root", "sub_formatter", "=", "proj", ".", "extensions", "[", "cpage", ".", "extension_name", "]", ".", "formatter", "subpage_link", ",", "_", "=", "cpage", ".", "link", ".", "get_link", "(", "self", ".", "app", ".", "link_resolver", ")", "prefix", "=", "sub_formatter", ".", "get_output_folder", "(", "cpage", ")", "if", "prefix", ":", "subpage_link", "=", "'%s/%s'", "%", "(", "prefix", ",", "subpage_link", ")", "subpages", "[", "subpage_link", "]", "=", "cpage", "html_subpages", "=", "self", ".", "formatter", ".", "format_subpages", "(", "page", ",", "subpages", ")", "js_dir", "=", "os", ".", "path", ".", "join", "(", "output", ",", "'html'", ",", "'assets'", ",", "'js'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "js_dir", ")", ":", "os", ".", "makedirs", "(", "js_dir", ")", "sm_path", "=", "os", ".", "path", ".", "join", "(", "js_dir", ",", "'sitemap.js'", ")", "self", ".", "write_out_sitemap", "(", "sm_path", ")", "self", ".", "formatter", ".", "write_out", "(", "page", ",", "html_subpages", ",", "output", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L687-L719
hotdoc/hotdoc
hotdoc/core/extension.py
Extension.get_subpages_sorted
def get_subpages_sorted(self, pages, page): """Get @page subpages sorted appropriately.""" sorted_pages = [] to_sort = [] for subpage in page.subpages: # Do not resort subprojects even if they are # 'generated'. if pages[subpage].pre_sorted: sorted_pages.append(subpage) else: to_sort.append(subpage) return sorted_pages + sorted( to_sort, key=lambda p: pages[p].get_title().lower())
python
def get_subpages_sorted(self, pages, page): sorted_pages = [] to_sort = [] for subpage in page.subpages: if pages[subpage].pre_sorted: sorted_pages.append(subpage) else: to_sort.append(subpage) return sorted_pages + sorted( to_sort, key=lambda p: pages[p].get_title().lower())
[ "def", "get_subpages_sorted", "(", "self", ",", "pages", ",", "page", ")", ":", "sorted_pages", "=", "[", "]", "to_sort", "=", "[", "]", "for", "subpage", "in", "page", ".", "subpages", ":", "# Do not resort subprojects even if they are", "# 'generated'.", "if", "pages", "[", "subpage", "]", ".", "pre_sorted", ":", "sorted_pages", ".", "append", "(", "subpage", ")", "else", ":", "to_sort", ".", "append", "(", "subpage", ")", "return", "sorted_pages", "+", "sorted", "(", "to_sort", ",", "key", "=", "lambda", "p", ":", "pages", "[", "p", "]", ".", "get_title", "(", ")", ".", "lower", "(", ")", ")" ]
Get @page subpages sorted appropriately.
[ "Get" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/extension.py#L721-L735
hotdoc/hotdoc
hotdoc/core/project.py
CoreExtension.include_file_cb
def include_file_cb(include_path, line_ranges, symbol): """ Banana banana """ lang = '' if include_path.endswith((".md", ".markdown")): lang = 'markdown' else: split = os.path.splitext(include_path) if len(split) == 2: ext = split[1].strip('.') lang = LANG_MAPPING.get(ext) or ext if line_ranges: res = [] for line_range in line_ranges: for lineno in range(line_range[0] + 1, line_range[1] + 1): line = linecache.getline(include_path, lineno) if not line: return None res.append(line) return ''.join(res), lang with io.open(include_path, 'r', encoding='utf-8') as _: return _.read(), lang
python
def include_file_cb(include_path, line_ranges, symbol): lang = '' if include_path.endswith((".md", ".markdown")): lang = 'markdown' else: split = os.path.splitext(include_path) if len(split) == 2: ext = split[1].strip('.') lang = LANG_MAPPING.get(ext) or ext if line_ranges: res = [] for line_range in line_ranges: for lineno in range(line_range[0] + 1, line_range[1] + 1): line = linecache.getline(include_path, lineno) if not line: return None res.append(line) return ''.join(res), lang with io.open(include_path, 'r', encoding='utf-8') as _: return _.read(), lang
[ "def", "include_file_cb", "(", "include_path", ",", "line_ranges", ",", "symbol", ")", ":", "lang", "=", "''", "if", "include_path", ".", "endswith", "(", "(", "\".md\"", ",", "\".markdown\"", ")", ")", ":", "lang", "=", "'markdown'", "else", ":", "split", "=", "os", ".", "path", ".", "splitext", "(", "include_path", ")", "if", "len", "(", "split", ")", "==", "2", ":", "ext", "=", "split", "[", "1", "]", ".", "strip", "(", "'.'", ")", "lang", "=", "LANG_MAPPING", ".", "get", "(", "ext", ")", "or", "ext", "if", "line_ranges", ":", "res", "=", "[", "]", "for", "line_range", "in", "line_ranges", ":", "for", "lineno", "in", "range", "(", "line_range", "[", "0", "]", "+", "1", ",", "line_range", "[", "1", "]", "+", "1", ")", ":", "line", "=", "linecache", ".", "getline", "(", "include_path", ",", "lineno", ")", "if", "not", "line", ":", "return", "None", "res", ".", "append", "(", "line", ")", "return", "''", ".", "join", "(", "res", ")", ",", "lang", "with", "io", ".", "open", "(", "include_path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "_", ":", "return", "_", ".", "read", "(", ")", ",", "lang" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L82-L106
hotdoc/hotdoc
hotdoc/core/project.py
Project.persist
def persist(self): """ Banana banana """ if self.app.dry: return for proj in self.subprojects.values(): proj.persist()
python
def persist(self): if self.app.dry: return for proj in self.subprojects.values(): proj.persist()
[ "def", "persist", "(", "self", ")", ":", "if", "self", ".", "app", ".", "dry", ":", "return", "for", "proj", "in", "self", ".", "subprojects", ".", "values", "(", ")", ":", "proj", ".", "persist", "(", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L151-L160
hotdoc/hotdoc
hotdoc/core/project.py
Project.setup
def setup(self): """ Banana banana """ info('Setting up %s' % self.project_name, 'project') for extension in list(self.extensions.values()): info('Setting up %s' % extension.extension_name) extension.setup() sitemap = SitemapParser().parse(self.sitemap_path) self.tree.build(sitemap, self.extensions) info("Resolving symbols", 'resolution') self.tree.resolve_symbols(self.app.database, self.app.link_resolver)
python
def setup(self): info('Setting up %s' % self.project_name, 'project') for extension in list(self.extensions.values()): info('Setting up %s' % extension.extension_name) extension.setup() sitemap = SitemapParser().parse(self.sitemap_path) self.tree.build(sitemap, self.extensions) info("Resolving symbols", 'resolution') self.tree.resolve_symbols(self.app.database, self.app.link_resolver)
[ "def", "setup", "(", "self", ")", ":", "info", "(", "'Setting up %s'", "%", "self", ".", "project_name", ",", "'project'", ")", "for", "extension", "in", "list", "(", "self", ".", "extensions", ".", "values", "(", ")", ")", ":", "info", "(", "'Setting up %s'", "%", "extension", ".", "extension_name", ")", "extension", ".", "setup", "(", ")", "sitemap", "=", "SitemapParser", "(", ")", ".", "parse", "(", "self", ".", "sitemap_path", ")", "self", ".", "tree", ".", "build", "(", "sitemap", ",", "self", ".", "extensions", ")", "info", "(", "\"Resolving symbols\"", ",", "'resolution'", ")", "self", ".", "tree", ".", "resolve_symbols", "(", "self", ".", "app", ".", "database", ",", "self", ".", "app", ".", "link_resolver", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L175-L189
hotdoc/hotdoc
hotdoc/core/project.py
Project.format
def format(self, link_resolver, output): """ Banana banana """ if not output: return self.tree.format(link_resolver, output, self.extensions) self.formatted_signal(self)
python
def format(self, link_resolver, output): if not output: return self.tree.format(link_resolver, output, self.extensions) self.formatted_signal(self)
[ "def", "format", "(", "self", ",", "link_resolver", ",", "output", ")", ":", "if", "not", "output", ":", "return", "self", ".", "tree", ".", "format", "(", "link_resolver", ",", "output", ",", "self", ".", "extensions", ")", "self", ".", "formatted_signal", "(", "self", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L191-L199
hotdoc/hotdoc
hotdoc/core/project.py
Project.add_subproject
def add_subproject(self, fname, conf_path): """Creates and adds a new subproject.""" config = Config(conf_file=conf_path) proj = Project(self.app, dependency_map=self.dependency_map) proj.parse_name_from_config(config) proj.parse_config(config) proj.setup() self.subprojects[fname] = proj
python
def add_subproject(self, fname, conf_path): config = Config(conf_file=conf_path) proj = Project(self.app, dependency_map=self.dependency_map) proj.parse_name_from_config(config) proj.parse_config(config) proj.setup() self.subprojects[fname] = proj
[ "def", "add_subproject", "(", "self", ",", "fname", ",", "conf_path", ")", ":", "config", "=", "Config", "(", "conf_file", "=", "conf_path", ")", "proj", "=", "Project", "(", "self", ".", "app", ",", "dependency_map", "=", "self", ".", "dependency_map", ")", "proj", ".", "parse_name_from_config", "(", "config", ")", "proj", ".", "parse_config", "(", "config", ")", "proj", ".", "setup", "(", ")", "self", ".", "subprojects", "[", "fname", "]", "=", "proj" ]
Creates and adds a new subproject.
[ "Creates", "and", "adds", "a", "new", "subproject", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L226-L234
hotdoc/hotdoc
hotdoc/core/project.py
Project.parse_name_from_config
def parse_name_from_config(self, config): """ Banana banana """ self.project_name = config.get('project_name', None) if not self.project_name: error('invalid-config', 'No project name was provided') self.project_version = config.get('project_version', None) if not self.project_version: error('invalid-config', 'No project version was provided') self.sanitized_name = '%s-%s' % (re.sub(r'\W+', '-', self.project_name), self.project_version)
python
def parse_name_from_config(self, config): self.project_name = config.get('project_name', None) if not self.project_name: error('invalid-config', 'No project name was provided') self.project_version = config.get('project_version', None) if not self.project_version: error('invalid-config', 'No project version was provided') self.sanitized_name = '%s-%s' % (re.sub(r'\W+', '-', self.project_name), self.project_version)
[ "def", "parse_name_from_config", "(", "self", ",", "config", ")", ":", "self", ".", "project_name", "=", "config", ".", "get", "(", "'project_name'", ",", "None", ")", "if", "not", "self", ".", "project_name", ":", "error", "(", "'invalid-config'", ",", "'No project name was provided'", ")", "self", ".", "project_version", "=", "config", ".", "get", "(", "'project_version'", ",", "None", ")", "if", "not", "self", ".", "project_version", ":", "error", "(", "'invalid-config'", ",", "'No project version was provided'", ")", "self", ".", "sanitized_name", "=", "'%s-%s'", "%", "(", "re", ".", "sub", "(", "r'\\W+'", ",", "'-'", ",", "self", ".", "project_name", ")", ",", "self", ".", "project_version", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L247-L261
hotdoc/hotdoc
hotdoc/core/project.py
Project.parse_config
def parse_config(self, config, toplevel=False): """Parses @config setting up @self state.""" self.sitemap_path = config.get_path('sitemap') if self.sitemap_path is None: error('invalid-config', 'No sitemap was provided') self.include_paths = OrderedSet([]) index_file = config.get_index() if index_file: if not os.path.exists(index_file): error('invalid-config', 'The provided index "%s" does not exist' % index_file) self.include_paths |= OrderedSet([os.path.dirname(index_file)]) self.include_paths |= OrderedSet(config.get_paths('include_paths')) self.is_toplevel = toplevel self.tree = Tree(self, self.app) self.__create_extensions() for extension in list(self.extensions.values()): if toplevel: extension.parse_toplevel_config(config) extension.parse_config(config) self.extra_asset_folders = OrderedSet(config.get_paths('extra_assets'))
python
def parse_config(self, config, toplevel=False): self.sitemap_path = config.get_path('sitemap') if self.sitemap_path is None: error('invalid-config', 'No sitemap was provided') self.include_paths = OrderedSet([]) index_file = config.get_index() if index_file: if not os.path.exists(index_file): error('invalid-config', 'The provided index "%s" does not exist' % index_file) self.include_paths |= OrderedSet([os.path.dirname(index_file)]) self.include_paths |= OrderedSet(config.get_paths('include_paths')) self.is_toplevel = toplevel self.tree = Tree(self, self.app) self.__create_extensions() for extension in list(self.extensions.values()): if toplevel: extension.parse_toplevel_config(config) extension.parse_config(config) self.extra_asset_folders = OrderedSet(config.get_paths('extra_assets'))
[ "def", "parse_config", "(", "self", ",", "config", ",", "toplevel", "=", "False", ")", ":", "self", ".", "sitemap_path", "=", "config", ".", "get_path", "(", "'sitemap'", ")", "if", "self", ".", "sitemap_path", "is", "None", ":", "error", "(", "'invalid-config'", ",", "'No sitemap was provided'", ")", "self", ".", "include_paths", "=", "OrderedSet", "(", "[", "]", ")", "index_file", "=", "config", ".", "get_index", "(", ")", "if", "index_file", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "index_file", ")", ":", "error", "(", "'invalid-config'", ",", "'The provided index \"%s\" does not exist'", "%", "index_file", ")", "self", ".", "include_paths", "|=", "OrderedSet", "(", "[", "os", ".", "path", ".", "dirname", "(", "index_file", ")", "]", ")", "self", ".", "include_paths", "|=", "OrderedSet", "(", "config", ".", "get_paths", "(", "'include_paths'", ")", ")", "self", ".", "is_toplevel", "=", "toplevel", "self", ".", "tree", "=", "Tree", "(", "self", ",", "self", ".", "app", ")", "self", ".", "__create_extensions", "(", ")", "for", "extension", "in", "list", "(", "self", ".", "extensions", ".", "values", "(", ")", ")", ":", "if", "toplevel", ":", "extension", ".", "parse_toplevel_config", "(", "config", ")", "extension", ".", "parse_config", "(", "config", ")", "self", ".", "extra_asset_folders", "=", "OrderedSet", "(", "config", ".", "get_paths", "(", "'extra_assets'", ")", ")" ]
Parses @config setting up @self state.
[ "Parses" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L264-L295
hotdoc/hotdoc
hotdoc/core/project.py
Project.__get_formatter
def __get_formatter(self, extension_name): """ Banana banana """ ext = self.extensions.get(extension_name) if ext: return ext.formatter return None
python
def __get_formatter(self, extension_name): ext = self.extensions.get(extension_name) if ext: return ext.formatter return None
[ "def", "__get_formatter", "(", "self", ",", "extension_name", ")", ":", "ext", "=", "self", ".", "extensions", ".", "get", "(", "extension_name", ")", "if", "ext", ":", "return", "ext", ".", "formatter", "return", "None" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L304-L311
hotdoc/hotdoc
hotdoc/core/project.py
Project.write_out
def write_out(self, output): """Banana banana """ if not output: return ext = self.extensions.get(self.tree.root.extension_name) self.tree.write_out(output) self.write_extra_assets(output) ext.formatter.copy_assets(os.path.join(output, 'html', 'assets')) # Just in case the sitemap root isn't named index ext_folder = ext.formatter.get_output_folder(self.tree.root) ref, _ = self.tree.root.link.get_link(self.app.link_resolver) index_path = os.path.join(ext_folder, ref) default_index_path = os.path.join(output, 'html', 'index.html') if not os.path.exists(default_index_path): with open(default_index_path, 'w', encoding='utf8') as _: _.write('<meta http-equiv="refresh" content="0; url=%s"/>' % index_path) self.written_out_signal(self)
python
def write_out(self, output): if not output: return ext = self.extensions.get(self.tree.root.extension_name) self.tree.write_out(output) self.write_extra_assets(output) ext.formatter.copy_assets(os.path.join(output, 'html', 'assets')) ext_folder = ext.formatter.get_output_folder(self.tree.root) ref, _ = self.tree.root.link.get_link(self.app.link_resolver) index_path = os.path.join(ext_folder, ref) default_index_path = os.path.join(output, 'html', 'index.html') if not os.path.exists(default_index_path): with open(default_index_path, 'w', encoding='utf8') as _: _.write('<meta http-equiv="refresh" content="0; url=%s"/>' % index_path) self.written_out_signal(self)
[ "def", "write_out", "(", "self", ",", "output", ")", ":", "if", "not", "output", ":", "return", "ext", "=", "self", ".", "extensions", ".", "get", "(", "self", ".", "tree", ".", "root", ".", "extension_name", ")", "self", ".", "tree", ".", "write_out", "(", "output", ")", "self", ".", "write_extra_assets", "(", "output", ")", "ext", ".", "formatter", ".", "copy_assets", "(", "os", ".", "path", ".", "join", "(", "output", ",", "'html'", ",", "'assets'", ")", ")", "# Just in case the sitemap root isn't named index", "ext_folder", "=", "ext", ".", "formatter", ".", "get_output_folder", "(", "self", ".", "tree", ".", "root", ")", "ref", ",", "_", "=", "self", ".", "tree", ".", "root", ".", "link", ".", "get_link", "(", "self", ".", "app", ".", "link_resolver", ")", "index_path", "=", "os", ".", "path", ".", "join", "(", "ext_folder", ",", "ref", ")", "default_index_path", "=", "os", ".", "path", ".", "join", "(", "output", ",", "'html'", ",", "'index.html'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "default_index_path", ")", ":", "with", "open", "(", "default_index_path", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "as", "_", ":", "_", ".", "write", "(", "'<meta http-equiv=\"refresh\" content=\"0; url=%s\"/>'", "%", "index_path", ")", "self", ".", "written_out_signal", "(", "self", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/project.py#L324-L349
hotdoc/hotdoc
hotdoc/core/tree.py
_no_duplicates_constructor
def _no_duplicates_constructor(loader, node, deep=False): """Check for duplicate keys.""" mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: raise ConstructorError("while constructing a mapping", node.start_mark, "found duplicate key (%s)" % key, key_node.start_mark) mapping[key] = value return loader.construct_mapping(node, deep)
python
def _no_duplicates_constructor(loader, node, deep=False): mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: raise ConstructorError("while constructing a mapping", node.start_mark, "found duplicate key (%s)" % key, key_node.start_mark) mapping[key] = value return loader.construct_mapping(node, deep)
[ "def", "_no_duplicates_constructor", "(", "loader", ",", "node", ",", "deep", "=", "False", ")", ":", "mapping", "=", "{", "}", "for", "key_node", ",", "value_node", "in", "node", ".", "value", ":", "key", "=", "loader", ".", "construct_object", "(", "key_node", ",", "deep", "=", "deep", ")", "value", "=", "loader", ".", "construct_object", "(", "value_node", ",", "deep", "=", "deep", ")", "if", "key", "in", "mapping", ":", "raise", "ConstructorError", "(", "\"while constructing a mapping\"", ",", "node", ".", "start_mark", ",", "\"found duplicate key (%s)\"", "%", "key", ",", "key_node", ".", "start_mark", ")", "mapping", "[", "key", "]", "=", "value", "return", "loader", ".", "construct_mapping", "(", "node", ",", "deep", ")" ]
Check for duplicate keys.
[ "Check", "for", "duplicate", "keys", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L49-L63
hotdoc/hotdoc
hotdoc/core/tree.py
Page.resolve_symbols
def resolve_symbols(self, tree, database, link_resolver): """ When this method is called, the page's symbol names are queried from `database`, and added to lists of actual symbols, sorted by symbol class. """ self.typed_symbols = self.__get_empty_typed_symbols() all_syms = OrderedSet() for sym_name in self.symbol_names: sym = database.get_symbol(sym_name) self.__query_extra_symbols( sym, all_syms, tree, link_resolver, database) if tree.project.is_toplevel: page_path = self.link.ref else: page_path = self.project_name + '/' + self.link.ref if self.meta.get("auto-sort", True): all_syms = sorted(all_syms, key=lambda x: x.unique_name) for sym in all_syms: sym.update_children_comments() self.__resolve_symbol(sym, link_resolver, page_path) self.symbol_names.add(sym.unique_name) # Always put symbols with no parent at the end no_parent_syms = self.by_parent_symbols.pop(None, None) if no_parent_syms: self.by_parent_symbols[None] = no_parent_syms for sym_type in [ClassSymbol, AliasSymbol, InterfaceSymbol, StructSymbol]: syms = self.typed_symbols[sym_type].symbols if not syms: continue if self.title is None: self.title = syms[0].display_name if self.comment is None: self.comment = Comment(name=self.name) self.comment.short_description = syms[ 0].comment.short_description self.comment.title = syms[0].comment.title break
python
def resolve_symbols(self, tree, database, link_resolver): self.typed_symbols = self.__get_empty_typed_symbols() all_syms = OrderedSet() for sym_name in self.symbol_names: sym = database.get_symbol(sym_name) self.__query_extra_symbols( sym, all_syms, tree, link_resolver, database) if tree.project.is_toplevel: page_path = self.link.ref else: page_path = self.project_name + '/' + self.link.ref if self.meta.get("auto-sort", True): all_syms = sorted(all_syms, key=lambda x: x.unique_name) for sym in all_syms: sym.update_children_comments() self.__resolve_symbol(sym, link_resolver, page_path) self.symbol_names.add(sym.unique_name) no_parent_syms = self.by_parent_symbols.pop(None, None) if no_parent_syms: self.by_parent_symbols[None] = no_parent_syms for sym_type in [ClassSymbol, AliasSymbol, InterfaceSymbol, StructSymbol]: syms = self.typed_symbols[sym_type].symbols if not syms: continue if self.title is None: self.title = syms[0].display_name if self.comment is None: self.comment = Comment(name=self.name) self.comment.short_description = syms[ 0].comment.short_description self.comment.title = syms[0].comment.title break
[ "def", "resolve_symbols", "(", "self", ",", "tree", ",", "database", ",", "link_resolver", ")", ":", "self", ".", "typed_symbols", "=", "self", ".", "__get_empty_typed_symbols", "(", ")", "all_syms", "=", "OrderedSet", "(", ")", "for", "sym_name", "in", "self", ".", "symbol_names", ":", "sym", "=", "database", ".", "get_symbol", "(", "sym_name", ")", "self", ".", "__query_extra_symbols", "(", "sym", ",", "all_syms", ",", "tree", ",", "link_resolver", ",", "database", ")", "if", "tree", ".", "project", ".", "is_toplevel", ":", "page_path", "=", "self", ".", "link", ".", "ref", "else", ":", "page_path", "=", "self", ".", "project_name", "+", "'/'", "+", "self", ".", "link", ".", "ref", "if", "self", ".", "meta", ".", "get", "(", "\"auto-sort\"", ",", "True", ")", ":", "all_syms", "=", "sorted", "(", "all_syms", ",", "key", "=", "lambda", "x", ":", "x", ".", "unique_name", ")", "for", "sym", "in", "all_syms", ":", "sym", ".", "update_children_comments", "(", ")", "self", ".", "__resolve_symbol", "(", "sym", ",", "link_resolver", ",", "page_path", ")", "self", ".", "symbol_names", ".", "add", "(", "sym", ".", "unique_name", ")", "# Always put symbols with no parent at the end", "no_parent_syms", "=", "self", ".", "by_parent_symbols", ".", "pop", "(", "None", ",", "None", ")", "if", "no_parent_syms", ":", "self", ".", "by_parent_symbols", "[", "None", "]", "=", "no_parent_syms", "for", "sym_type", "in", "[", "ClassSymbol", ",", "AliasSymbol", ",", "InterfaceSymbol", ",", "StructSymbol", "]", ":", "syms", "=", "self", ".", "typed_symbols", "[", "sym_type", "]", ".", "symbols", "if", "not", "syms", ":", "continue", "if", "self", ".", "title", "is", "None", ":", "self", ".", "title", "=", "syms", "[", "0", "]", ".", "display_name", "if", "self", ".", "comment", "is", "None", ":", "self", ".", "comment", "=", "Comment", "(", "name", "=", "self", ".", "name", ")", "self", ".", "comment", ".", "short_description", "=", "syms", "[", "0", "]", ".", "comment", ".", "short_description", "self", ".", "comment", ".", "title", "=", "syms", "[", "0", "]", ".", "comment", ".", "title", "break" ]
When this method is called, the page's symbol names are queried from `database`, and added to lists of actual symbols, sorted by symbol class.
[ "When", "this", "method", "is", "called", "the", "page", "s", "symbol", "names", "are", "queried", "from", "database", "and", "added", "to", "lists", "of", "actual", "symbols", "sorted", "by", "symbol", "class", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L196-L240
hotdoc/hotdoc
hotdoc/core/tree.py
Page.format
def format(self, formatter, link_resolver, output): """ Banana banana """ if not self.title and self.name: title = os.path.splitext(self.name)[0] self.title = os.path.basename(title).replace('-', ' ') self.formatted_contents = u'' self.build_path = os.path.join(formatter.get_output_folder(self), self.link.ref) if self.ast: out, diags = cmark.ast_to_html(self.ast, link_resolver) for diag in diags: warn( diag.code, message=diag.message, filename=self.source_file or self.name) self.formatted_contents += out if not self.formatted_contents: self.__format_page_comment(formatter, link_resolver) self.output_attrs = defaultdict(lambda: defaultdict(dict)) formatter.prepare_page_attributes(self) self.__format_symbols(formatter, link_resolver) self.detailed_description =\ formatter.format_page(self)[0] if output: formatter.cache_page(self)
python
def format(self, formatter, link_resolver, output): if not self.title and self.name: title = os.path.splitext(self.name)[0] self.title = os.path.basename(title).replace('-', ' ') self.formatted_contents = u'' self.build_path = os.path.join(formatter.get_output_folder(self), self.link.ref) if self.ast: out, diags = cmark.ast_to_html(self.ast, link_resolver) for diag in diags: warn( diag.code, message=diag.message, filename=self.source_file or self.name) self.formatted_contents += out if not self.formatted_contents: self.__format_page_comment(formatter, link_resolver) self.output_attrs = defaultdict(lambda: defaultdict(dict)) formatter.prepare_page_attributes(self) self.__format_symbols(formatter, link_resolver) self.detailed_description =\ formatter.format_page(self)[0] if output: formatter.cache_page(self)
[ "def", "format", "(", "self", ",", "formatter", ",", "link_resolver", ",", "output", ")", ":", "if", "not", "self", ".", "title", "and", "self", ".", "name", ":", "title", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "name", ")", "[", "0", "]", "self", ".", "title", "=", "os", ".", "path", ".", "basename", "(", "title", ")", ".", "replace", "(", "'-'", ",", "' '", ")", "self", ".", "formatted_contents", "=", "u''", "self", ".", "build_path", "=", "os", ".", "path", ".", "join", "(", "formatter", ".", "get_output_folder", "(", "self", ")", ",", "self", ".", "link", ".", "ref", ")", "if", "self", ".", "ast", ":", "out", ",", "diags", "=", "cmark", ".", "ast_to_html", "(", "self", ".", "ast", ",", "link_resolver", ")", "for", "diag", "in", "diags", ":", "warn", "(", "diag", ".", "code", ",", "message", "=", "diag", ".", "message", ",", "filename", "=", "self", ".", "source_file", "or", "self", ".", "name", ")", "self", ".", "formatted_contents", "+=", "out", "if", "not", "self", ".", "formatted_contents", ":", "self", ".", "__format_page_comment", "(", "formatter", ",", "link_resolver", ")", "self", ".", "output_attrs", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "dict", ")", ")", "formatter", ".", "prepare_page_attributes", "(", "self", ")", "self", ".", "__format_symbols", "(", "formatter", ",", "link_resolver", ")", "self", ".", "detailed_description", "=", "formatter", ".", "format_page", "(", "self", ")", "[", "0", "]", "if", "output", ":", "formatter", ".", "cache_page", "(", "self", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L269-L303
hotdoc/hotdoc
hotdoc/core/tree.py
Tree.walk
def walk(self, parent=None): """Generator that yields pages in infix order Args: parent: hotdoc.core.tree.Page, optional, the page to start traversal from. If None, defaults to the root of the tree. Yields: hotdoc.core.tree.Page: the next page """ if parent is None: yield self.root parent = self.root for cpage_name in parent.subpages: cpage = self.__all_pages[cpage_name] yield cpage for page in self.walk(parent=cpage): yield page
python
def walk(self, parent=None): if parent is None: yield self.root parent = self.root for cpage_name in parent.subpages: cpage = self.__all_pages[cpage_name] yield cpage for page in self.walk(parent=cpage): yield page
[ "def", "walk", "(", "self", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "None", ":", "yield", "self", ".", "root", "parent", "=", "self", ".", "root", "for", "cpage_name", "in", "parent", ".", "subpages", ":", "cpage", "=", "self", ".", "__all_pages", "[", "cpage_name", "]", "yield", "cpage", "for", "page", "in", "self", ".", "walk", "(", "parent", "=", "cpage", ")", ":", "yield", "page" ]
Generator that yields pages in infix order Args: parent: hotdoc.core.tree.Page, optional, the page to start traversal from. If None, defaults to the root of the tree. Yields: hotdoc.core.tree.Page: the next page
[ "Generator", "that", "yields", "pages", "in", "infix", "order" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L514-L532
hotdoc/hotdoc
hotdoc/core/tree.py
Tree.page_from_raw_text
def page_from_raw_text(self, source_file, contents, extension_name): """ Banana banana """ raw_contents = contents meta = {} if contents.startswith('---\n'): split = contents.split('\n...\n', 1) if len(split) == 2: contents = split[1] try: blocks = yaml.load_all(split[0], Loader=yaml.FullLoader) for block in blocks: if block: meta.update(block) except ConstructorError as exception: warn('invalid-page-metadata', '%s: Invalid metadata: \n%s' % (source_file, str(exception))) output_path = os.path.dirname(os.path.relpath( source_file, next(iter(self.project.include_paths)))) ast = cmark.hotdoc_to_ast(contents, self) return Page(source_file, False, self.project.sanitized_name, extension_name, source_file=source_file, ast=ast, meta=meta, raw_contents=raw_contents, output_path=output_path)
python
def page_from_raw_text(self, source_file, contents, extension_name): raw_contents = contents meta = {} if contents.startswith('---\n'): split = contents.split('\n...\n', 1) if len(split) == 2: contents = split[1] try: blocks = yaml.load_all(split[0], Loader=yaml.FullLoader) for block in blocks: if block: meta.update(block) except ConstructorError as exception: warn('invalid-page-metadata', '%s: Invalid metadata: \n%s' % (source_file, str(exception))) output_path = os.path.dirname(os.path.relpath( source_file, next(iter(self.project.include_paths)))) ast = cmark.hotdoc_to_ast(contents, self) return Page(source_file, False, self.project.sanitized_name, extension_name, source_file=source_file, ast=ast, meta=meta, raw_contents=raw_contents, output_path=output_path)
[ "def", "page_from_raw_text", "(", "self", ",", "source_file", ",", "contents", ",", "extension_name", ")", ":", "raw_contents", "=", "contents", "meta", "=", "{", "}", "if", "contents", ".", "startswith", "(", "'---\\n'", ")", ":", "split", "=", "contents", ".", "split", "(", "'\\n...\\n'", ",", "1", ")", "if", "len", "(", "split", ")", "==", "2", ":", "contents", "=", "split", "[", "1", "]", "try", ":", "blocks", "=", "yaml", ".", "load_all", "(", "split", "[", "0", "]", ",", "Loader", "=", "yaml", ".", "FullLoader", ")", "for", "block", "in", "blocks", ":", "if", "block", ":", "meta", ".", "update", "(", "block", ")", "except", "ConstructorError", "as", "exception", ":", "warn", "(", "'invalid-page-metadata'", ",", "'%s: Invalid metadata: \\n%s'", "%", "(", "source_file", ",", "str", "(", "exception", ")", ")", ")", "output_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "relpath", "(", "source_file", ",", "next", "(", "iter", "(", "self", ".", "project", ".", "include_paths", ")", ")", ")", ")", "ast", "=", "cmark", ".", "hotdoc_to_ast", "(", "contents", ",", "self", ")", "return", "Page", "(", "source_file", ",", "False", ",", "self", ".", "project", ".", "sanitized_name", ",", "extension_name", ",", "source_file", "=", "source_file", ",", "ast", "=", "ast", ",", "meta", "=", "meta", ",", "raw_contents", "=", "raw_contents", ",", "output_path", "=", "output_path", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L534-L561
hotdoc/hotdoc
hotdoc/core/tree.py
Tree.resolve_symbols
def resolve_symbols(self, database, link_resolver, page=None): """Will call resolve_symbols on all the stale subpages of the tree. Args: page: hotdoc.core.tree.Page, the page to resolve symbols in, will recurse on potential subpages. """ page = page or self.root if page.ast is None and not page.generated: with io.open(page.source_file, 'r', encoding='utf-8') as _: page.ast = cmark.hotdoc_to_ast(_.read(), self) page.resolve_symbols(self, database, link_resolver) self.__update_dep_map(page, page.symbols) for pagename in page.subpages: cpage = self.__all_pages[pagename] self.resolve_symbols(database, link_resolver, page=cpage)
python
def resolve_symbols(self, database, link_resolver, page=None): page = page or self.root if page.ast is None and not page.generated: with io.open(page.source_file, 'r', encoding='utf-8') as _: page.ast = cmark.hotdoc_to_ast(_.read(), self) page.resolve_symbols(self, database, link_resolver) self.__update_dep_map(page, page.symbols) for pagename in page.subpages: cpage = self.__all_pages[pagename] self.resolve_symbols(database, link_resolver, page=cpage)
[ "def", "resolve_symbols", "(", "self", ",", "database", ",", "link_resolver", ",", "page", "=", "None", ")", ":", "page", "=", "page", "or", "self", ".", "root", "if", "page", ".", "ast", "is", "None", "and", "not", "page", ".", "generated", ":", "with", "io", ".", "open", "(", "page", ".", "source_file", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "_", ":", "page", ".", "ast", "=", "cmark", ".", "hotdoc_to_ast", "(", "_", ".", "read", "(", ")", ",", "self", ")", "page", ".", "resolve_symbols", "(", "self", ",", "database", ",", "link_resolver", ")", "self", ".", "__update_dep_map", "(", "page", ",", "page", ".", "symbols", ")", "for", "pagename", "in", "page", ".", "subpages", ":", "cpage", "=", "self", ".", "__all_pages", "[", "pagename", "]", "self", ".", "resolve_symbols", "(", "database", ",", "link_resolver", ",", "page", "=", "cpage", ")" ]
Will call resolve_symbols on all the stale subpages of the tree. Args: page: hotdoc.core.tree.Page, the page to resolve symbols in, will recurse on potential subpages.
[ "Will", "call", "resolve_symbols", "on", "all", "the", "stale", "subpages", "of", "the", "tree", ".", "Args", ":", "page", ":", "hotdoc", ".", "core", ".", "tree", ".", "Page", "the", "page", "to", "resolve", "symbols", "in", "will", "recurse", "on", "potential", "subpages", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L577-L595
hotdoc/hotdoc
hotdoc/core/tree.py
Tree.format_page
def format_page(self, page, link_resolver, output, extensions): """ Banana banana """ info('formatting %s' % page.source_file, 'formatting') extension = extensions[page.extension_name] extension.format_page(page, link_resolver, output)
python
def format_page(self, page, link_resolver, output, extensions): info('formatting %s' % page.source_file, 'formatting') extension = extensions[page.extension_name] extension.format_page(page, link_resolver, output)
[ "def", "format_page", "(", "self", ",", "page", ",", "link_resolver", ",", "output", ",", "extensions", ")", ":", "info", "(", "'formatting %s'", "%", "page", ".", "source_file", ",", "'formatting'", ")", "extension", "=", "extensions", "[", "page", ".", "extension_name", "]", "extension", ".", "format_page", "(", "page", ",", "link_resolver", ",", "output", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L597-L603
hotdoc/hotdoc
hotdoc/core/tree.py
Tree.format
def format(self, link_resolver, output, extensions): """Banana banana """ info('Formatting documentation tree', 'formatting') self.__setup_folder(output) link_resolver.get_link_signal.connect(self.__get_link_cb) # Page.formatting_signal.connect(self.__formatting_page_cb) # Link.resolving_link_signal.connect(self.__link_referenced_cb) self.__extensions = extensions for page in self.walk(): self.format_page(page, link_resolver, output, extensions) self.__extensions = None link_resolver.get_link_signal.disconnect(self.__get_link_cb)
python
def format(self, link_resolver, output, extensions): info('Formatting documentation tree', 'formatting') self.__setup_folder(output) link_resolver.get_link_signal.connect(self.__get_link_cb) self.__extensions = extensions for page in self.walk(): self.format_page(page, link_resolver, output, extensions) self.__extensions = None link_resolver.get_link_signal.disconnect(self.__get_link_cb)
[ "def", "format", "(", "self", ",", "link_resolver", ",", "output", ",", "extensions", ")", ":", "info", "(", "'Formatting documentation tree'", ",", "'formatting'", ")", "self", ".", "__setup_folder", "(", "output", ")", "link_resolver", ".", "get_link_signal", ".", "connect", "(", "self", ".", "__get_link_cb", ")", "# Page.formatting_signal.connect(self.__formatting_page_cb)", "# Link.resolving_link_signal.connect(self.__link_referenced_cb)", "self", ".", "__extensions", "=", "extensions", "for", "page", "in", "self", ".", "walk", "(", ")", ":", "self", ".", "format_page", "(", "page", ",", "link_resolver", ",", "output", ",", "extensions", ")", "self", ".", "__extensions", "=", "None", "link_resolver", ".", "get_link_signal", ".", "disconnect", "(", "self", ".", "__get_link_cb", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L605-L621
hotdoc/hotdoc
hotdoc/core/tree.py
Tree.write_out
def write_out(self, output): """Banana banana """ for page in self.walk(): ext = self.project.extensions[page.extension_name] ext.write_out_page(output, page)
python
def write_out(self, output): for page in self.walk(): ext = self.project.extensions[page.extension_name] ext.write_out_page(output, page)
[ "def", "write_out", "(", "self", ",", "output", ")", ":", "for", "page", "in", "self", ".", "walk", "(", ")", ":", "ext", "=", "self", ".", "project", ".", "extensions", "[", "page", ".", "extension_name", "]", "ext", ".", "write_out_page", "(", "output", ",", "page", ")" ]
Banana banana
[ "Banana", "banana" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L623-L628
hotdoc/hotdoc
hotdoc/extensions/__init__.py
get_extension_classes
def get_extension_classes(): """ Hotdoc's setuptools entry point """ res = [SyntaxHighlightingExtension, SearchExtension, TagExtension, DevhelpExtension, LicenseExtension, GitUploadExtension, EditOnGitHubExtension] if sys.version_info[1] >= 5: res += [DBusExtension] try: from hotdoc.extensions.c.c_extension import CExtension res += [CExtension] except ImportError: pass try: from hotdoc.extensions.gi.gi_extension import GIExtension res += [GIExtension] except ImportError: pass return res
python
def get_extension_classes(): res = [SyntaxHighlightingExtension, SearchExtension, TagExtension, DevhelpExtension, LicenseExtension, GitUploadExtension, EditOnGitHubExtension] if sys.version_info[1] >= 5: res += [DBusExtension] try: from hotdoc.extensions.c.c_extension import CExtension res += [CExtension] except ImportError: pass try: from hotdoc.extensions.gi.gi_extension import GIExtension res += [GIExtension] except ImportError: pass return res
[ "def", "get_extension_classes", "(", ")", ":", "res", "=", "[", "SyntaxHighlightingExtension", ",", "SearchExtension", ",", "TagExtension", ",", "DevhelpExtension", ",", "LicenseExtension", ",", "GitUploadExtension", ",", "EditOnGitHubExtension", "]", "if", "sys", ".", "version_info", "[", "1", "]", ">=", "5", ":", "res", "+=", "[", "DBusExtension", "]", "try", ":", "from", "hotdoc", ".", "extensions", ".", "c", ".", "c_extension", "import", "CExtension", "res", "+=", "[", "CExtension", "]", "except", "ImportError", ":", "pass", "try", ":", "from", "hotdoc", ".", "extensions", ".", "gi", ".", "gi_extension", "import", "GIExtension", "res", "+=", "[", "GIExtension", "]", "except", "ImportError", ":", "pass", "return", "res" ]
Hotdoc's setuptools entry point
[ "Hotdoc", "s", "setuptools", "entry", "point" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/__init__.py#L40-L63
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
register_functions
def register_functions(lib, ignore_errors): """Register function prototypes with a libclang library instance. This must be called as part of library instantiation so Python knows how to call out to the shared library. """ def register(item): return register_function(lib, item, ignore_errors) for f in functionList: register(f)
python
def register_functions(lib, ignore_errors): def register(item): return register_function(lib, item, ignore_errors) for f in functionList: register(f)
[ "def", "register_functions", "(", "lib", ",", "ignore_errors", ")", ":", "def", "register", "(", "item", ")", ":", "return", "register_function", "(", "lib", ",", "item", ",", "ignore_errors", ")", "for", "f", "in", "functionList", ":", "register", "(", "f", ")" ]
Register function prototypes with a libclang library instance. This must be called as part of library instantiation so Python knows how to call out to the shared library.
[ "Register", "function", "prototypes", "with", "a", "libclang", "library", "instance", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L3814-L3825
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
SourceLocation.from_position
def from_position(tu, file, line, column): """ Retrieve the source location associated with a given file/line/column in a particular translation unit. """ return conf.lib.clang_getLocation(tu, file, line, column)
python
def from_position(tu, file, line, column): return conf.lib.clang_getLocation(tu, file, line, column)
[ "def", "from_position", "(", "tu", ",", "file", ",", "line", ",", "column", ")", ":", "return", "conf", ".", "lib", ".", "clang_getLocation", "(", "tu", ",", "file", ",", "line", ",", "column", ")" ]
Retrieve the source location associated with a given file/line/column in a particular translation unit.
[ "Retrieve", "the", "source", "location", "associated", "with", "a", "given", "file", "/", "line", "/", "column", "in", "a", "particular", "translation", "unit", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L209-L214
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
SourceLocation.from_offset
def from_offset(tu, file, offset): """Retrieve a SourceLocation from a given character offset. tu -- TranslationUnit file belongs to file -- File instance to obtain offset from offset -- Integer character offset within file """ return conf.lib.clang_getLocationForOffset(tu, file, offset)
python
def from_offset(tu, file, offset): return conf.lib.clang_getLocationForOffset(tu, file, offset)
[ "def", "from_offset", "(", "tu", ",", "file", ",", "offset", ")", ":", "return", "conf", ".", "lib", ".", "clang_getLocationForOffset", "(", "tu", ",", "file", ",", "offset", ")" ]
Retrieve a SourceLocation from a given character offset. tu -- TranslationUnit file belongs to file -- File instance to obtain offset from offset -- Integer character offset within file
[ "Retrieve", "a", "SourceLocation", "from", "a", "given", "character", "offset", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L217-L224
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Diagnostic.disable_option
def disable_option(self): """The command-line option that disables this diagnostic.""" disable = _CXString() conf.lib.clang_getDiagnosticOption(self, byref(disable)) return str(conf.lib.clang_getCString(disable))
python
def disable_option(self): disable = _CXString() conf.lib.clang_getDiagnosticOption(self, byref(disable)) return str(conf.lib.clang_getCString(disable))
[ "def", "disable_option", "(", "self", ")", ":", "disable", "=", "_CXString", "(", ")", "conf", ".", "lib", ".", "clang_getDiagnosticOption", "(", "self", ",", "byref", "(", "disable", ")", ")", "return", "str", "(", "conf", ".", "lib", ".", "clang_getCString", "(", "disable", ")", ")" ]
The command-line option that disables this diagnostic.
[ "The", "command", "-", "line", "option", "that", "disables", "this", "diagnostic", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L432-L437
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Diagnostic.format
def format(self, options=None): """ Format this diagnostic for display. The options argument takes Diagnostic.Display* flags, which can be combined using bitwise OR. If the options argument is not provided, the default display options will be used. """ if options is None: options = conf.lib.clang_defaultDiagnosticDisplayOptions() if options & ~Diagnostic._FormatOptionsMask: raise ValueError('Invalid format options') formatted = conf.lib.clang_formatDiagnostic(self, options) return str(conf.lib.clang_getCString(formatted))
python
def format(self, options=None): if options is None: options = conf.lib.clang_defaultDiagnosticDisplayOptions() if options & ~Diagnostic._FormatOptionsMask: raise ValueError('Invalid format options') formatted = conf.lib.clang_formatDiagnostic(self, options) return str(conf.lib.clang_getCString(formatted))
[ "def", "format", "(", "self", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "conf", ".", "lib", ".", "clang_defaultDiagnosticDisplayOptions", "(", ")", "if", "options", "&", "~", "Diagnostic", ".", "_FormatOptionsMask", ":", "raise", "ValueError", "(", "'Invalid format options'", ")", "formatted", "=", "conf", ".", "lib", ".", "clang_formatDiagnostic", "(", "self", ",", "options", ")", "return", "str", "(", "conf", ".", "lib", ".", "clang_getCString", "(", "formatted", ")", ")" ]
Format this diagnostic for display. The options argument takes Diagnostic.Display* flags, which can be combined using bitwise OR. If the options argument is not provided, the default display options will be used.
[ "Format", "this", "diagnostic", "for", "display", ".", "The", "options", "argument", "takes", "Diagnostic", ".", "Display", "*", "flags", "which", "can", "be", "combined", "using", "bitwise", "OR", ".", "If", "the", "options", "argument", "is", "not", "provided", "the", "default", "display", "options", "will", "be", "used", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L439-L451
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TokenGroup.get_tokens
def get_tokens(tu, extent): """Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place. """ tokens_memory = POINTER(Token)() tokens_count = c_uint() conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), byref(tokens_count)) count = int(tokens_count.value) # If we get no tokens, no memory was allocated. Be sure not to return # anything and potentially call a destructor on nothing. if count < 1: return tokens_array = cast(tokens_memory, POINTER(Token * count)).contents token_group = TokenGroup(tu, tokens_memory, tokens_count) for i in xrange(0, count): token = Token() token.int_data = tokens_array[i].int_data token.ptr_data = tokens_array[i].ptr_data token._tu = tu token._group = token_group yield token
python
def get_tokens(tu, extent): tokens_memory = POINTER(Token)() tokens_count = c_uint() conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), byref(tokens_count)) count = int(tokens_count.value) if count < 1: return tokens_array = cast(tokens_memory, POINTER(Token * count)).contents token_group = TokenGroup(tu, tokens_memory, tokens_count) for i in xrange(0, count): token = Token() token.int_data = tokens_array[i].int_data token.ptr_data = tokens_array[i].ptr_data token._tu = tu token._group = token_group yield token
[ "def", "get_tokens", "(", "tu", ",", "extent", ")", ":", "tokens_memory", "=", "POINTER", "(", "Token", ")", "(", ")", "tokens_count", "=", "c_uint", "(", ")", "conf", ".", "lib", ".", "clang_tokenize", "(", "tu", ",", "extent", ",", "byref", "(", "tokens_memory", ")", ",", "byref", "(", "tokens_count", ")", ")", "count", "=", "int", "(", "tokens_count", ".", "value", ")", "# If we get no tokens, no memory was allocated. Be sure not to return", "# anything and potentially call a destructor on nothing.", "if", "count", "<", "1", ":", "return", "tokens_array", "=", "cast", "(", "tokens_memory", ",", "POINTER", "(", "Token", "*", "count", ")", ")", ".", "contents", "token_group", "=", "TokenGroup", "(", "tu", ",", "tokens_memory", ",", "tokens_count", ")", "for", "i", "in", "xrange", "(", "0", ",", "count", ")", ":", "token", "=", "Token", "(", ")", "token", ".", "int_data", "=", "tokens_array", "[", "i", "]", ".", "int_data", "token", ".", "ptr_data", "=", "tokens_array", "[", "i", "]", ".", "ptr_data", "token", ".", "_tu", "=", "tu", "token", ".", "_group", "=", "token_group", "yield", "token" ]
Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place.
[ "Helper", "method", "to", "return", "all", "tokens", "in", "an", "extent", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L500-L530
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TokenKind.from_value
def from_value(value): """Obtain a registered TokenKind instance from its value.""" result = TokenKind._value_map.get(value, None) if result is None: raise ValueError('Unknown TokenKind: %d' % value) return result
python
def from_value(value): result = TokenKind._value_map.get(value, None) if result is None: raise ValueError('Unknown TokenKind: %d' % value) return result
[ "def", "from_value", "(", "value", ")", ":", "result", "=", "TokenKind", ".", "_value_map", ".", "get", "(", "value", ",", "None", ")", "if", "result", "is", "None", ":", "raise", "ValueError", "(", "'Unknown TokenKind: %d'", "%", "value", ")", "return", "result" ]
Obtain a registered TokenKind instance from its value.
[ "Obtain", "a", "registered", "TokenKind", "instance", "from", "its", "value", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L546-L553
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TokenKind.register
def register(value, name): """Register a new TokenKind enumeration. This should only be called at module load time by code within this package. """ if value in TokenKind._value_map: raise ValueError('TokenKind already registered: %d' % value) kind = TokenKind(value, name) TokenKind._value_map[value] = kind setattr(TokenKind, name, kind)
python
def register(value, name): if value in TokenKind._value_map: raise ValueError('TokenKind already registered: %d' % value) kind = TokenKind(value, name) TokenKind._value_map[value] = kind setattr(TokenKind, name, kind)
[ "def", "register", "(", "value", ",", "name", ")", ":", "if", "value", "in", "TokenKind", ".", "_value_map", ":", "raise", "ValueError", "(", "'TokenKind already registered: %d'", "%", "value", ")", "kind", "=", "TokenKind", "(", "value", ",", "name", ")", "TokenKind", ".", "_value_map", "[", "value", "]", "=", "kind", "setattr", "(", "TokenKind", ",", "name", ",", "kind", ")" ]
Register a new TokenKind enumeration. This should only be called at module load time by code within this package.
[ "Register", "a", "new", "TokenKind", "enumeration", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L556-L567
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.location
def location(self): """ Return the source location (the starting character) of the entity pointed at by the cursor. """ if not hasattr(self, '_loc'): self._loc = conf.lib.clang_getCursorLocation(self) return self._loc
python
def location(self): if not hasattr(self, '_loc'): self._loc = conf.lib.clang_getCursorLocation(self) return self._loc
[ "def", "location", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_loc'", ")", ":", "self", ".", "_loc", "=", "conf", ".", "lib", ".", "clang_getCursorLocation", "(", "self", ")", "return", "self", ".", "_loc" ]
Return the source location (the starting character) of the entity pointed at by the cursor.
[ "Return", "the", "source", "location", "(", "the", "starting", "character", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1488-L1496
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.extent
def extent(self): """ Return the source range (the range of text) occupied by the entity pointed at by the cursor. """ if not hasattr(self, '_extent'): self._extent = conf.lib.clang_getCursorExtent(self) return self._extent
python
def extent(self): if not hasattr(self, '_extent'): self._extent = conf.lib.clang_getCursorExtent(self) return self._extent
[ "def", "extent", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_extent'", ")", ":", "self", ".", "_extent", "=", "conf", ".", "lib", ".", "clang_getCursorExtent", "(", "self", ")", "return", "self", ".", "_extent" ]
Return the source range (the range of text) occupied by the entity pointed at by the cursor.
[ "Return", "the", "source", "range", "(", "the", "range", "of", "text", ")", "occupied", "by", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1499-L1507
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.storage_class
def storage_class(self): """ Retrieves the storage class (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_storage_class'): self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) return StorageClass.from_id(self._storage_class)
python
def storage_class(self): if not hasattr(self, '_storage_class'): self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) return StorageClass.from_id(self._storage_class)
[ "def", "storage_class", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_storage_class'", ")", ":", "self", ".", "_storage_class", "=", "conf", ".", "lib", ".", "clang_Cursor_getStorageClass", "(", "self", ")", "return", "StorageClass", ".", "from_id", "(", "self", ".", "_storage_class", ")" ]
Retrieves the storage class (if any) of the entity pointed at by the cursor.
[ "Retrieves", "the", "storage", "class", "(", "if", "any", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1510-L1518
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.access_specifier
def access_specifier(self): """ Retrieves the access specifier (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_access_specifier'): self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) return AccessSpecifier.from_id(self._access_specifier)
python
def access_specifier(self): if not hasattr(self, '_access_specifier'): self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) return AccessSpecifier.from_id(self._access_specifier)
[ "def", "access_specifier", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_access_specifier'", ")", ":", "self", ".", "_access_specifier", "=", "conf", ".", "lib", ".", "clang_getCXXAccessSpecifier", "(", "self", ")", "return", "AccessSpecifier", ".", "from_id", "(", "self", ".", "_access_specifier", ")" ]
Retrieves the access specifier (if any) of the entity pointed at by the cursor.
[ "Retrieves", "the", "access", "specifier", "(", "if", "any", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1521-L1529
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.type
def type(self): """ Retrieve the Type (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): self._type = conf.lib.clang_getCursorType(self) return self._type
python
def type(self): if not hasattr(self, '_type'): self._type = conf.lib.clang_getCursorType(self) return self._type
[ "def", "type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_type'", ")", ":", "self", ".", "_type", "=", "conf", ".", "lib", ".", "clang_getCursorType", "(", "self", ")", "return", "self", ".", "_type" ]
Retrieve the Type (if any) of the entity pointed at by the cursor.
[ "Retrieve", "the", "Type", "(", "if", "any", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1532-L1539
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.canonical
def canonical(self): """Return the canonical Cursor corresponding to this Cursor. The canonical cursor is the cursor which is representative for the underlying entity. For example, if you have multiple forward declarations for the same class, the canonical cursor for the forward declarations will be identical. """ if not hasattr(self, '_canonical'): self._canonical = conf.lib.clang_getCanonicalCursor(self) return self._canonical
python
def canonical(self): if not hasattr(self, '_canonical'): self._canonical = conf.lib.clang_getCanonicalCursor(self) return self._canonical
[ "def", "canonical", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_canonical'", ")", ":", "self", ".", "_canonical", "=", "conf", ".", "lib", ".", "clang_getCanonicalCursor", "(", "self", ")", "return", "self", ".", "_canonical" ]
Return the canonical Cursor corresponding to this Cursor. The canonical cursor is the cursor which is representative for the underlying entity. For example, if you have multiple forward declarations for the same class, the canonical cursor for the forward declarations will be identical.
[ "Return", "the", "canonical", "Cursor", "corresponding", "to", "this", "Cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1542-L1553
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.result_type
def result_type(self): """Retrieve the Type of the result for this Cursor.""" if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getResultType(self.type) return self._result_type
python
def result_type(self): if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getResultType(self.type) return self._result_type
[ "def", "result_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_result_type'", ")", ":", "self", ".", "_result_type", "=", "conf", ".", "lib", ".", "clang_getResultType", "(", "self", ".", "type", ")", "return", "self", ".", "_result_type" ]
Retrieve the Type of the result for this Cursor.
[ "Retrieve", "the", "Type", "of", "the", "result", "for", "this", "Cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1556-L1561
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.underlying_typedef_type
def underlying_typedef_type(self): """Return the underlying type of a typedef declaration. Returns a Type for the typedef this cursor is a declaration for. If the current cursor is not a typedef, this raises. """ if not hasattr(self, '_underlying_type'): assert self.kind.is_declaration() self._underlying_type = \ conf.lib.clang_getTypedefDeclUnderlyingType(self) return self._underlying_type
python
def underlying_typedef_type(self): if not hasattr(self, '_underlying_type'): assert self.kind.is_declaration() self._underlying_type = \ conf.lib.clang_getTypedefDeclUnderlyingType(self) return self._underlying_type
[ "def", "underlying_typedef_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_underlying_type'", ")", ":", "assert", "self", ".", "kind", ".", "is_declaration", "(", ")", "self", ".", "_underlying_type", "=", "conf", ".", "lib", ".", "clang_getTypedefDeclUnderlyingType", "(", "self", ")", "return", "self", ".", "_underlying_type" ]
Return the underlying type of a typedef declaration. Returns a Type for the typedef this cursor is a declaration for. If the current cursor is not a typedef, this raises.
[ "Return", "the", "underlying", "type", "of", "a", "typedef", "declaration", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1564-L1575
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.enum_type
def enum_type(self): """Return the integer type of an enum declaration. Returns a Type corresponding to an integer. If the cursor is not for an enum, this raises. """ if not hasattr(self, '_enum_type'): assert self.kind == CursorKind.ENUM_DECL self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) return self._enum_type
python
def enum_type(self): if not hasattr(self, '_enum_type'): assert self.kind == CursorKind.ENUM_DECL self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) return self._enum_type
[ "def", "enum_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_enum_type'", ")", ":", "assert", "self", ".", "kind", "==", "CursorKind", ".", "ENUM_DECL", "self", ".", "_enum_type", "=", "conf", ".", "lib", ".", "clang_getEnumDeclIntegerType", "(", "self", ")", "return", "self", ".", "_enum_type" ]
Return the integer type of an enum declaration. Returns a Type corresponding to an integer. If the cursor is not for an enum, this raises.
[ "Return", "the", "integer", "type", "of", "an", "enum", "declaration", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1578-L1588
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.enum_value
def enum_value(self): """Return the value of an enum constant.""" if not hasattr(self, '_enum_value'): assert self.kind == CursorKind.ENUM_CONSTANT_DECL # Figure out the underlying type of the enum to know if it # is a signed or unsigned quantity. underlying_type = self.type if underlying_type.kind == TypeKind.ENUM: underlying_type = underlying_type.get_declaration().enum_type if underlying_type.kind in (TypeKind.CHAR_U, TypeKind.UCHAR, TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG, TypeKind.ULONGLONG, TypeKind.UINT128): self._enum_value = \ conf.lib.clang_getEnumConstantDeclUnsignedValue(self) else: self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) return self._enum_value
python
def enum_value(self): if not hasattr(self, '_enum_value'): assert self.kind == CursorKind.ENUM_CONSTANT_DECL underlying_type = self.type if underlying_type.kind == TypeKind.ENUM: underlying_type = underlying_type.get_declaration().enum_type if underlying_type.kind in (TypeKind.CHAR_U, TypeKind.UCHAR, TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG, TypeKind.ULONGLONG, TypeKind.UINT128): self._enum_value = \ conf.lib.clang_getEnumConstantDeclUnsignedValue(self) else: self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) return self._enum_value
[ "def", "enum_value", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_enum_value'", ")", ":", "assert", "self", ".", "kind", "==", "CursorKind", ".", "ENUM_CONSTANT_DECL", "# Figure out the underlying type of the enum to know if it", "# is a signed or unsigned quantity.", "underlying_type", "=", "self", ".", "type", "if", "underlying_type", ".", "kind", "==", "TypeKind", ".", "ENUM", ":", "underlying_type", "=", "underlying_type", ".", "get_declaration", "(", ")", ".", "enum_type", "if", "underlying_type", ".", "kind", "in", "(", "TypeKind", ".", "CHAR_U", ",", "TypeKind", ".", "UCHAR", ",", "TypeKind", ".", "CHAR16", ",", "TypeKind", ".", "CHAR32", ",", "TypeKind", ".", "USHORT", ",", "TypeKind", ".", "UINT", ",", "TypeKind", ".", "ULONG", ",", "TypeKind", ".", "ULONGLONG", ",", "TypeKind", ".", "UINT128", ")", ":", "self", ".", "_enum_value", "=", "conf", ".", "lib", ".", "clang_getEnumConstantDeclUnsignedValue", "(", "self", ")", "else", ":", "self", ".", "_enum_value", "=", "conf", ".", "lib", ".", "clang_getEnumConstantDeclValue", "(", "self", ")", "return", "self", ".", "_enum_value" ]
Return the value of an enum constant.
[ "Return", "the", "value", "of", "an", "enum", "constant", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1591-L1613
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.hash
def hash(self): """Returns a hash of the cursor as an int.""" if not hasattr(self, '_hash'): self._hash = conf.lib.clang_hashCursor(self) return self._hash
python
def hash(self): if not hasattr(self, '_hash'): self._hash = conf.lib.clang_hashCursor(self) return self._hash
[ "def", "hash", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_hash'", ")", ":", "self", ".", "_hash", "=", "conf", ".", "lib", ".", "clang_hashCursor", "(", "self", ")", "return", "self", ".", "_hash" ]
Returns a hash of the cursor as an int.
[ "Returns", "a", "hash", "of", "the", "cursor", "as", "an", "int", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1625-L1630
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.semantic_parent
def semantic_parent(self): """Return the semantic parent for this cursor.""" if not hasattr(self, '_semantic_parent'): self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) return self._semantic_parent
python
def semantic_parent(self): if not hasattr(self, '_semantic_parent'): self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) return self._semantic_parent
[ "def", "semantic_parent", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_semantic_parent'", ")", ":", "self", ".", "_semantic_parent", "=", "conf", ".", "lib", ".", "clang_getCursorSemanticParent", "(", "self", ")", "return", "self", ".", "_semantic_parent" ]
Return the semantic parent for this cursor.
[ "Return", "the", "semantic", "parent", "for", "this", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1633-L1638
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.lexical_parent
def lexical_parent(self): """Return the lexical parent for this cursor.""" if not hasattr(self, '_lexical_parent'): self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) return self._lexical_parent
python
def lexical_parent(self): if not hasattr(self, '_lexical_parent'): self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) return self._lexical_parent
[ "def", "lexical_parent", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_lexical_parent'", ")", ":", "self", ".", "_lexical_parent", "=", "conf", ".", "lib", ".", "clang_getCursorLexicalParent", "(", "self", ")", "return", "self", ".", "_lexical_parent" ]
Return the lexical parent for this cursor.
[ "Return", "the", "lexical", "parent", "for", "this", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1641-L1646
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.referenced
def referenced(self): """ For a cursor that is a reference, returns a cursor representing the entity that it references. """ if not hasattr(self, '_referenced'): self._referenced = conf.lib.clang_getCursorReferenced(self) return self._referenced
python
def referenced(self): if not hasattr(self, '_referenced'): self._referenced = conf.lib.clang_getCursorReferenced(self) return self._referenced
[ "def", "referenced", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_referenced'", ")", ":", "self", ".", "_referenced", "=", "conf", ".", "lib", ".", "clang_getCursorReferenced", "(", "self", ")", "return", "self", ".", "_referenced" ]
For a cursor that is a reference, returns a cursor representing the entity that it references.
[ "For", "a", "cursor", "that", "is", "a", "reference", "returns", "a", "cursor", "representing", "the", "entity", "that", "it", "references", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1656-L1664
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.brief_comment
def brief_comment(self): """Returns the brief comment text associated with that Cursor""" r = conf.lib.clang_Cursor_getBriefCommentText(self) if not r: return None return str(r)
python
def brief_comment(self): r = conf.lib.clang_Cursor_getBriefCommentText(self) if not r: return None return str(r)
[ "def", "brief_comment", "(", "self", ")", ":", "r", "=", "conf", ".", "lib", ".", "clang_Cursor_getBriefCommentText", "(", "self", ")", "if", "not", "r", ":", "return", "None", "return", "str", "(", "r", ")" ]
Returns the brief comment text associated with that Cursor
[ "Returns", "the", "brief", "comment", "text", "associated", "with", "that", "Cursor" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1667-L1672
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.raw_comment
def raw_comment(self): """Returns the raw comment text associated with that Cursor""" r = conf.lib.clang_Cursor_getRawCommentText(self) if not r: return None return str(r)
python
def raw_comment(self): r = conf.lib.clang_Cursor_getRawCommentText(self) if not r: return None return str(r)
[ "def", "raw_comment", "(", "self", ")", ":", "r", "=", "conf", ".", "lib", ".", "clang_Cursor_getRawCommentText", "(", "self", ")", "if", "not", "r", ":", "return", "None", "return", "str", "(", "r", ")" ]
Returns the raw comment text associated with that Cursor
[ "Returns", "the", "raw", "comment", "text", "associated", "with", "that", "Cursor" ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1675-L1680
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.get_arguments
def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) for i in xrange(0, num_args): yield conf.lib.clang_Cursor_getArgument(self, i)
python
def get_arguments(self): num_args = conf.lib.clang_Cursor_getNumArguments(self) for i in xrange(0, num_args): yield conf.lib.clang_Cursor_getArgument(self, i)
[ "def", "get_arguments", "(", "self", ")", ":", "num_args", "=", "conf", ".", "lib", ".", "clang_Cursor_getNumArguments", "(", "self", ")", "for", "i", "in", "xrange", "(", "0", ",", "num_args", ")", ":", "yield", "conf", ".", "lib", ".", "clang_Cursor_getArgument", "(", "self", ",", "i", ")" ]
Return an iterator for accessing the arguments of this cursor.
[ "Return", "an", "iterator", "for", "accessing", "the", "arguments", "of", "this", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1682-L1686
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.get_children
def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. assert child != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. child._tu = self._tu children.append(child) return 1 # continue children = [] conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), children) return iter(children)
python
def get_children(self): def visitor(child, parent, children): assert child != conf.lib.clang_getNullCursor() child._tu = self._tu children.append(child) return 1 children = [] conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), children) return iter(children)
[ "def", "get_children", "(", "self", ")", ":", "# FIXME: Expose iteration from CIndex, PR6125.", "def", "visitor", "(", "child", ",", "parent", ",", "children", ")", ":", "# FIXME: Document this assertion in API.", "# FIXME: There should just be an isNull method.", "assert", "child", "!=", "conf", ".", "lib", ".", "clang_getNullCursor", "(", ")", "# Create reference to TU so it isn't GC'd before Cursor.", "child", ".", "_tu", "=", "self", ".", "_tu", "children", ".", "append", "(", "child", ")", "return", "1", "# continue", "children", "=", "[", "]", "conf", ".", "lib", ".", "clang_visitChildren", "(", "self", ",", "callbacks", "[", "'cursor_visit'", "]", "(", "visitor", ")", ",", "children", ")", "return", "iter", "(", "children", ")" ]
Return an iterator for accessing the children of this cursor.
[ "Return", "an", "iterator", "for", "accessing", "the", "children", "of", "this", "cursor", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1709-L1725
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.walk_preorder
def walk_preorder(self): """Depth-first preorder walk over the cursor and its descendants. Yields cursors. """ yield self for child in self.get_children(): for descendant in child.walk_preorder(): yield descendant
python
def walk_preorder(self): yield self for child in self.get_children(): for descendant in child.walk_preorder(): yield descendant
[ "def", "walk_preorder", "(", "self", ")", ":", "yield", "self", "for", "child", "in", "self", ".", "get_children", "(", ")", ":", "for", "descendant", "in", "child", ".", "walk_preorder", "(", ")", ":", "yield", "descendant" ]
Depth-first preorder walk over the cursor and its descendants. Yields cursors.
[ "Depth", "-", "first", "preorder", "walk", "over", "the", "cursor", "and", "its", "descendants", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1727-L1735
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Cursor.is_anonymous
def is_anonymous(self): """ Check if the record is anonymous. """ if self.kind == CursorKind.FIELD_DECL: return self.type.get_declaration().is_anonymous() return conf.lib.clang_Cursor_isAnonymous(self)
python
def is_anonymous(self): if self.kind == CursorKind.FIELD_DECL: return self.type.get_declaration().is_anonymous() return conf.lib.clang_Cursor_isAnonymous(self)
[ "def", "is_anonymous", "(", "self", ")", ":", "if", "self", ".", "kind", "==", "CursorKind", ".", "FIELD_DECL", ":", "return", "self", ".", "type", ".", "get_declaration", "(", ")", ".", "is_anonymous", "(", ")", "return", "conf", ".", "lib", ".", "clang_Cursor_isAnonymous", "(", "self", ")" ]
Check if the record is anonymous.
[ "Check", "if", "the", "record", "is", "anonymous", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1749-L1755
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Type.argument_types
def argument_types(self): """Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance. """ class ArgumentsIterator(collections.Sequence): def __init__(self, parent): self.parent = parent self.length = None def __len__(self): if self.length is None: self.length = conf.lib.clang_getNumArgTypes(self.parent) return self.length def __getitem__(self, key): # FIXME Support slice objects. if not isinstance(key, int): raise TypeError("Must supply a non-negative int.") if key < 0: raise IndexError("Only non-negative indexes are accepted.") if key >= len(self): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) result = conf.lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") return result assert self.kind == TypeKind.FUNCTIONPROTO return ArgumentsIterator(self)
python
def argument_types(self): class ArgumentsIterator(collections.Sequence): def __init__(self, parent): self.parent = parent self.length = None def __len__(self): if self.length is None: self.length = conf.lib.clang_getNumArgTypes(self.parent) return self.length def __getitem__(self, key): if not isinstance(key, int): raise TypeError("Must supply a non-negative int.") if key < 0: raise IndexError("Only non-negative indexes are accepted.") if key >= len(self): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) result = conf.lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") return result assert self.kind == TypeKind.FUNCTIONPROTO return ArgumentsIterator(self)
[ "def", "argument_types", "(", "self", ")", ":", "class", "ArgumentsIterator", "(", "collections", ".", "Sequence", ")", ":", "def", "__init__", "(", "self", ",", "parent", ")", ":", "self", ".", "parent", "=", "parent", "self", ".", "length", "=", "None", "def", "__len__", "(", "self", ")", ":", "if", "self", ".", "length", "is", "None", ":", "self", ".", "length", "=", "conf", ".", "lib", ".", "clang_getNumArgTypes", "(", "self", ".", "parent", ")", "return", "self", ".", "length", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "# FIXME Support slice objects.", "if", "not", "isinstance", "(", "key", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Must supply a non-negative int.\"", ")", "if", "key", "<", "0", ":", "raise", "IndexError", "(", "\"Only non-negative indexes are accepted.\"", ")", "if", "key", ">=", "len", "(", "self", ")", ":", "raise", "IndexError", "(", "\"Index greater than container length: \"", "\"%d > %d\"", "%", "(", "key", ",", "len", "(", "self", ")", ")", ")", "result", "=", "conf", ".", "lib", ".", "clang_getArgType", "(", "self", ".", "parent", ",", "key", ")", "if", "result", ".", "kind", "==", "TypeKind", ".", "INVALID", ":", "raise", "IndexError", "(", "\"Argument could not be retrieved.\"", ")", "return", "result", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "ArgumentsIterator", "(", "self", ")" ]
Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance.
[ "Retrieve", "a", "container", "for", "the", "non", "-", "variadic", "arguments", "for", "this", "type", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1974-L2010
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Type.element_type
def element_type(self): """Retrieve the Type of elements within this Type. If accessed on a type that is not an array, complex, or vector type, an exception will be raised. """ result = conf.lib.clang_getElementType(self) if result.kind == TypeKind.INVALID: raise Exception('Element type not available on this type.') return result
python
def element_type(self): result = conf.lib.clang_getElementType(self) if result.kind == TypeKind.INVALID: raise Exception('Element type not available on this type.') return result
[ "def", "element_type", "(", "self", ")", ":", "result", "=", "conf", ".", "lib", ".", "clang_getElementType", "(", "self", ")", "if", "result", ".", "kind", "==", "TypeKind", ".", "INVALID", ":", "raise", "Exception", "(", "'Element type not available on this type.'", ")", "return", "result" ]
Retrieve the Type of elements within this Type. If accessed on a type that is not an array, complex, or vector type, an exception will be raised.
[ "Retrieve", "the", "Type", "of", "elements", "within", "this", "Type", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2013-L2023
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Type.element_count
def element_count(self): """Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises. """ result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') return result
python
def element_count(self): result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') return result
[ "def", "element_count", "(", "self", ")", ":", "result", "=", "conf", ".", "lib", ".", "clang_getNumElements", "(", "self", ")", "if", "result", "<", "0", ":", "raise", "Exception", "(", "'Type does not have elements.'", ")", "return", "result" ]
Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises.
[ "Retrieve", "the", "number", "of", "elements", "in", "this", "type", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2026-L2037
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Type.is_function_variadic
def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
python
def is_function_variadic(self): assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
[ "def", "is_function_variadic", "(", "self", ")", ":", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "conf", ".", "lib", ".", "clang_isFunctionTypeVariadic", "(", "self", ")" ]
Determine whether this function Type is a variadic function type.
[ "Determine", "whether", "this", "function", "Type", "is", "a", "variadic", "function", "type", "." ]
train
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2097-L2101