Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get_fields(self):
"""Return an iterator for accessing the fields of this type."""
def visitor(field, children):
assert field != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
field._tu = self._tu
fields.append... |
def parse(self, path, args=None, unsaved_files=None, options = 0):
"""Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents fo... |
def from_ast_file(cls, filename, index=None):
"""Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will... |
def get_includes(self):
"""
Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files includ... |
def get_location(self, filename, position):
"""Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0,... |
def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
... |
def diagnostics(self):
"""
Return an iterable (and indexable) object containing the diagnostics.
"""
class DiagIterator:
def __init__(self, tu):
self.tu = tu
def __len__(self):
return int(conf.lib.clang_getNumDiagnostics(self.tu))
... |
def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents ... |
def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an erro... |
def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
"""
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list o... |
def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both... |
def name(self):
"""Return the complete file and path name of the file."""
return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self))) |
def arguments(self):
"""
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
"""
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i... |
def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
r... |
def make_translations(unique_name, node):
'''
Compute and store the title that should be displayed
when linking to a given unique_name, eg in python
when linking to test_greeter_greet() we want to display
Test.Greeter.greet
'''
introspectable = not node.attrib.get('introspectable') == '0'
... |
def get_klass_parents(gi_name):
'''
Returns a sorted list of qualified symbols representing
the parents of the klass-like symbol named gi_name
'''
res = []
parents = __HIERARCHY_GRAPH.predecessors(gi_name)
if not parents:
return []
__get_parent_link_recurse(parents[0], res)
r... |
def get_klass_children(gi_name):
'''
Returns a dict of qualified symbols representing
the children of the klass-like symbol named gi_name
'''
res = {}
children = __HIERARCHY_GRAPH.successors(gi_name)
for gi_name in children:
ctype_name = ALL_GI_TYPES[gi_name]
qs = QualifiedSy... |
def cache_nodes(gir_root, all_girs):
'''
Identify and store all the gir symbols the symbols we will document
may link to, or be typed with
'''
ns_node = gir_root.find('./{%s}namespace' % NS_MAP['core'])
id_prefixes = ns_node.attrib['{%s}identifier-prefixes' % NS_MAP['c']]
sym_prefixes = ns_n... |
def type_description_from_node(gi_node):
'''
Parse a typed node, returns a usable description
'''
ctype_name, gi_name, array_nesting = unnest_type (gi_node)
cur_ns = get_namespace(gi_node)
if ctype_name is not None:
type_tokens = __type_tokens_from_cdecl (ctype_name)
else:
... |
def is_introspectable(name, language):
'''
Do not call this before caching the nodes
'''
if name in FUNDAMENTALS[language]:
return True
if name not in __TRANSLATED_NAMES[language]:
return False
return True |
def dict_to_html_attrs(dict_):
"""
Banana banana
"""
res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items())
return res |
def title(self):
"""
Banana banana
"""
resolved_title = Link.resolving_title_signal(self)
resolved_title = [elem for elem in resolved_title if elem is not
None]
if resolved_title:
return str(resolved_title[0])
return self._tit... |
def get_link(self, link_resolver):
"""
Banana banana
"""
res = link_resolver.resolving_link_signal(self)
if not res:
return self.ref, None
ref = res[0] or self.ref
if res[1]:
return ref, dict_to_html_attrs(res[1])
return ref, None |
def add_link(self, link):
"""
Banana banana
"""
if link.id_ not in self.__links:
self.__links[link.id_] = link |
def upsert_link(self, link, overwrite_ref=False):
"""
Banana banana
"""
elink = self.__links.get(link.id_)
if elink:
if elink.ref is None or overwrite_ref and link.ref:
elink.ref = link.ref
# pylint: disable=protected-access
if... |
def find_file(filename, include_paths):
"""Banana banana
"""
if os.path.isabs(filename):
if os.path.exists(filename):
return filename
return None
for include_path in include_paths:
fpath = os.path.join(include_path, filename)
if os.path.exists(fpath) and os.p... |
def resolve(uri, include_paths):
"""
Banana banana
"""
include_filename, line_ranges, symbol = __parse_include(uri)
if include_filename is None:
return None
include_path = find_file(include_filename, include_paths)
if include_path is None:
return None
return __get_content... |
def load_config_json(conf_file):
"""Banana?"""
try:
with open(conf_file) as _:
try:
json_conf = json.load(_)
except ValueError as ze_error:
error('invalid-config',
'The provided configuration file %s is not valid json.\n'
... |
def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
"""
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.... |
def get(self, key, default=None):
"""
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
"""
if key in self.__cli:
return self... |
def get_index(self, prefix=''):
"""
Retrieve the absolute path to an index, according to
`prefix`.
Args:
prefix: str, the desired prefix or `None`.
Returns:
str: An absolute path, or `None`
"""
if prefix:
prefixed = '%s_index'... |
def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
"""
Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Ar... |
def get_paths(self, key):
"""
Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths.
"""
final_paths = []
if key in self.__cli:
paths = self.__cli[key] ... |
def get_sources(self, prefix=''):
"""
Retrieve a set of absolute paths to sources, according to `prefix`
`ConfigParser` will perform wildcard expansion and
filtering.
Args:
prefix: str, the desired prefix.
Returns:
utils.utils.OrderedSet: The se... |
def get_dependencies(self):
"""
Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration.
"""
all_deps = OrderedSet()
for key, _ in list(self.__c... |
def dump(self, conf_file=None):
"""
Dump the possibly updated config to a file.
Args:
conf_file: str, the destination, or None to overwrite the
existing configuration.
"""
if conf_file:
conf_dir = os.path.dirname(conf_file)
if... |
def _check_submodule_status(root, submodules):
"""check submodule status
Has three return values:
'missing' - submodules are absent
'unclean' - submodules have unstaged changes
'clean' - all submodules are up to date
"""
if hasattr(sys, "frozen"):
# frozen via py2exe or similar, don... |
def _update_submodules(repo_dir):
"""update submodules in a repo"""
subprocess.check_call("git submodule init", cwd=repo_dir, shell=True)
subprocess.check_call(
"git submodule update --recursive", cwd=repo_dir, shell=True) |
def require_clean_submodules(repo_root, submodules):
"""Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion,
this is not a distutils command.
"""
# PACKAGERS: Add a return here to skip checks for gi... |
def symlink(source, link_name):
"""
Method to allow creating symlinks on Windows
"""
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
impor... |
def pkgconfig(*packages, **kw):
"""
Query pkg-config for library compile and linking options. Return configuration in distutils
Extension format.
Usage:
pkgconfig('opencv')
pkgconfig('opencv', 'libavformat')
pkgconfig('opencv', optional='--static')
pkgconfig('opencv', config=c)
... |
def register_error_code(code, exception_type, domain='core'):
"""Register a new error code"""
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) |
def register_warning_code(code, exception_type, domain='core'):
"""Register a new warning code"""
Logger._warning_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code) |
def _log(code, message, level, domain):
"""Call this to add an entry in the journal"""
entry = LogEntry(level, domain, code, message)
Logger.journal.append(entry)
if Logger.silent:
return
if level >= Logger._verbosity:
_print_entry(entry) |
def error(code, message, **kwargs):
"""Call this to raise an exception and have it stored in the journal"""
assert code in Logger._error_code_to_exception
exc_type, domain = Logger._error_code_to_exception[code]
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, ERR... |
def warn(code, message, **kwargs):
"""
Call this to store a warning in the journal.
Will raise if `Logger.fatal_warnings` is set to True.
"""
if code in Logger._ignored_codes:
return
assert code in Logger._warning_code_to_exception
exc_type, domain ... |
def debug(message, domain):
"""Log debugging information"""
if domain in Logger._ignored_domains:
return
Logger._log(None, message, DEBUG, domain) |
def info(message, domain):
"""Log simple info"""
if domain in Logger._ignored_domains:
return
Logger._log(None, message, INFO, domain) |
def get_issues():
"""Get actual issues in the journal."""
issues = []
for entry in Logger.journal:
if entry.level >= WARNING:
issues.append(entry)
return issues |
def reset():
"""Resets Logger to its initial state"""
Logger.journal = []
Logger.fatal_warnings = False
Logger._ignored_codes = set()
Logger._ignored_domains = set()
Logger._verbosity = 2
Logger._last_checkpoint = 0 |
def set_verbosity(verbosity):
"""Banana banana
"""
Logger._verbosity = min(max(0, WARNING - verbosity), 2)
debug("Verbosity set to %d" % (WARNING - Logger._verbosity), 'logging') |
def walk(self, action, user_data=None):
"""
Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap.
... |
def get_all_sources(self):
"""
Returns:
OrderedDict: all source file names in the hierarchy, paired with
the names of their subpages.
"""
if self.__all_sources is None:
self.__all_sources = OrderedDict()
self.walk(self.__add_one)
... |
def parse(self, filename):
"""
Parse a sitemap file.
Args:
filename: str, the path to the sitemap file.
Returns:
Sitemap: the generated sitemap.
"""
with io.open(filename, 'r', encoding='utf-8') as _:
lines = _.readlines()
al... |
def _grouper(iterable, n_args, fillvalue=None):
"""
Banana banana
"""
args = [iter(iterable)] * n_args
return zip_longest(*args, fillvalue=fillvalue) |
def parse_comment(self, comment, filename, lineno, endlineno,
include_paths=None, stripped=False):
"""
Returns a Comment given a string
"""
if not stripped and not self.__validate_c_comment(comment.strip()):
return None
title_offset = 0
... |
def comment_to_ast(self, comment, link_resolver):
"""
Given a gtk-doc comment string, returns an opaque PyCapsule
containing the document root.
This is an optimization allowing to parse the docstring only
once, and to render it multiple times with
`ast_to_html`, links di... |
def ast_to_html(self, ast, link_resolver):
"""
See the documentation of `to_ast` for
more information.
Args:
ast: PyCapsule, a capsule as returned by `to_ast`
link_resolver: hotdoc.core.links.LinkResolver, a link
resolver instance.
"""
... |
def translate_comment(self, comment, link_resolver):
"""
Given a gtk-doc comment string, returns the comment translated
to the desired format.
"""
out = u''
self.translate_tags(comment, link_resolver)
ast = self.comment_to_ast(comment, link_resolver)
out ... |
def translate_tags(self, comment, link_resolver):
"""Banana banana
"""
for tname in ('deprecated',):
tag = comment.tags.get(tname)
if tag is not None and tag.description:
comment = comment_from_tag(tag)
ast = self.comment_to_ast(comment, li... |
def parse_config(self, config):
"""Banana banana
"""
self.remove_xml_tags = config.get('gtk_doc_remove_xml')
self.escape_html = config.get('gtk_doc_escape_html')
self.gdbus_codegen_sources = config.get_paths('gdbus_codegen_sources') |
def add_extension_attribute(self, ext_name, key, value):
"""
Banana banana
"""
attributes = self.extension_attributes.pop(ext_name, {})
attributes[key] = value
self.extension_attributes[ext_name] = attributes |
def get_extension_attribute(self, ext_name, key):
"""
Banana banana
"""
attributes = self.extension_attributes.get(ext_name)
if not attributes:
return None
return attributes.get(key) |
def update_children_comments(self):
"""
Banana banana
"""
if self.comment is None:
return
for sym in self.get_children_symbols():
if isinstance(sym, ParameterSymbol):
sym.comment = self.comment.params.get(sym.argname)
elif isin... |
def resolve_links(self, link_resolver):
"""
Banana banana
"""
if self.link is None:
self.link = Link(self.unique_name, self._make_name(),
self.unique_name)
self.link = link_resolver.upsert_link(self.link, overwrite_ref=True)
for ... |
def resolve_links(self, link_resolver):
"""
Banana banana
"""
self.type_link = None
self.type_tokens = []
for child in self.get_children_symbols():
child.resolve_links(link_resolver)
for tok in self.input_tokens:
if isinstance(tok, Link):... |
def comment_from_tag(tag):
"""
Convenience function to create a full-fledged comment for a
given tag, for example it is convenient to assign a Comment
to a ReturnValueSymbol.
"""
if not tag:
return None
comment = Comment(name=tag.name,
meta={'description': tag.d... |
def decoder(data):
"""
This generator processes a sequence of bytes in Modified UTF-8 encoding
and produces a sequence of unicode string characters.
It takes bits from the byte until it matches one of the known encoding
sequences.
It uses ``DecodeMap`` to mask, compare and generate values.
... |
def decode_modified_utf8(data, errors="strict"):
"""
Decodes a sequence of bytes to a unicode text and length using
Modified UTF-8.
This function is designed to be used with Python ``codecs`` module.
:param data: a string of bytes in Modified UTF-8
:param errors: handle decoding errors
:ret... |
def apply(self, byte, value, data, i, count):
"""
Apply mask, compare to expected value, shift and return result.
Eventually, this could become a ``reduce`` function.
:param byte: The byte to compare
:param value: The currently accumulated value.
:param data: The data bu... |
def load(file_object, *transformers, **kwargs):
"""
Deserializes Java primitive data and objects serialized using
ObjectOutputStream from a file-like object.
:param file_object: A file-like object
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log a... |
def loads(string, *transformers, **kwargs):
"""
Deserializes Java objects and primitive data serialized using
ObjectOutputStream from a string.
:param string: A Java data string
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused... |
def dumps(obj, *transformers):
"""
Serializes Java primitive data and objects unmarshaled by load(s) before
into string.
:param obj: A Python primitive object, or one loaded using load(s)
:param transformers: Custom transformers to use
:return: The serialized data as a string
"""
marsha... |
def read(data, fmt_str):
"""
Reads input bytes and extract the given structure. Returns both the read
elements and the remaining data
:param data: Data as bytes
:param fmt_str: Struct unpack format string
:return: A tuple (results as tuple, remaining data)
"""
size = struct.calcsize(fmt... |
def read_string(data, length_fmt="H"):
"""
Reads a serialized string
:param data: Bytes where to read the string from
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
"""
(length,), data = read(data, ">{0}".format(length_fmt))
ba, data =... |
def flags(flags):
"""
Returns the names of the class description flags found in the given
integer
:param flags: A class description flag entry
:return: The flags names as a single string
"""
names = sorted(
descr for key, descr in OpCodeDebug.STREAM_C... |
def _readStreamHeader(self):
"""
Reads the magic header of a Java serialization stream
:raise IOError: Invalid magic header (not a Java stream)
"""
(magic, version) = self._readStruct(">HH")
if magic != self.STREAM_MAGIC or version != self.STREAM_VERSION:
rai... |
def _read_and_exec_opcode(self, ident=0, expect=None):
"""
Reads the next opcode, and executes its handler
:param ident: Log identation level
:param expect: A list of expected opcodes
:return: A tuple: (opcode, result of the handler)
:raise IOError: Read opcode is not on... |
def _readString(self, length_fmt="H"):
"""
Reads a serialized string
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
:raise RuntimeError: Unexpected end of stream
"""
(length,) = self._readStruct(">{0}".format(le... |
def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
"""
# TC_CLASSDESC className serialVersionUID newHandle classDescInfo
# classDescInfo:
#... |
def do_string(self, parent=None, ident=0):
"""
Handles a TC_STRING opcode
:param parent:
:param ident: Log indentation level
:return: A string
"""
log_debug("[string]", ident)
ba = JavaString(self._readString())
self._add_reference(ba, ident)
... |
def do_array(self, parent=None, ident=0):
"""
Handles a TC_ARRAY opcode
:param parent:
:param ident: Log indentation level
:return: A list of deserialized objects
"""
# TC_ARRAY classDesc newHandle (int)<size> values[size]
log_debug("[array]", ident)
... |
def do_reference(self, parent=None, ident=0):
"""
Handles a TC_REFERENCE opcode
:param parent:
:param ident: Log indentation level
:return: The referenced object
"""
(handle,) = self._readStruct(">L")
log_debug("## Reference handle: 0x{0:X}".format(handle... |
def do_enum(self, parent=None, ident=0):
"""
Handles a TC_ENUM opcode
:param parent:
:param ident: Log indentation level
:return: A JavaEnum object
"""
# TC_ENUM classDesc newHandle enumConstantName
enum = JavaEnum()
_, classdesc = self._read_and_... |
def _create_hexdump(src, start_offset=0, length=16):
"""
Prepares an hexadecimal dump string
:param src: A string containing binary data
:param start_offset: The start offset of the source
:param length: Length of a dump line
:return: A dump string
"""
FI... |
def _convert_char_to_type(self, type_char):
"""
Ensures a read character is a typecode.
:param type_char: Read typecode
:return: The typecode as a string (using chr)
:raise RuntimeError: Unknown typecode
"""
typecode = type_char
if type(type_char) is int:... |
def _add_reference(self, obj, ident=0):
"""
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
"""
log_debug(
"## New reference handle 0x{0:X}: {1} -> {2}".format(
len(self.reference... |
def _oops_dump_state(self, ignore_remaining_data=False):
"""
Log a deserialization error
:param ignore_remaining_data: If True, don't log an error when
unused trailing bytes are remaining
"""
log_error("==Oops state dump" + "=" * (30 - 17))
... |
def dump(self, obj):
"""
Dumps the given object in the Java serialization format
"""
self.references = []
self.object_obj = obj
self.object_stream = BytesIO()
self._writeStreamHeader()
self.writeObject(obj)
return self.object_stream.getvalue() |
def writeObject(self, obj):
"""
Appends an object to the serialization stream
:param obj: A string or a deserialized Java object
:raise RuntimeError: Unsupported type
"""
log_debug("Writing object of type {0}".format(type(obj).__name__))
if isinstance(obj, JavaAr... |
def _writeString(self, obj, use_reference=True):
"""
Appends a string to the serialization stream
:param obj: String to serialize
:param use_reference: If True, allow writing a reference
"""
# TODO: Convert to "modified UTF-8"
# http://docs.oracle.com/javase/7/do... |
def write_string(self, obj, use_reference=True):
"""
Writes a Java string with the TC_STRING type marker
:param obj: The string to print
:param use_reference: If True, allow writing a reference
"""
if use_reference and isinstance(obj, JavaString):
try:
... |
def write_enum(self, obj):
"""
Writes an Enum value
:param obj: A JavaEnum object
"""
# FIXME: the output doesn't have the same references as the real
# serializable form
self._writeStruct(">B", 1, (self.TC_ENUM,))
try:
idx = self.references.... |
def write_blockdata(self, obj, parent=None):
"""
Appends a block of data to the serialization stream
:param obj: String form of the data block
"""
if type(obj) is str:
# Latin-1: keep bytes as is
obj = to_bytes(obj, "latin-1")
length = len(obj)
... |
def write_object(self, obj, parent=None):
"""
Writes an object header to the serialization stream
:param obj: Not yet used
:param parent: Not yet used
"""
# Transform object
for transformer in self.object_transformers:
tmp_object = transformer.transfo... |
def write_class(self, obj, parent=None):
"""
Writes a class to the stream
:param obj: A JavaClass object
:param parent:
"""
self._writeStruct(">B", 1, (self.TC_CLASS,))
self.write_classdesc(obj) |
def write_classdesc(self, obj, parent=None):
"""
Writes a class description
:param obj: Class description to write
:param parent:
"""
if obj not in self.references:
# Add reference
self.references.append(obj)
logging.debug(
... |
def write_reference(self, ref_index):
"""
Writes a reference
:param ref_index: Local index (0-based) to the reference
"""
self._writeStruct(
">BL", 1, (self.TC_REFERENCE, ref_index + self.BASE_REFERENCE_IDX)
) |
def write_array(self, obj):
"""
Writes a JavaArray
:param obj: A JavaArray object
"""
classdesc = obj.get_class()
self._writeStruct(">B", 1, (self.TC_ARRAY,))
self.write_classdesc(classdesc)
self._writeStruct(">i", 1, (len(obj),))
# Add reference... |
def _write_value(self, field_type, value):
"""
Writes an item of an array
:param field_type: Value type
:param value: The value itself
"""
if len(field_type) > 1:
# We don't need details for arrays and objects
field_type = field_type[0]
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.