Search is not available for this dataset
text
stringlengths
75
104k
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) ...
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 ...
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: ...
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)
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...
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)
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...
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 = ...
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...
def format_page(self, page): """ Banana banana """ self.formatting_page_signal(self, page) return self._format_page(page)
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.joi...
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(ful...
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_at...
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...
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)
def format_navigation(self, project): """Banana banana """ try: template = self.get_template('site_navigation.html') except IOError: return None return template.render({'project': project})
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, ...
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
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') ...
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 ...
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_extensi...
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.wr...
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)
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: ...
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 f...
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...
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 ...
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.make...
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
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 ent...
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.e...
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()
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) ...
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_
def discard(self, key): """ Banana banana """ if key in self.map: key, prev, nxt = self.map.pop(key) prev[2] = nxt nxt[1] = prev
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, dom...
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)
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 ex...
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)
def get_attr(self, symbol, attrname): """ Helper for getting symbol extension attributes """ return symbol.extension_attributes.get(self.extension_name, {}).get( attrname, None)
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_ar...
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 exten...
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, ...
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...
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...
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....
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 =...
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....
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: ...
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: e...
def persist(self): """ Banana banana """ if self.app.dry: return for proj in self.subprojects.values(): proj.persist()
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.s...
def format(self, link_resolver, output): """ Banana banana """ if not output: return self.tree.format(link_resolver, output, self.extensions) self.formatted_signal(self)
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...
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) ...
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([])...
def __get_formatter(self, extension_name): """ Banana banana """ ext = self.extensions.get(extension_name) if ext: return ext.formatter return None
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', 'asse...
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: rai...
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() a...
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_pat...
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 ""...
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...
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 ...
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)
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)...
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)
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] ...
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_error...
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)
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(...
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))
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 ...
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() con...
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
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 = TokenKin...
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
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
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_c...
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(s...
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
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 ...
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
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....
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_...
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. underlyi...
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
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
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
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
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)
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)
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)
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. ...
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
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)
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)...
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: r...
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.') ...
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)