repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L500-L530
train
235,700
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): """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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L546-L553
train
235,701
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): """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)
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L556-L567
train
235,702
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1542-L1553
train
235,703
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): """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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1556-L1561
train
235,704
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1564-L1575
train
235,705
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1578-L1588
train
235,706
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1591-L1613
train
235,707
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): """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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1625-L1630
train
235,708
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): """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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1633-L1638
train
235,709
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): """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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1641-L1646
train
235,710
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): """ 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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1656-L1664
train
235,711
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): """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", "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" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1667-L1672
train
235,712
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): """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", "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" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1675-L1680
train
235,713
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): """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_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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1682-L1686
train
235,714
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): """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)
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1709-L1725
train
235,715
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): """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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1727-L1735
train
235,716
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): """ 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", "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1749-L1755
train
235,717
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): """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)
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1974-L2010
train
235,718
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2013-L2023
train
235,719
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): """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
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2026-L2037
train
235,720
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): """Determine whether this function Type is a variadic function type.""" 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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2097-L2101
train
235,721
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Type.get_fields
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(field) return 1 # continue fields = [] conf.lib.clang_Type_visitFields(self, callbacks['fields_visit'](visitor), fields) return iter(fields)
python
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(field) return 1 # continue fields = [] conf.lib.clang_Type_visitFields(self, callbacks['fields_visit'](visitor), fields) return iter(fields)
[ "def", "get_fields", "(", "self", ")", ":", "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", "(", "field", ")", "return", "1", "# continue", "fields", "=", "[", "]", "conf", ".", "lib", ".", "clang_Type_visitFields", "(", "self", ",", "callbacks", "[", "'fields_visit'", "]", "(", "visitor", ")", ",", "fields", ")", "return", "iter", "(", "fields", ")" ]
Return an iterator for accessing the fields of this type.
[ "Return", "an", "iterator", "for", "accessing", "the", "fields", "of", "this", "type", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2174-L2187
train
235,722
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
Index.parse
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 for files can be provided by passing a list of pairs to as unsaved_files, the first item should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. If an error was encountered during parsing, a TranslationUnitLoadError will be raised. """ return TranslationUnit.from_source(path, args, unsaved_files, options, self)
python
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 for files can be provided by passing a list of pairs to as unsaved_files, the first item should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. If an error was encountered during parsing, a TranslationUnitLoadError will be raised. """ return TranslationUnit.from_source(path, args, unsaved_files, options, self)
[ "def", "parse", "(", "self", ",", "path", ",", "args", "=", "None", ",", "unsaved_files", "=", "None", ",", "options", "=", "0", ")", ":", "return", "TranslationUnit", ".", "from_source", "(", "path", ",", "args", ",", "unsaved_files", ",", "options", ",", "self", ")" ]
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 for files can be provided by passing a list of pairs to as unsaved_files, the first item should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. If an error was encountered during parsing, a TranslationUnitLoadError will be raised.
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2471-L2485
train
235,723
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.from_ast_file
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 be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created. """ if index is None: index = Index.create() ptr = conf.lib.clang_createTranslationUnit(index, filename) if not ptr: raise TranslationUnitLoadError(filename) return cls(ptr=ptr, index=index)
python
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 be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created. """ if index is None: index = Index.create() ptr = conf.lib.clang_createTranslationUnit(index, filename) if not ptr: raise TranslationUnitLoadError(filename) return cls(ptr=ptr, index=index)
[ "def", "from_ast_file", "(", "cls", ",", "filename", ",", "index", "=", "None", ")", ":", "if", "index", "is", "None", ":", "index", "=", "Index", ".", "create", "(", ")", "ptr", "=", "conf", ".", "lib", ".", "clang_createTranslationUnit", "(", "index", ",", "filename", ")", "if", "not", "ptr", ":", "raise", "TranslationUnitLoadError", "(", "filename", ")", "return", "cls", "(", "ptr", "=", "ptr", ",", "index", "=", "index", ")" ]
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 be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created.
[ "Create", "a", "TranslationUnit", "instance", "from", "a", "saved", "AST", "file", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2604-L2623
train
235,724
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.get_includes
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 included through precompiled headers. """ def visitor(fobj, lptr, depth, includes): if depth > 0: loc = lptr.contents includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) # Automatically adapt CIndex/ctype pointers to python objects includes = [] conf.lib.clang_getInclusions(self, callbacks['translation_unit_includes'](visitor), includes) return iter(includes)
python
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 included through precompiled headers. """ def visitor(fobj, lptr, depth, includes): if depth > 0: loc = lptr.contents includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) # Automatically adapt CIndex/ctype pointers to python objects includes = [] conf.lib.clang_getInclusions(self, callbacks['translation_unit_includes'](visitor), includes) return iter(includes)
[ "def", "get_includes", "(", "self", ")", ":", "def", "visitor", "(", "fobj", ",", "lptr", ",", "depth", ",", "includes", ")", ":", "if", "depth", ">", "0", ":", "loc", "=", "lptr", ".", "contents", "includes", ".", "append", "(", "FileInclusion", "(", "loc", ".", "file", ",", "File", "(", "fobj", ")", ",", "loc", ",", "depth", ")", ")", "# Automatically adapt CIndex/ctype pointers to python objects", "includes", "=", "[", "]", "conf", ".", "lib", ".", "clang_getInclusions", "(", "self", ",", "callbacks", "[", "'translation_unit_includes'", "]", "(", "visitor", ")", ",", "includes", ")", "return", "iter", "(", "includes", ")" ]
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 included through precompiled headers.
[ "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", "included", "through", "precompiled", "headers", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2648-L2666
train
235,725
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.get_location
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, 0) """ f = self.get_file(filename) if isinstance(position, int): return SourceLocation.from_offset(self, f, position) return SourceLocation.from_position(self, f, position[0], position[1])
python
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, 0) """ f = self.get_file(filename) if isinstance(position, int): return SourceLocation.from_offset(self, f, position) return SourceLocation.from_position(self, f, position[0], position[1])
[ "def", "get_location", "(", "self", ",", "filename", ",", "position", ")", ":", "f", "=", "self", ".", "get_file", "(", "filename", ")", "if", "isinstance", "(", "position", ",", "int", ")", ":", "return", "SourceLocation", ".", "from_offset", "(", "self", ",", "f", ",", "position", ")", "return", "SourceLocation", ".", "from_position", "(", "self", ",", "f", ",", "position", "[", "0", "]", ",", "position", "[", "1", "]", ")" ]
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, 0)
[ "Obtain", "a", "SourceLocation", "for", "a", "file", "in", "this", "translation", "unit", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2673-L2687
train
235,726
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.get_extent
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. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15))) """ f = self.get_file(filename) if len(locations) < 2: raise Exception('Must pass object with at least 2 elements') start_location, end_location = locations if hasattr(start_location, '__len__'): start_location = SourceLocation.from_position(self, f, start_location[0], start_location[1]) elif isinstance(start_location, int): start_location = SourceLocation.from_offset(self, f, start_location) if hasattr(end_location, '__len__'): end_location = SourceLocation.from_position(self, f, end_location[0], end_location[1]) elif isinstance(end_location, int): end_location = SourceLocation.from_offset(self, f, end_location) assert isinstance(start_location, SourceLocation) assert isinstance(end_location, SourceLocation) return SourceRange.from_locations(start_location, end_location)
python
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. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15))) """ f = self.get_file(filename) if len(locations) < 2: raise Exception('Must pass object with at least 2 elements') start_location, end_location = locations if hasattr(start_location, '__len__'): start_location = SourceLocation.from_position(self, f, start_location[0], start_location[1]) elif isinstance(start_location, int): start_location = SourceLocation.from_offset(self, f, start_location) if hasattr(end_location, '__len__'): end_location = SourceLocation.from_position(self, f, end_location[0], end_location[1]) elif isinstance(end_location, int): end_location = SourceLocation.from_offset(self, f, end_location) assert isinstance(start_location, SourceLocation) assert isinstance(end_location, SourceLocation) return SourceRange.from_locations(start_location, end_location)
[ "def", "get_extent", "(", "self", ",", "filename", ",", "locations", ")", ":", "f", "=", "self", ".", "get_file", "(", "filename", ")", "if", "len", "(", "locations", ")", "<", "2", ":", "raise", "Exception", "(", "'Must pass object with at least 2 elements'", ")", "start_location", ",", "end_location", "=", "locations", "if", "hasattr", "(", "start_location", ",", "'__len__'", ")", ":", "start_location", "=", "SourceLocation", ".", "from_position", "(", "self", ",", "f", ",", "start_location", "[", "0", "]", ",", "start_location", "[", "1", "]", ")", "elif", "isinstance", "(", "start_location", ",", "int", ")", ":", "start_location", "=", "SourceLocation", ".", "from_offset", "(", "self", ",", "f", ",", "start_location", ")", "if", "hasattr", "(", "end_location", ",", "'__len__'", ")", ":", "end_location", "=", "SourceLocation", ".", "from_position", "(", "self", ",", "f", ",", "end_location", "[", "0", "]", ",", "end_location", "[", "1", "]", ")", "elif", "isinstance", "(", "end_location", ",", "int", ")", ":", "end_location", "=", "SourceLocation", ".", "from_offset", "(", "self", ",", "f", ",", "end_location", ")", "assert", "isinstance", "(", "start_location", ",", "SourceLocation", ")", "assert", "isinstance", "(", "end_location", ",", "SourceLocation", ")", "return", "SourceRange", ".", "from_locations", "(", "start_location", ",", "end_location", ")" ]
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. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15)))
[ "Obtain", "a", "SourceRange", "from", "this", "translation", "unit", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2689-L2727
train
235,727
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.reparse
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 to be substituted for the file. The contents may be passed as strings or file objects. """ if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), unsaved_files_array, options)
python
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 to be substituted for the file. The contents may be passed as strings or file objects. """ if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), unsaved_files_array, options)
[ "def", "reparse", "(", "self", ",", "unsaved_files", "=", "None", ",", "options", "=", "0", ")", ":", "if", "unsaved_files", "is", "None", ":", "unsaved_files", "=", "[", "]", "unsaved_files_array", "=", "0", "if", "len", "(", "unsaved_files", ")", ":", "unsaved_files_array", "=", "(", "_CXUnsavedFile", "*", "len", "(", "unsaved_files", ")", ")", "(", ")", "for", "i", ",", "(", "name", ",", "value", ")", "in", "enumerate", "(", "unsaved_files", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "# FIXME: It would be great to support an efficient version", "# of this, one day.", "value", "=", "value", ".", "read", "(", ")", "print", "(", "value", ")", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "'Unexpected unsaved file contents.'", ")", "unsaved_files_array", "[", "i", "]", ".", "name", "=", "name", "unsaved_files_array", "[", "i", "]", ".", "contents", "=", "value", "unsaved_files_array", "[", "i", "]", ".", "length", "=", "len", "(", "value", ")", "ptr", "=", "conf", ".", "lib", ".", "clang_reparseTranslationUnit", "(", "self", ",", "len", "(", "unsaved_files", ")", ",", "unsaved_files_array", ",", "options", ")" ]
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 to be substituted for the file. The contents may be passed as strings or file objects.
[ "Reparse", "an", "already", "parsed", "translation", "unit", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2749-L2776
train
235,728
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.save
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 error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to. """ options = conf.lib.clang_defaultSaveOptions(self) result = int(conf.lib.clang_saveTranslationUnit(self, filename, options)) if result != 0: raise TranslationUnitSaveError(result, 'Error saving TranslationUnit.')
python
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 error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to. """ options = conf.lib.clang_defaultSaveOptions(self) result = int(conf.lib.clang_saveTranslationUnit(self, filename, options)) if result != 0: raise TranslationUnitSaveError(result, 'Error saving TranslationUnit.')
[ "def", "save", "(", "self", ",", "filename", ")", ":", "options", "=", "conf", ".", "lib", ".", "clang_defaultSaveOptions", "(", "self", ")", "result", "=", "int", "(", "conf", ".", "lib", ".", "clang_saveTranslationUnit", "(", "self", ",", "filename", ",", "options", ")", ")", "if", "result", "!=", "0", ":", "raise", "TranslationUnitSaveError", "(", "result", ",", "'Error saving TranslationUnit.'", ")" ]
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 error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to.
[ "Saves", "the", "TranslationUnit", "to", "a", "file", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2778-L2798
train
235,729
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.codeComplete
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 of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ options = 0 if include_macros: options += 1 if include_code_patterns: options += 2 if include_brief_comments: options += 4 if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = c_string_p(name) unsaved_files_array[i].contents = c_string_p(value) unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, unsaved_files_array, len(unsaved_files), options) if ptr: return CodeCompletionResults(ptr) return None
python
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 of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ options = 0 if include_macros: options += 1 if include_code_patterns: options += 2 if include_brief_comments: options += 4 if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = c_string_p(name) unsaved_files_array[i].contents = c_string_p(value) unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, unsaved_files_array, len(unsaved_files), options) if ptr: return CodeCompletionResults(ptr) return None
[ "def", "codeComplete", "(", "self", ",", "path", ",", "line", ",", "column", ",", "unsaved_files", "=", "None", ",", "include_macros", "=", "False", ",", "include_code_patterns", "=", "False", ",", "include_brief_comments", "=", "False", ")", ":", "options", "=", "0", "if", "include_macros", ":", "options", "+=", "1", "if", "include_code_patterns", ":", "options", "+=", "2", "if", "include_brief_comments", ":", "options", "+=", "4", "if", "unsaved_files", "is", "None", ":", "unsaved_files", "=", "[", "]", "unsaved_files_array", "=", "0", "if", "len", "(", "unsaved_files", ")", ":", "unsaved_files_array", "=", "(", "_CXUnsavedFile", "*", "len", "(", "unsaved_files", ")", ")", "(", ")", "for", "i", ",", "(", "name", ",", "value", ")", "in", "enumerate", "(", "unsaved_files", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "# FIXME: It would be great to support an efficient version", "# of this, one day.", "value", "=", "value", ".", "read", "(", ")", "print", "(", "value", ")", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "'Unexpected unsaved file contents.'", ")", "unsaved_files_array", "[", "i", "]", ".", "name", "=", "c_string_p", "(", "name", ")", "unsaved_files_array", "[", "i", "]", ".", "contents", "=", "c_string_p", "(", "value", ")", "unsaved_files_array", "[", "i", "]", ".", "length", "=", "len", "(", "value", ")", "ptr", "=", "conf", ".", "lib", ".", "clang_codeCompleteAt", "(", "self", ",", "path", ",", "line", ",", "column", ",", "unsaved_files_array", ",", "len", "(", "unsaved_files", ")", ",", "options", ")", "if", "ptr", ":", "return", "CodeCompletionResults", "(", "ptr", ")", "return", "None" ]
Code complete in this 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 to be substituted for the file. The contents may be passed as strings or file objects.
[ "Code", "complete", "in", "this", "translation", "unit", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2800-L2843
train
235,730
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
TranslationUnit.get_tokens
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 are defined, behavior is undefined. """ if locations is not None: extent = SourceRange(start=locations[0], end=locations[1]) return TokenGroup.get_tokens(self, extent)
python
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 are defined, behavior is undefined. """ if locations is not None: extent = SourceRange(start=locations[0], end=locations[1]) return TokenGroup.get_tokens(self, extent)
[ "def", "get_tokens", "(", "self", ",", "locations", "=", "None", ",", "extent", "=", "None", ")", ":", "if", "locations", "is", "not", "None", ":", "extent", "=", "SourceRange", "(", "start", "=", "locations", "[", "0", "]", ",", "end", "=", "locations", "[", "1", "]", ")", "return", "TokenGroup", ".", "get_tokens", "(", "self", ",", "extent", ")" ]
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 are defined, behavior is undefined.
[ "Obtain", "tokens", "in", "this", "translation", "unit", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2845-L2856
train
235,731
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
File.name
def name(self): """Return the complete file and path name of the file.""" return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self)))
python
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", "name", "(", "self", ")", ":", "return", "str", "(", "conf", ".", "lib", ".", "clang_getCString", "(", "conf", ".", "lib", ".", "clang_getFileName", "(", "self", ")", ")", ")" ]
Return the complete file and path name of the file.
[ "Return", "the", "complete", "file", "and", "path", "name", "of", "the", "file", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2870-L2872
train
235,732
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
CompileCommand.arguments
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 in xrange(length): yield str(conf.lib.clang_CompileCommand_getArg(self.cmd, i))
python
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 in xrange(length): yield str(conf.lib.clang_CompileCommand_getArg(self.cmd, i))
[ "def", "arguments", "(", "self", ")", ":", "length", "=", "conf", ".", "lib", ".", "clang_CompileCommand_getNumArgs", "(", "self", ".", "cmd", ")", "for", "i", "in", "xrange", "(", "length", ")", ":", "yield", "str", "(", "conf", ".", "lib", ".", "clang_CompileCommand_getArg", "(", "self", ".", "cmd", ",", "i", ")", ")" ]
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
[ "Get", "an", "iterable", "object", "providing", "each", "argument", "in", "the", "command", "line", "for", "the", "compiler", "invocation", "as", "a", "_CXString", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2957-L2966
train
235,733
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
CompilationDatabase.fromDirectory
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: raise CompilationDatabaseError(int(errorCode.value), "CompilationDatabase loading failed") return cdb
python
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: raise CompilationDatabaseError(int(errorCode.value), "CompilationDatabase loading failed") return cdb
[ "def", "fromDirectory", "(", "buildDir", ")", ":", "errorCode", "=", "c_uint", "(", ")", "try", ":", "cdb", "=", "conf", ".", "lib", ".", "clang_CompilationDatabase_fromDirectory", "(", "buildDir", ",", "byref", "(", "errorCode", ")", ")", "except", "CompilationDatabaseError", "as", "e", ":", "raise", "CompilationDatabaseError", "(", "int", "(", "errorCode", ".", "value", ")", ",", "\"CompilationDatabase loading failed\"", ")", "return", "cdb" ]
Builds a CompilationDatabase from the database found in buildDir
[ "Builds", "a", "CompilationDatabase", "from", "the", "database", "found", "in", "buildDir" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L3013-L3022
train
235,734
hotdoc/hotdoc
hotdoc/extensions/gi/node_cache.py
get_klass_parents
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) return res
python
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) return res
[ "def", "get_klass_parents", "(", "gi_name", ")", ":", "res", "=", "[", "]", "parents", "=", "__HIERARCHY_GRAPH", ".", "predecessors", "(", "gi_name", ")", "if", "not", "parents", ":", "return", "[", "]", "__get_parent_link_recurse", "(", "parents", "[", "0", "]", ",", "res", ")", "return", "res" ]
Returns a sorted list of qualified symbols representing the parents of the klass-like symbol named gi_name
[ "Returns", "a", "sorted", "list", "of", "qualified", "symbols", "representing", "the", "parents", "of", "the", "klass", "-", "like", "symbol", "named", "gi_name" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L173-L183
train
235,735
hotdoc/hotdoc
hotdoc/extensions/gi/node_cache.py
get_klass_children
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 = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)]) qs.add_extension_attribute ('gi-extension', 'type_desc', SymbolTypeDesc([], gi_name, ctype_name, 0)) res[ctype_name] = qs return res
python
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 = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)]) qs.add_extension_attribute ('gi-extension', 'type_desc', SymbolTypeDesc([], gi_name, ctype_name, 0)) res[ctype_name] = qs return res
[ "def", "get_klass_children", "(", "gi_name", ")", ":", "res", "=", "{", "}", "children", "=", "__HIERARCHY_GRAPH", ".", "successors", "(", "gi_name", ")", "for", "gi_name", "in", "children", ":", "ctype_name", "=", "ALL_GI_TYPES", "[", "gi_name", "]", "qs", "=", "QualifiedSymbol", "(", "type_tokens", "=", "[", "Link", "(", "None", ",", "ctype_name", ",", "ctype_name", ")", "]", ")", "qs", ".", "add_extension_attribute", "(", "'gi-extension'", ",", "'type_desc'", ",", "SymbolTypeDesc", "(", "[", "]", ",", "gi_name", ",", "ctype_name", ",", "0", ")", ")", "res", "[", "ctype_name", "]", "=", "qs", "return", "res" ]
Returns a dict of qualified symbols representing the children of the klass-like symbol named gi_name
[ "Returns", "a", "dict", "of", "qualified", "symbols", "representing", "the", "children", "of", "the", "klass", "-", "like", "symbol", "named", "gi_name" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L186-L199
train
235,736
hotdoc/hotdoc
hotdoc/extensions/gi/node_cache.py
cache_nodes
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_node.attrib['{%s}symbol-prefixes' % NS_MAP['c']] id_key = '{%s}identifier' % NS_MAP['c'] for node in gir_root.xpath( './/*[@c:identifier]', namespaces=NS_MAP): make_translations (node.attrib[id_key], node) id_type = c_ns('type') glib_type = glib_ns('type-name') class_tag = core_ns('class') callback_tag = core_ns('callback') interface_tag = core_ns('interface') for node in gir_root.xpath('.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]', namespaces=NS_MAP): try: name = node.attrib[id_type] except KeyError: name = node.attrib[glib_type] make_translations (name, node) gi_name = '.'.join(get_gi_name_components(node)) ALL_GI_TYPES[gi_name] = get_klass_name(node) if node.tag in (class_tag, interface_tag): __update_hierarchies (ns_node.attrib.get('name'), node, gi_name) make_translations('%s::%s' % (name, name), node) __generate_smart_filters(id_prefixes, sym_prefixes, node) elif node.tag in (callback_tag,): ALL_CALLBACK_TYPES.add(node.attrib[c_ns('type')]) for field in gir_root.xpath('.//self::core:field', namespaces=NS_MAP): unique_name = get_field_c_name(field) make_translations(unique_name, field) for node in gir_root.xpath( './/core:property', namespaces=NS_MAP): name = '%s:%s' % (get_klass_name(node.getparent()), node.attrib['name']) make_translations (name, node) for node in gir_root.xpath( './/glib:signal', namespaces=NS_MAP): name = '%s::%s' % (get_klass_name(node.getparent()), node.attrib['name']) make_translations (name, node) for node in gir_root.xpath( './/core:virtual-method', namespaces=NS_MAP): name = get_symbol_names(node)[0] make_translations (name, node) for inc in gir_root.findall('./core:include', namespaces = NS_MAP): inc_name = inc.attrib["name"] inc_version = inc.attrib["version"] gir_file = __find_gir_file('%s-%s.gir' % (inc_name, inc_version), all_girs) if not gir_file: warn('missing-gir-include', "Couldn't find a gir for %s-%s.gir" % (inc_name, inc_version)) continue if gir_file in __PARSED_GIRS: continue __PARSED_GIRS.add(gir_file) inc_gir_root = etree.parse(gir_file).getroot() cache_nodes(inc_gir_root, all_girs)
python
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_node.attrib['{%s}symbol-prefixes' % NS_MAP['c']] id_key = '{%s}identifier' % NS_MAP['c'] for node in gir_root.xpath( './/*[@c:identifier]', namespaces=NS_MAP): make_translations (node.attrib[id_key], node) id_type = c_ns('type') glib_type = glib_ns('type-name') class_tag = core_ns('class') callback_tag = core_ns('callback') interface_tag = core_ns('interface') for node in gir_root.xpath('.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]', namespaces=NS_MAP): try: name = node.attrib[id_type] except KeyError: name = node.attrib[glib_type] make_translations (name, node) gi_name = '.'.join(get_gi_name_components(node)) ALL_GI_TYPES[gi_name] = get_klass_name(node) if node.tag in (class_tag, interface_tag): __update_hierarchies (ns_node.attrib.get('name'), node, gi_name) make_translations('%s::%s' % (name, name), node) __generate_smart_filters(id_prefixes, sym_prefixes, node) elif node.tag in (callback_tag,): ALL_CALLBACK_TYPES.add(node.attrib[c_ns('type')]) for field in gir_root.xpath('.//self::core:field', namespaces=NS_MAP): unique_name = get_field_c_name(field) make_translations(unique_name, field) for node in gir_root.xpath( './/core:property', namespaces=NS_MAP): name = '%s:%s' % (get_klass_name(node.getparent()), node.attrib['name']) make_translations (name, node) for node in gir_root.xpath( './/glib:signal', namespaces=NS_MAP): name = '%s::%s' % (get_klass_name(node.getparent()), node.attrib['name']) make_translations (name, node) for node in gir_root.xpath( './/core:virtual-method', namespaces=NS_MAP): name = get_symbol_names(node)[0] make_translations (name, node) for inc in gir_root.findall('./core:include', namespaces = NS_MAP): inc_name = inc.attrib["name"] inc_version = inc.attrib["version"] gir_file = __find_gir_file('%s-%s.gir' % (inc_name, inc_version), all_girs) if not gir_file: warn('missing-gir-include', "Couldn't find a gir for %s-%s.gir" % (inc_name, inc_version)) continue if gir_file in __PARSED_GIRS: continue __PARSED_GIRS.add(gir_file) inc_gir_root = etree.parse(gir_file).getroot() cache_nodes(inc_gir_root, all_girs)
[ "def", "cache_nodes", "(", "gir_root", ",", "all_girs", ")", ":", "ns_node", "=", "gir_root", ".", "find", "(", "'./{%s}namespace'", "%", "NS_MAP", "[", "'core'", "]", ")", "id_prefixes", "=", "ns_node", ".", "attrib", "[", "'{%s}identifier-prefixes'", "%", "NS_MAP", "[", "'c'", "]", "]", "sym_prefixes", "=", "ns_node", ".", "attrib", "[", "'{%s}symbol-prefixes'", "%", "NS_MAP", "[", "'c'", "]", "]", "id_key", "=", "'{%s}identifier'", "%", "NS_MAP", "[", "'c'", "]", "for", "node", "in", "gir_root", ".", "xpath", "(", "'.//*[@c:identifier]'", ",", "namespaces", "=", "NS_MAP", ")", ":", "make_translations", "(", "node", ".", "attrib", "[", "id_key", "]", ",", "node", ")", "id_type", "=", "c_ns", "(", "'type'", ")", "glib_type", "=", "glib_ns", "(", "'type-name'", ")", "class_tag", "=", "core_ns", "(", "'class'", ")", "callback_tag", "=", "core_ns", "(", "'callback'", ")", "interface_tag", "=", "core_ns", "(", "'interface'", ")", "for", "node", "in", "gir_root", ".", "xpath", "(", "'.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]'", ",", "namespaces", "=", "NS_MAP", ")", ":", "try", ":", "name", "=", "node", ".", "attrib", "[", "id_type", "]", "except", "KeyError", ":", "name", "=", "node", ".", "attrib", "[", "glib_type", "]", "make_translations", "(", "name", ",", "node", ")", "gi_name", "=", "'.'", ".", "join", "(", "get_gi_name_components", "(", "node", ")", ")", "ALL_GI_TYPES", "[", "gi_name", "]", "=", "get_klass_name", "(", "node", ")", "if", "node", ".", "tag", "in", "(", "class_tag", ",", "interface_tag", ")", ":", "__update_hierarchies", "(", "ns_node", ".", "attrib", ".", "get", "(", "'name'", ")", ",", "node", ",", "gi_name", ")", "make_translations", "(", "'%s::%s'", "%", "(", "name", ",", "name", ")", ",", "node", ")", "__generate_smart_filters", "(", "id_prefixes", ",", "sym_prefixes", ",", "node", ")", "elif", "node", ".", "tag", "in", "(", "callback_tag", ",", ")", ":", "ALL_CALLBACK_TYPES", ".", "add", "(", "node", ".", "attrib", "[", "c_ns", "(", "'type'", ")", "]", ")", "for", "field", "in", "gir_root", ".", "xpath", "(", "'.//self::core:field'", ",", "namespaces", "=", "NS_MAP", ")", ":", "unique_name", "=", "get_field_c_name", "(", "field", ")", "make_translations", "(", "unique_name", ",", "field", ")", "for", "node", "in", "gir_root", ".", "xpath", "(", "'.//core:property'", ",", "namespaces", "=", "NS_MAP", ")", ":", "name", "=", "'%s:%s'", "%", "(", "get_klass_name", "(", "node", ".", "getparent", "(", ")", ")", ",", "node", ".", "attrib", "[", "'name'", "]", ")", "make_translations", "(", "name", ",", "node", ")", "for", "node", "in", "gir_root", ".", "xpath", "(", "'.//glib:signal'", ",", "namespaces", "=", "NS_MAP", ")", ":", "name", "=", "'%s::%s'", "%", "(", "get_klass_name", "(", "node", ".", "getparent", "(", ")", ")", ",", "node", ".", "attrib", "[", "'name'", "]", ")", "make_translations", "(", "name", ",", "node", ")", "for", "node", "in", "gir_root", ".", "xpath", "(", "'.//core:virtual-method'", ",", "namespaces", "=", "NS_MAP", ")", ":", "name", "=", "get_symbol_names", "(", "node", ")", "[", "0", "]", "make_translations", "(", "name", ",", "node", ")", "for", "inc", "in", "gir_root", ".", "findall", "(", "'./core:include'", ",", "namespaces", "=", "NS_MAP", ")", ":", "inc_name", "=", "inc", ".", "attrib", "[", "\"name\"", "]", "inc_version", "=", "inc", ".", "attrib", "[", "\"version\"", "]", "gir_file", "=", "__find_gir_file", "(", "'%s-%s.gir'", "%", "(", "inc_name", ",", "inc_version", ")", ",", "all_girs", ")", "if", "not", "gir_file", ":", "warn", "(", "'missing-gir-include'", ",", "\"Couldn't find a gir for %s-%s.gir\"", "%", "(", "inc_name", ",", "inc_version", ")", ")", "continue", "if", "gir_file", "in", "__PARSED_GIRS", ":", "continue", "__PARSED_GIRS", ".", "add", "(", "gir_file", ")", "inc_gir_root", "=", "etree", ".", "parse", "(", "gir_file", ")", ".", "getroot", "(", ")", "cache_nodes", "(", "inc_gir_root", ",", "all_girs", ")" ]
Identify and store all the gir symbols the symbols we will document may link to, or be typed with
[ "Identify", "and", "store", "all", "the", "gir", "symbols", "the", "symbols", "we", "will", "document", "may", "link", "to", "or", "be", "typed", "with" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L202-L277
train
235,737
hotdoc/hotdoc
hotdoc/extensions/gi/node_cache.py
type_description_from_node
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: type_tokens = __type_tokens_from_gitype (cur_ns, gi_name) namespaced = '%s.%s' % (cur_ns, gi_name) if namespaced in ALL_GI_TYPES: gi_name = namespaced return SymbolTypeDesc(type_tokens, gi_name, ctype_name, array_nesting)
python
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: type_tokens = __type_tokens_from_gitype (cur_ns, gi_name) namespaced = '%s.%s' % (cur_ns, gi_name) if namespaced in ALL_GI_TYPES: gi_name = namespaced return SymbolTypeDesc(type_tokens, gi_name, ctype_name, array_nesting)
[ "def", "type_description_from_node", "(", "gi_node", ")", ":", "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", ":", "type_tokens", "=", "__type_tokens_from_gitype", "(", "cur_ns", ",", "gi_name", ")", "namespaced", "=", "'%s.%s'", "%", "(", "cur_ns", ",", "gi_name", ")", "if", "namespaced", "in", "ALL_GI_TYPES", ":", "gi_name", "=", "namespaced", "return", "SymbolTypeDesc", "(", "type_tokens", ",", "gi_name", ",", "ctype_name", ",", "array_nesting", ")" ]
Parse a typed node, returns a usable description
[ "Parse", "a", "typed", "node", "returns", "a", "usable", "description" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L318-L335
train
235,738
hotdoc/hotdoc
hotdoc/extensions/gi/node_cache.py
is_introspectable
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
python
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", "is_introspectable", "(", "name", ",", "language", ")", ":", "if", "name", "in", "FUNDAMENTALS", "[", "language", "]", ":", "return", "True", "if", "name", "not", "in", "__TRANSLATED_NAMES", "[", "language", "]", ":", "return", "False", "return", "True" ]
Do not call this before caching the nodes
[ "Do", "not", "call", "this", "before", "caching", "the", "nodes" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L338-L348
train
235,739
hotdoc/hotdoc
hotdoc/core/config.py
Config.get_markdown_files
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.path.splitext(name) if len(split) == 1: continue if split[1] in ('.markdown', '.md', '.yaml'): md_files.add(os.path.join(root, name)) return md_files
python
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.path.splitext(name) if len(split) == 1: continue if split[1] in ('.markdown', '.md', '.yaml'): md_files.add(os.path.join(root, name)) return md_files
[ "def", "get_markdown_files", "(", "self", ",", "dir_", ")", ":", "md_files", "=", "OrderedSet", "(", ")", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "dir_", ")", ":", "for", "name", "in", "files", ":", "split", "=", "os", ".", "path", ".", "splitext", "(", "name", ")", "if", "len", "(", "split", ")", "==", "1", ":", "continue", "if", "split", "[", "1", "]", "in", "(", "'.markdown'", ",", "'.md'", ",", "'.yaml'", ")", ":", "md_files", ".", "add", "(", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", ")", "return", "md_files" ]
Get all the markdown files in a folder, recursively Args: dir_: str, a toplevel folder to walk.
[ "Get", "all", "the", "markdown", "files", "in", "a", "folder", "recursively" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L164-L179
train
235,740
hotdoc/hotdoc
hotdoc/core/config.py
Config.get
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.__cli[key] if key in self.__config: return self.__config.get(key) if key in self.__defaults: return self.__defaults.get(key) return default
python
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.__cli[key] if key in self.__config: return self.__config.get(key) if key in self.__defaults: return self.__defaults.get(key) return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ".", "__cli", ":", "return", "self", ".", "__cli", "[", "key", "]", "if", "key", "in", "self", ".", "__config", ":", "return", "self", ".", "__config", ".", "get", "(", "key", ")", "if", "key", "in", "self", ".", "__defaults", ":", "return", "self", ".", "__defaults", ".", "get", "(", "key", ")", "return", "default" ]
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`
[ "Get", "the", "value", "for", "key", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L187-L205
train
235,741
hotdoc/hotdoc
hotdoc/core/config.py
Config.get_index
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' % prefix else: prefixed = 'index' if prefixed in self.__cli and self.__cli[prefixed]: index = self.__cli.get(prefixed) from_conf = False else: index = self.__config.get(prefixed) from_conf = True return self.__abspath(index, from_conf)
python
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' % prefix else: prefixed = 'index' if prefixed in self.__cli and self.__cli[prefixed]: index = self.__cli.get(prefixed) from_conf = False else: index = self.__config.get(prefixed) from_conf = True return self.__abspath(index, from_conf)
[ "def", "get_index", "(", "self", ",", "prefix", "=", "''", ")", ":", "if", "prefix", ":", "prefixed", "=", "'%s_index'", "%", "prefix", "else", ":", "prefixed", "=", "'index'", "if", "prefixed", "in", "self", ".", "__cli", "and", "self", ".", "__cli", "[", "prefixed", "]", ":", "index", "=", "self", ".", "__cli", ".", "get", "(", "prefixed", ")", "from_conf", "=", "False", "else", ":", "index", "=", "self", ".", "__config", ".", "get", "(", "prefixed", ")", "from_conf", "=", "True", "return", "self", ".", "__abspath", "(", "index", ",", "from_conf", ")" ]
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`
[ "Retrieve", "the", "absolute", "path", "to", "an", "index", "according", "to", "prefix", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L207-L230
train
235,742
hotdoc/hotdoc
hotdoc/core/config.py
Config.get_path
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. Args: key: str, the key to lookup the path with Returns: str: The path, or `None` """ if key in self.__cli: path = self.__cli[key] from_conf = False else: path = self.__config.get(key) from_conf = True if not isinstance(path, str): return None res = self.__abspath(path, from_conf) if rel_to_cwd: return os.path.relpath(res, self.__invoke_dir) if rel_to_conf: return os.path.relpath(res, self.__conf_dir) return self.__abspath(path, from_conf)
python
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. Args: key: str, the key to lookup the path with Returns: str: The path, or `None` """ if key in self.__cli: path = self.__cli[key] from_conf = False else: path = self.__config.get(key) from_conf = True if not isinstance(path, str): return None res = self.__abspath(path, from_conf) if rel_to_cwd: return os.path.relpath(res, self.__invoke_dir) if rel_to_conf: return os.path.relpath(res, self.__conf_dir) return self.__abspath(path, from_conf)
[ "def", "get_path", "(", "self", ",", "key", ",", "rel_to_cwd", "=", "False", ",", "rel_to_conf", "=", "False", ")", ":", "if", "key", "in", "self", ".", "__cli", ":", "path", "=", "self", ".", "__cli", "[", "key", "]", "from_conf", "=", "False", "else", ":", "path", "=", "self", ".", "__config", ".", "get", "(", "key", ")", "from_conf", "=", "True", "if", "not", "isinstance", "(", "path", ",", "str", ")", ":", "return", "None", "res", "=", "self", ".", "__abspath", "(", "path", ",", "from_conf", ")", "if", "rel_to_cwd", ":", "return", "os", ".", "path", ".", "relpath", "(", "res", ",", "self", ".", "__invoke_dir", ")", "if", "rel_to_conf", ":", "return", "os", ".", "path", ".", "relpath", "(", "res", ",", "self", ".", "__conf_dir", ")", "return", "self", ".", "__abspath", "(", "path", ",", "from_conf", ")" ]
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. Args: key: str, the key to lookup the path with Returns: str: The path, or `None`
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L232-L262
train
235,743
hotdoc/hotdoc
hotdoc/core/config.py
Config.get_paths
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] or [] from_conf = False else: paths = self.__config.get(key) or [] from_conf = True for path in flatten_list(paths): final_path = self.__abspath(path, from_conf) if final_path: final_paths.append(final_path) return final_paths
python
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] or [] from_conf = False else: paths = self.__config.get(key) or [] from_conf = True for path in flatten_list(paths): final_path = self.__abspath(path, from_conf) if final_path: final_paths.append(final_path) return final_paths
[ "def", "get_paths", "(", "self", ",", "key", ")", ":", "final_paths", "=", "[", "]", "if", "key", "in", "self", ".", "__cli", ":", "paths", "=", "self", ".", "__cli", "[", "key", "]", "or", "[", "]", "from_conf", "=", "False", "else", ":", "paths", "=", "self", ".", "__config", ".", "get", "(", "key", ")", "or", "[", "]", "from_conf", "=", "True", "for", "path", "in", "flatten_list", "(", "paths", ")", ":", "final_path", "=", "self", ".", "__abspath", "(", "path", ",", "from_conf", ")", "if", "final_path", ":", "final_paths", ".", "append", "(", "final_path", ")", "return", "final_paths" ]
Same as `ConfigParser.get_path` for a list of paths. Args: key: str, the key to lookup the paths with Returns: list: The paths.
[ "Same", "as", "ConfigParser", ".", "get_path", "for", "a", "list", "of", "paths", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L264-L288
train
235,744
hotdoc/hotdoc
hotdoc/core/config.py
Config.get_sources
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 set of sources for the given `prefix`. """ prefix = prefix.replace('-', '_') prefixed = '%s_sources' % prefix if prefixed in self.__cli: sources = self.__cli.get(prefixed) from_conf = False else: sources = self.__config.get(prefixed) from_conf = True if sources is None: return OrderedSet() sources = self.__resolve_patterns(sources, from_conf) prefixed = '%s_source_filters' % prefix if prefixed in self.__cli: filters = self.__cli.get(prefixed) from_conf = False else: filters = self.__config.get(prefixed) from_conf = True if filters is None: return sources sources -= self.__resolve_patterns(filters, from_conf) return sources
python
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 set of sources for the given `prefix`. """ prefix = prefix.replace('-', '_') prefixed = '%s_sources' % prefix if prefixed in self.__cli: sources = self.__cli.get(prefixed) from_conf = False else: sources = self.__config.get(prefixed) from_conf = True if sources is None: return OrderedSet() sources = self.__resolve_patterns(sources, from_conf) prefixed = '%s_source_filters' % prefix if prefixed in self.__cli: filters = self.__cli.get(prefixed) from_conf = False else: filters = self.__config.get(prefixed) from_conf = True if filters is None: return sources sources -= self.__resolve_patterns(filters, from_conf) return sources
[ "def", "get_sources", "(", "self", ",", "prefix", "=", "''", ")", ":", "prefix", "=", "prefix", ".", "replace", "(", "'-'", ",", "'_'", ")", "prefixed", "=", "'%s_sources'", "%", "prefix", "if", "prefixed", "in", "self", ".", "__cli", ":", "sources", "=", "self", ".", "__cli", ".", "get", "(", "prefixed", ")", "from_conf", "=", "False", "else", ":", "sources", "=", "self", ".", "__config", ".", "get", "(", "prefixed", ")", "from_conf", "=", "True", "if", "sources", "is", "None", ":", "return", "OrderedSet", "(", ")", "sources", "=", "self", ".", "__resolve_patterns", "(", "sources", ",", "from_conf", ")", "prefixed", "=", "'%s_source_filters'", "%", "prefix", "if", "prefixed", "in", "self", ".", "__cli", ":", "filters", "=", "self", ".", "__cli", ".", "get", "(", "prefixed", ")", "from_conf", "=", "False", "else", ":", "filters", "=", "self", ".", "__config", ".", "get", "(", "prefixed", ")", "from_conf", "=", "True", "if", "filters", "is", "None", ":", "return", "sources", "sources", "-=", "self", ".", "__resolve_patterns", "(", "filters", ",", "from_conf", ")", "return", "sources" ]
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 set of sources for the given `prefix`.
[ "Retrieve", "a", "set", "of", "absolute", "paths", "to", "sources", "according", "to", "prefix" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L290-L332
train
235,745
hotdoc/hotdoc
hotdoc/core/config.py
Config.get_dependencies
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.__config.items()): if key in self.__cli: continue if key.endswith('sources'): all_deps |= self.get_sources(key[:len('sources') * -1 - 1]) for key, _ in list(self.__cli.items()): if key.endswith('sources'): all_deps |= self.get_sources(key[:len('sources') * -1 - 1]) if self.conf_file is not None: all_deps.add(self.conf_file) all_deps.add(self.get_path("sitemap", rel_to_cwd=True)) cwd = os.getcwd() return [os.path.relpath(fname, cwd) for fname in all_deps if fname]
python
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.__config.items()): if key in self.__cli: continue if key.endswith('sources'): all_deps |= self.get_sources(key[:len('sources') * -1 - 1]) for key, _ in list(self.__cli.items()): if key.endswith('sources'): all_deps |= self.get_sources(key[:len('sources') * -1 - 1]) if self.conf_file is not None: all_deps.add(self.conf_file) all_deps.add(self.get_path("sitemap", rel_to_cwd=True)) cwd = os.getcwd() return [os.path.relpath(fname, cwd) for fname in all_deps if fname]
[ "def", "get_dependencies", "(", "self", ")", ":", "all_deps", "=", "OrderedSet", "(", ")", "for", "key", ",", "_", "in", "list", "(", "self", ".", "__config", ".", "items", "(", ")", ")", ":", "if", "key", "in", "self", ".", "__cli", ":", "continue", "if", "key", ".", "endswith", "(", "'sources'", ")", ":", "all_deps", "|=", "self", ".", "get_sources", "(", "key", "[", ":", "len", "(", "'sources'", ")", "*", "-", "1", "-", "1", "]", ")", "for", "key", ",", "_", "in", "list", "(", "self", ".", "__cli", ".", "items", "(", ")", ")", ":", "if", "key", ".", "endswith", "(", "'sources'", ")", ":", "all_deps", "|=", "self", ".", "get_sources", "(", "key", "[", ":", "len", "(", "'sources'", ")", "*", "-", "1", "-", "1", "]", ")", "if", "self", ".", "conf_file", "is", "not", "None", ":", "all_deps", ".", "add", "(", "self", ".", "conf_file", ")", "all_deps", ".", "add", "(", "self", ".", "get_path", "(", "\"sitemap\"", ",", "rel_to_cwd", "=", "True", ")", ")", "cwd", "=", "os", ".", "getcwd", "(", ")", "return", "[", "os", ".", "path", ".", "relpath", "(", "fname", ",", "cwd", ")", "for", "fname", "in", "all_deps", "if", "fname", "]" ]
Retrieve the set of all dependencies for a given configuration. Returns: utils.utils.OrderedSet: The set of all dependencies for the tracked configuration.
[ "Retrieve", "the", "set", "of", "all", "dependencies", "for", "a", "given", "configuration", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L334-L360
train
235,746
hotdoc/hotdoc
hotdoc/core/config.py
Config.dump
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 not conf_dir: conf_dir = self.__invoke_dir elif not os.path.exists(conf_dir): os.makedirs(conf_dir) else: conf_dir = self.__conf_dir final_conf = {} for key, value in list(self.__config.items()): if key in self.__cli: continue final_conf[key] = value for key, value in list(self.__cli.items()): if key.endswith('index') or key in ['sitemap', 'output']: path = self.__abspath(value, from_conf=False) if path: relpath = os.path.relpath(path, conf_dir) final_conf[key] = relpath elif key.endswith('sources') or key.endswith('source_filters'): new_list = [] for path in value: path = self.__abspath(path, from_conf=False) if path: relpath = os.path.relpath(path, conf_dir) new_list.append(relpath) final_conf[key] = new_list elif key not in ['command', 'output_conf_file']: final_conf[key] = value with open(conf_file or self.conf_file or 'hotdoc.json', 'w') as _: _.write(json.dumps(final_conf, sort_keys=True, indent=4))
python
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 not conf_dir: conf_dir = self.__invoke_dir elif not os.path.exists(conf_dir): os.makedirs(conf_dir) else: conf_dir = self.__conf_dir final_conf = {} for key, value in list(self.__config.items()): if key in self.__cli: continue final_conf[key] = value for key, value in list(self.__cli.items()): if key.endswith('index') or key in ['sitemap', 'output']: path = self.__abspath(value, from_conf=False) if path: relpath = os.path.relpath(path, conf_dir) final_conf[key] = relpath elif key.endswith('sources') or key.endswith('source_filters'): new_list = [] for path in value: path = self.__abspath(path, from_conf=False) if path: relpath = os.path.relpath(path, conf_dir) new_list.append(relpath) final_conf[key] = new_list elif key not in ['command', 'output_conf_file']: final_conf[key] = value with open(conf_file or self.conf_file or 'hotdoc.json', 'w') as _: _.write(json.dumps(final_conf, sort_keys=True, indent=4))
[ "def", "dump", "(", "self", ",", "conf_file", "=", "None", ")", ":", "if", "conf_file", ":", "conf_dir", "=", "os", ".", "path", ".", "dirname", "(", "conf_file", ")", "if", "not", "conf_dir", ":", "conf_dir", "=", "self", ".", "__invoke_dir", "elif", "not", "os", ".", "path", ".", "exists", "(", "conf_dir", ")", ":", "os", ".", "makedirs", "(", "conf_dir", ")", "else", ":", "conf_dir", "=", "self", ".", "__conf_dir", "final_conf", "=", "{", "}", "for", "key", ",", "value", "in", "list", "(", "self", ".", "__config", ".", "items", "(", ")", ")", ":", "if", "key", "in", "self", ".", "__cli", ":", "continue", "final_conf", "[", "key", "]", "=", "value", "for", "key", ",", "value", "in", "list", "(", "self", ".", "__cli", ".", "items", "(", ")", ")", ":", "if", "key", ".", "endswith", "(", "'index'", ")", "or", "key", "in", "[", "'sitemap'", ",", "'output'", "]", ":", "path", "=", "self", ".", "__abspath", "(", "value", ",", "from_conf", "=", "False", ")", "if", "path", ":", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "conf_dir", ")", "final_conf", "[", "key", "]", "=", "relpath", "elif", "key", ".", "endswith", "(", "'sources'", ")", "or", "key", ".", "endswith", "(", "'source_filters'", ")", ":", "new_list", "=", "[", "]", "for", "path", "in", "value", ":", "path", "=", "self", ".", "__abspath", "(", "path", ",", "from_conf", "=", "False", ")", "if", "path", ":", "relpath", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "conf_dir", ")", "new_list", ".", "append", "(", "relpath", ")", "final_conf", "[", "key", "]", "=", "new_list", "elif", "key", "not", "in", "[", "'command'", ",", "'output_conf_file'", "]", ":", "final_conf", "[", "key", "]", "=", "value", "with", "open", "(", "conf_file", "or", "self", ".", "conf_file", "or", "'hotdoc.json'", ",", "'w'", ")", "as", "_", ":", "_", ".", "write", "(", "json", ".", "dumps", "(", "final_conf", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", ")" ]
Dump the possibly updated config to a file. Args: conf_file: str, the destination, or None to overwrite the existing configuration.
[ "Dump", "the", "possibly", "updated", "config", "to", "a", "file", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L363-L405
train
235,747
hotdoc/hotdoc
hotdoc/utils/setup_utils.py
_update_submodules
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)
python
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", "_update_submodules", "(", "repo_dir", ")", ":", "subprocess", ".", "check_call", "(", "\"git submodule init\"", ",", "cwd", "=", "repo_dir", ",", "shell", "=", "True", ")", "subprocess", ".", "check_call", "(", "\"git submodule update --recursive\"", ",", "cwd", "=", "repo_dir", ",", "shell", "=", "True", ")" ]
update submodules in a repo
[ "update", "submodules", "in", "a", "repo" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L75-L79
train
235,748
hotdoc/hotdoc
hotdoc/utils/setup_utils.py
require_clean_submodules
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 git submodules # don't do anything if nothing is actually supposed to happen for do_nothing in ( '-h', '--help', '--help-commands', 'clean', 'submodule'): if do_nothing in sys.argv: return status = _check_submodule_status(repo_root, submodules) if status == "missing": print("checking out submodules for the first time") _update_submodules(repo_root) elif status == "unclean": print(UNCLEAN_SUBMODULES_MSG)
python
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 git submodules # don't do anything if nothing is actually supposed to happen for do_nothing in ( '-h', '--help', '--help-commands', 'clean', 'submodule'): if do_nothing in sys.argv: return status = _check_submodule_status(repo_root, submodules) if status == "missing": print("checking out submodules for the first time") _update_submodules(repo_root) elif status == "unclean": print(UNCLEAN_SUBMODULES_MSG)
[ "def", "require_clean_submodules", "(", "repo_root", ",", "submodules", ")", ":", "# PACKAGERS: Add a return here to skip checks for git submodules", "# don't do anything if nothing is actually supposed to happen", "for", "do_nothing", "in", "(", "'-h'", ",", "'--help'", ",", "'--help-commands'", ",", "'clean'", ",", "'submodule'", ")", ":", "if", "do_nothing", "in", "sys", ".", "argv", ":", "return", "status", "=", "_check_submodule_status", "(", "repo_root", ",", "submodules", ")", "if", "status", "==", "\"missing\"", ":", "print", "(", "\"checking out submodules for the first time\"", ")", "_update_submodules", "(", "repo_root", ")", "elif", "status", "==", "\"unclean\"", ":", "print", "(", "UNCLEAN_SUBMODULES_MSG", ")" ]
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.
[ "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", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L93-L113
train
235,749
hotdoc/hotdoc
hotdoc/utils/setup_utils.py
symlink
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: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte flags = 1 if os.path.isdir(source) else 0 if csl(link_name, source, flags) == 0: raise ctypes.WinError()
python
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: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte flags = 1 if os.path.isdir(source) else 0 if csl(link_name, source, flags) == 0: raise ctypes.WinError()
[ "def", "symlink", "(", "source", ",", "link_name", ")", ":", "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", ":", "import", "ctypes", "csl", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "CreateSymbolicLinkW", "csl", ".", "argtypes", "=", "(", "ctypes", ".", "c_wchar_p", ",", "ctypes", ".", "c_wchar_p", ",", "ctypes", ".", "c_uint32", ")", "csl", ".", "restype", "=", "ctypes", ".", "c_ubyte", "flags", "=", "1", "if", "os", ".", "path", ".", "isdir", "(", "source", ")", "else", "0", "if", "csl", "(", "link_name", ",", "source", ",", "flags", ")", "==", "0", ":", "raise", "ctypes", ".", "WinError", "(", ")" ]
Method to allow creating symlinks on Windows
[ "Method", "to", "allow", "creating", "symlinks", "on", "Windows" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L116-L133
train
235,750
hotdoc/hotdoc
hotdoc/utils/setup_utils.py
pkgconfig
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) returns e.g. {'extra_compile_args': [], 'extra_link_args': [], 'include_dirs': ['/usr/include/ffmpeg'], 'libraries': ['avformat'], 'library_dirs': []} Intended use: distutils.core.Extension('pyextension', sources=['source.cpp'], **c) Set PKG_CONFIG_PATH environment variable for nonstandard library locations. based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/) """ config = kw.setdefault('config', {}) optional_args = kw.setdefault('optional', '') # { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...} flag_map = {'include_dirs': ['--cflags-only-I', 2], 'library_dirs': ['--libs-only-L', 2], 'libraries': ['--libs-only-l', 2], 'extra_compile_args': ['--cflags-only-other', 0], 'extra_link_args': ['--libs-only-other', 0], } for package in packages: for distutils_key, (pkg_option, n) in flag_map.items(): items = subprocess.check_output(['pkg-config', optional_args, pkg_option, package]).decode('utf8').split() config.setdefault(distutils_key, []).extend([i[n:] for i in items]) return config
python
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) returns e.g. {'extra_compile_args': [], 'extra_link_args': [], 'include_dirs': ['/usr/include/ffmpeg'], 'libraries': ['avformat'], 'library_dirs': []} Intended use: distutils.core.Extension('pyextension', sources=['source.cpp'], **c) Set PKG_CONFIG_PATH environment variable for nonstandard library locations. based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/) """ config = kw.setdefault('config', {}) optional_args = kw.setdefault('optional', '') # { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...} flag_map = {'include_dirs': ['--cflags-only-I', 2], 'library_dirs': ['--libs-only-L', 2], 'libraries': ['--libs-only-l', 2], 'extra_compile_args': ['--cflags-only-other', 0], 'extra_link_args': ['--libs-only-other', 0], } for package in packages: for distutils_key, (pkg_option, n) in flag_map.items(): items = subprocess.check_output(['pkg-config', optional_args, pkg_option, package]).decode('utf8').split() config.setdefault(distutils_key, []).extend([i[n:] for i in items]) return config
[ "def", "pkgconfig", "(", "*", "packages", ",", "*", "*", "kw", ")", ":", "config", "=", "kw", ".", "setdefault", "(", "'config'", ",", "{", "}", ")", "optional_args", "=", "kw", ".", "setdefault", "(", "'optional'", ",", "''", ")", "# { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...}", "flag_map", "=", "{", "'include_dirs'", ":", "[", "'--cflags-only-I'", ",", "2", "]", ",", "'library_dirs'", ":", "[", "'--libs-only-L'", ",", "2", "]", ",", "'libraries'", ":", "[", "'--libs-only-l'", ",", "2", "]", ",", "'extra_compile_args'", ":", "[", "'--cflags-only-other'", ",", "0", "]", ",", "'extra_link_args'", ":", "[", "'--libs-only-other'", ",", "0", "]", ",", "}", "for", "package", "in", "packages", ":", "for", "distutils_key", ",", "(", "pkg_option", ",", "n", ")", "in", "flag_map", ".", "items", "(", ")", ":", "items", "=", "subprocess", ".", "check_output", "(", "[", "'pkg-config'", ",", "optional_args", ",", "pkg_option", ",", "package", "]", ")", ".", "decode", "(", "'utf8'", ")", ".", "split", "(", ")", "config", ".", "setdefault", "(", "distutils_key", ",", "[", "]", ")", ".", "extend", "(", "[", "i", "[", "n", ":", "]", "for", "i", "in", "items", "]", ")", "return", "config" ]
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) returns e.g. {'extra_compile_args': [], 'extra_link_args': [], 'include_dirs': ['/usr/include/ffmpeg'], 'libraries': ['avformat'], 'library_dirs': []} Intended use: distutils.core.Extension('pyextension', sources=['source.cpp'], **c) Set PKG_CONFIG_PATH environment variable for nonstandard library locations. based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/)
[ "Query", "pkg", "-", "config", "for", "library", "compile", "and", "linking", "options", ".", "Return", "configuration", "in", "distutils", "Extension", "format", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L135-L180
train
235,751
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.register_error_code
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)
python
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_error_code", "(", "code", ",", "exception_type", ",", "domain", "=", "'core'", ")", ":", "Logger", ".", "_error_code_to_exception", "[", "code", "]", "=", "(", "exception_type", ",", "domain", ")", "Logger", ".", "_domain_codes", "[", "domain", "]", ".", "add", "(", "code", ")" ]
Register a new error code
[ "Register", "a", "new", "error", "code" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L201-L204
train
235,752
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.register_warning_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)
python
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", "register_warning_code", "(", "code", ",", "exception_type", ",", "domain", "=", "'core'", ")", ":", "Logger", ".", "_warning_code_to_exception", "[", "code", "]", "=", "(", "exception_type", ",", "domain", ")", "Logger", ".", "_domain_codes", "[", "domain", "]", ".", "add", "(", "code", ")" ]
Register a new warning code
[ "Register", "a", "new", "warning", "code" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L207-L210
train
235,753
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger._log
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)
python
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", "_log", "(", "code", ",", "message", ",", "level", ",", "domain", ")", ":", "entry", "=", "LogEntry", "(", "level", ",", "domain", ",", "code", ",", "message", ")", "Logger", ".", "journal", ".", "append", "(", "entry", ")", "if", "Logger", ".", "silent", ":", "return", "if", "level", ">=", "Logger", ".", "_verbosity", ":", "_print_entry", "(", "entry", ")" ]
Call this to add an entry in the journal
[ "Call", "this", "to", "add", "an", "entry", "in", "the", "journal" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L213-L222
train
235,754
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.error
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, ERROR, domain) raise exc
python
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, ERROR, domain) raise exc
[ "def", "error", "(", "code", ",", "message", ",", "*", "*", "kwargs", ")", ":", "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", ",", "ERROR", ",", "domain", ")", "raise", "exc" ]
Call this to raise an exception and have it stored in the journal
[ "Call", "this", "to", "raise", "an", "exception", "and", "have", "it", "stored", "in", "the", "journal" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L225-L231
train
235,755
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.warn
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 = Logger._warning_code_to_exception[code] if domain in Logger._ignored_domains: return level = WARNING if Logger.fatal_warnings: level = ERROR exc = exc_type(message, **kwargs) Logger._log(code, exc.message, level, domain) if Logger.fatal_warnings: raise exc
python
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 = Logger._warning_code_to_exception[code] if domain in Logger._ignored_domains: return level = WARNING if Logger.fatal_warnings: level = ERROR exc = exc_type(message, **kwargs) Logger._log(code, exc.message, level, domain) if Logger.fatal_warnings: raise exc
[ "def", "warn", "(", "code", ",", "message", ",", "*", "*", "kwargs", ")", ":", "if", "code", "in", "Logger", ".", "_ignored_codes", ":", "return", "assert", "code", "in", "Logger", ".", "_warning_code_to_exception", "exc_type", ",", "domain", "=", "Logger", ".", "_warning_code_to_exception", "[", "code", "]", "if", "domain", "in", "Logger", ".", "_ignored_domains", ":", "return", "level", "=", "WARNING", "if", "Logger", ".", "fatal_warnings", ":", "level", "=", "ERROR", "exc", "=", "exc_type", "(", "message", ",", "*", "*", "kwargs", ")", "Logger", ".", "_log", "(", "code", ",", "exc", ".", "message", ",", "level", ",", "domain", ")", "if", "Logger", ".", "fatal_warnings", ":", "raise", "exc" ]
Call this to store a warning in the journal. Will raise if `Logger.fatal_warnings` is set to True.
[ "Call", "this", "to", "store", "a", "warning", "in", "the", "journal", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L234-L259
train
235,756
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.debug
def debug(message, domain): """Log debugging information""" if domain in Logger._ignored_domains: return Logger._log(None, message, DEBUG, domain)
python
def debug(message, domain): """Log debugging information""" if domain in Logger._ignored_domains: return Logger._log(None, message, DEBUG, domain)
[ "def", "debug", "(", "message", ",", "domain", ")", ":", "if", "domain", "in", "Logger", ".", "_ignored_domains", ":", "return", "Logger", ".", "_log", "(", "None", ",", "message", ",", "DEBUG", ",", "domain", ")" ]
Log debugging information
[ "Log", "debugging", "information" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L262-L267
train
235,757
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.info
def info(message, domain): """Log simple info""" if domain in Logger._ignored_domains: return Logger._log(None, message, INFO, domain)
python
def info(message, domain): """Log simple info""" if domain in Logger._ignored_domains: return Logger._log(None, message, INFO, domain)
[ "def", "info", "(", "message", ",", "domain", ")", ":", "if", "domain", "in", "Logger", ".", "_ignored_domains", ":", "return", "Logger", ".", "_log", "(", "None", ",", "message", ",", "INFO", ",", "domain", ")" ]
Log simple info
[ "Log", "simple", "info" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L270-L275
train
235,758
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.get_issues
def get_issues(): """Get actual issues in the journal.""" issues = [] for entry in Logger.journal: if entry.level >= WARNING: issues.append(entry) return issues
python
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", "get_issues", "(", ")", ":", "issues", "=", "[", "]", "for", "entry", "in", "Logger", ".", "journal", ":", "if", "entry", ".", "level", ">=", "WARNING", ":", "issues", ".", "append", "(", "entry", ")", "return", "issues" ]
Get actual issues in the journal.
[ "Get", "actual", "issues", "in", "the", "journal", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L298-L304
train
235,759
hotdoc/hotdoc
hotdoc/utils/loggable.py
Logger.reset
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
python
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", "reset", "(", ")", ":", "Logger", ".", "journal", "=", "[", "]", "Logger", ".", "fatal_warnings", "=", "False", "Logger", ".", "_ignored_codes", "=", "set", "(", ")", "Logger", ".", "_ignored_domains", "=", "set", "(", ")", "Logger", ".", "_verbosity", "=", "2", "Logger", ".", "_last_checkpoint", "=", "0" ]
Resets Logger to its initial state
[ "Resets", "Logger", "to", "its", "initial", "state" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L307-L314
train
235,760
hotdoc/hotdoc
hotdoc/parsers/sitemap.py
Sitemap.walk
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. """ action(self.index_file, self.__root, 0, user_data) self.__do_walk(self.__root, 1, action, user_data)
python
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. """ action(self.index_file, self.__root, 0, user_data) self.__do_walk(self.__root, 1, action, user_data)
[ "def", "walk", "(", "self", ",", "action", ",", "user_data", "=", "None", ")", ":", "action", "(", "self", ".", "index_file", ",", "self", ".", "__root", ",", "0", ",", "user_data", ")", "self", ".", "__do_walk", "(", "self", ".", "__root", ",", "1", ",", "action", ",", "user_data", ")" ]
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.
[ "Walk", "the", "hierarchy", "applying", "action", "to", "each", "filename", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/sitemap.py#L77-L87
train
235,761
hotdoc/hotdoc
hotdoc/parsers/sitemap.py
SitemapParser.parse
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() all_source_files = set() source_map = {} lineno = 0 root = None index = None cur_level = -1 parent_queue = [] for line in lines: try: level, line = dedent(line) if line.startswith('#'): lineno += 1 continue elif line.startswith('\\#'): line = line[1:] except IndentError as exc: error('bad-indent', 'Invalid indentation', filename=filename, lineno=lineno, column=exc.column) if not line: lineno += 1 continue source_file = dequote(line) if not source_file: lineno += 1 continue if source_file in all_source_files: error('sitemap-duplicate', 'Filename listed twice', filename=filename, lineno=lineno, column=level * 8 + 1) all_source_files.add(source_file) source_map[source_file] = (lineno, level * 8 + 1) page = OrderedDict() if root is not None and level == 0: error('sitemap-error', 'Sitemaps only support one root', filename=filename, lineno=lineno, column=0) if root is None: root = page index = source_file else: lvl_diff = cur_level - level while lvl_diff >= 0: parent_queue.pop() lvl_diff -= 1 parent_queue[-1][source_file] = page parent_queue.append(page) cur_level = level lineno += 1 return Sitemap(root, filename, index, source_map)
python
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() all_source_files = set() source_map = {} lineno = 0 root = None index = None cur_level = -1 parent_queue = [] for line in lines: try: level, line = dedent(line) if line.startswith('#'): lineno += 1 continue elif line.startswith('\\#'): line = line[1:] except IndentError as exc: error('bad-indent', 'Invalid indentation', filename=filename, lineno=lineno, column=exc.column) if not line: lineno += 1 continue source_file = dequote(line) if not source_file: lineno += 1 continue if source_file in all_source_files: error('sitemap-duplicate', 'Filename listed twice', filename=filename, lineno=lineno, column=level * 8 + 1) all_source_files.add(source_file) source_map[source_file] = (lineno, level * 8 + 1) page = OrderedDict() if root is not None and level == 0: error('sitemap-error', 'Sitemaps only support one root', filename=filename, lineno=lineno, column=0) if root is None: root = page index = source_file else: lvl_diff = cur_level - level while lvl_diff >= 0: parent_queue.pop() lvl_diff -= 1 parent_queue[-1][source_file] = page parent_queue.append(page) cur_level = level lineno += 1 return Sitemap(root, filename, index, source_map)
[ "def", "parse", "(", "self", ",", "filename", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "_", ":", "lines", "=", "_", ".", "readlines", "(", ")", "all_source_files", "=", "set", "(", ")", "source_map", "=", "{", "}", "lineno", "=", "0", "root", "=", "None", "index", "=", "None", "cur_level", "=", "-", "1", "parent_queue", "=", "[", "]", "for", "line", "in", "lines", ":", "try", ":", "level", ",", "line", "=", "dedent", "(", "line", ")", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "lineno", "+=", "1", "continue", "elif", "line", ".", "startswith", "(", "'\\\\#'", ")", ":", "line", "=", "line", "[", "1", ":", "]", "except", "IndentError", "as", "exc", ":", "error", "(", "'bad-indent'", ",", "'Invalid indentation'", ",", "filename", "=", "filename", ",", "lineno", "=", "lineno", ",", "column", "=", "exc", ".", "column", ")", "if", "not", "line", ":", "lineno", "+=", "1", "continue", "source_file", "=", "dequote", "(", "line", ")", "if", "not", "source_file", ":", "lineno", "+=", "1", "continue", "if", "source_file", "in", "all_source_files", ":", "error", "(", "'sitemap-duplicate'", ",", "'Filename listed twice'", ",", "filename", "=", "filename", ",", "lineno", "=", "lineno", ",", "column", "=", "level", "*", "8", "+", "1", ")", "all_source_files", ".", "add", "(", "source_file", ")", "source_map", "[", "source_file", "]", "=", "(", "lineno", ",", "level", "*", "8", "+", "1", ")", "page", "=", "OrderedDict", "(", ")", "if", "root", "is", "not", "None", "and", "level", "==", "0", ":", "error", "(", "'sitemap-error'", ",", "'Sitemaps only support one root'", ",", "filename", "=", "filename", ",", "lineno", "=", "lineno", ",", "column", "=", "0", ")", "if", "root", "is", "None", ":", "root", "=", "page", "index", "=", "source_file", "else", ":", "lvl_diff", "=", "cur_level", "-", "level", "while", "lvl_diff", ">=", "0", ":", "parent_queue", ".", "pop", "(", ")", "lvl_diff", "-=", "1", "parent_queue", "[", "-", "1", "]", "[", "source_file", "]", "=", "page", "parent_queue", ".", "append", "(", "page", ")", "cur_level", "=", "level", "lineno", "+=", "1", "return", "Sitemap", "(", "root", ",", "filename", ",", "index", ",", "source_map", ")" ]
Parse a sitemap file. Args: filename: str, the path to the sitemap file. Returns: Sitemap: the generated sitemap.
[ "Parse", "a", "sitemap", "file", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/sitemap.py#L144-L218
train
235,762
hotdoc/hotdoc
hotdoc/parsers/gtk_doc.py
GtkDocParser.parse_comment
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 column_offset = 0 raw_comment = comment if not stripped: try: while comment[column_offset * -1 - 1] != '\n': column_offset += 1 except IndexError: column_offset = 0 comment, title_offset = self.__strip_comment(comment) title_and_params, description = self.__extract_titles_params_and_description(comment) try: block_name, parameters, annotations, is_section = \ self.__parse_title_and_parameters(filename, title_and_params) except HotdocSourceException as _: warn('gtk-doc-bad-syntax', message=_.message, filename=filename, lineno=lineno + title_offset) return None params_offset = 0 for param in parameters: param.filename = filename param.lineno = lineno param_offset = param.line_offset param.line_offset = title_offset + params_offset + 1 params_offset += param_offset param.col_offset = column_offset if not block_name: return None description_offset = 0 meta = {} tags = [] if description is not None: n_lines = len(comment.split('\n')) description_offset = (title_offset + n_lines - len(description.split('\n'))) meta['description'], tags = self.__parse_description_and_tags(description) actual_parameters = OrderedDict({}) for param in parameters: if is_section: cleaned_up_name = param.name.lower().replace('_', '-') if cleaned_up_name in ['symbols', 'private-symbols', 'auto-sort', 'sources']: meta.update(self.__parse_yaml_comment(param, filename)) if cleaned_up_name == 'sources': sources_paths = [os.path.abspath(os.path.join(os.path.dirname(filename), path)) for path in meta[cleaned_up_name]] meta[cleaned_up_name] = sources_paths else: meta[param.name] = param.description else: actual_parameters[param.name] = param annotations = {annotation.name: annotation for annotation in annotations} tags = {tag.name.lower(): tag for tag in tags} block = Comment(name=block_name, filename=filename, lineno=lineno, endlineno=endlineno, annotations=annotations, params=actual_parameters, tags=tags, raw_comment=raw_comment, meta=meta, toplevel=is_section) block.line_offset = description_offset block.col_offset = column_offset return block
python
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 column_offset = 0 raw_comment = comment if not stripped: try: while comment[column_offset * -1 - 1] != '\n': column_offset += 1 except IndexError: column_offset = 0 comment, title_offset = self.__strip_comment(comment) title_and_params, description = self.__extract_titles_params_and_description(comment) try: block_name, parameters, annotations, is_section = \ self.__parse_title_and_parameters(filename, title_and_params) except HotdocSourceException as _: warn('gtk-doc-bad-syntax', message=_.message, filename=filename, lineno=lineno + title_offset) return None params_offset = 0 for param in parameters: param.filename = filename param.lineno = lineno param_offset = param.line_offset param.line_offset = title_offset + params_offset + 1 params_offset += param_offset param.col_offset = column_offset if not block_name: return None description_offset = 0 meta = {} tags = [] if description is not None: n_lines = len(comment.split('\n')) description_offset = (title_offset + n_lines - len(description.split('\n'))) meta['description'], tags = self.__parse_description_and_tags(description) actual_parameters = OrderedDict({}) for param in parameters: if is_section: cleaned_up_name = param.name.lower().replace('_', '-') if cleaned_up_name in ['symbols', 'private-symbols', 'auto-sort', 'sources']: meta.update(self.__parse_yaml_comment(param, filename)) if cleaned_up_name == 'sources': sources_paths = [os.path.abspath(os.path.join(os.path.dirname(filename), path)) for path in meta[cleaned_up_name]] meta[cleaned_up_name] = sources_paths else: meta[param.name] = param.description else: actual_parameters[param.name] = param annotations = {annotation.name: annotation for annotation in annotations} tags = {tag.name.lower(): tag for tag in tags} block = Comment(name=block_name, filename=filename, lineno=lineno, endlineno=endlineno, annotations=annotations, params=actual_parameters, tags=tags, raw_comment=raw_comment, meta=meta, toplevel=is_section) block.line_offset = description_offset block.col_offset = column_offset return block
[ "def", "parse_comment", "(", "self", ",", "comment", ",", "filename", ",", "lineno", ",", "endlineno", ",", "include_paths", "=", "None", ",", "stripped", "=", "False", ")", ":", "if", "not", "stripped", "and", "not", "self", ".", "__validate_c_comment", "(", "comment", ".", "strip", "(", ")", ")", ":", "return", "None", "title_offset", "=", "0", "column_offset", "=", "0", "raw_comment", "=", "comment", "if", "not", "stripped", ":", "try", ":", "while", "comment", "[", "column_offset", "*", "-", "1", "-", "1", "]", "!=", "'\\n'", ":", "column_offset", "+=", "1", "except", "IndexError", ":", "column_offset", "=", "0", "comment", ",", "title_offset", "=", "self", ".", "__strip_comment", "(", "comment", ")", "title_and_params", ",", "description", "=", "self", ".", "__extract_titles_params_and_description", "(", "comment", ")", "try", ":", "block_name", ",", "parameters", ",", "annotations", ",", "is_section", "=", "self", ".", "__parse_title_and_parameters", "(", "filename", ",", "title_and_params", ")", "except", "HotdocSourceException", "as", "_", ":", "warn", "(", "'gtk-doc-bad-syntax'", ",", "message", "=", "_", ".", "message", ",", "filename", "=", "filename", ",", "lineno", "=", "lineno", "+", "title_offset", ")", "return", "None", "params_offset", "=", "0", "for", "param", "in", "parameters", ":", "param", ".", "filename", "=", "filename", "param", ".", "lineno", "=", "lineno", "param_offset", "=", "param", ".", "line_offset", "param", ".", "line_offset", "=", "title_offset", "+", "params_offset", "+", "1", "params_offset", "+=", "param_offset", "param", ".", "col_offset", "=", "column_offset", "if", "not", "block_name", ":", "return", "None", "description_offset", "=", "0", "meta", "=", "{", "}", "tags", "=", "[", "]", "if", "description", "is", "not", "None", ":", "n_lines", "=", "len", "(", "comment", ".", "split", "(", "'\\n'", ")", ")", "description_offset", "=", "(", "title_offset", "+", "n_lines", "-", "len", "(", "description", ".", "split", "(", "'\\n'", ")", ")", ")", "meta", "[", "'description'", "]", ",", "tags", "=", "self", ".", "__parse_description_and_tags", "(", "description", ")", "actual_parameters", "=", "OrderedDict", "(", "{", "}", ")", "for", "param", "in", "parameters", ":", "if", "is_section", ":", "cleaned_up_name", "=", "param", ".", "name", ".", "lower", "(", ")", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "cleaned_up_name", "in", "[", "'symbols'", ",", "'private-symbols'", ",", "'auto-sort'", ",", "'sources'", "]", ":", "meta", ".", "update", "(", "self", ".", "__parse_yaml_comment", "(", "param", ",", "filename", ")", ")", "if", "cleaned_up_name", "==", "'sources'", ":", "sources_paths", "=", "[", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "path", ")", ")", "for", "path", "in", "meta", "[", "cleaned_up_name", "]", "]", "meta", "[", "cleaned_up_name", "]", "=", "sources_paths", "else", ":", "meta", "[", "param", ".", "name", "]", "=", "param", ".", "description", "else", ":", "actual_parameters", "[", "param", ".", "name", "]", "=", "param", "annotations", "=", "{", "annotation", ".", "name", ":", "annotation", "for", "annotation", "in", "annotations", "}", "tags", "=", "{", "tag", ".", "name", ".", "lower", "(", ")", ":", "tag", "for", "tag", "in", "tags", "}", "block", "=", "Comment", "(", "name", "=", "block_name", ",", "filename", "=", "filename", ",", "lineno", "=", "lineno", ",", "endlineno", "=", "endlineno", ",", "annotations", "=", "annotations", ",", "params", "=", "actual_parameters", ",", "tags", "=", "tags", ",", "raw_comment", "=", "raw_comment", ",", "meta", "=", "meta", ",", "toplevel", "=", "is_section", ")", "block", ".", "line_offset", "=", "description_offset", "block", ".", "col_offset", "=", "column_offset", "return", "block" ]
Returns a Comment given a string
[ "Returns", "a", "Comment", "given", "a", "string" ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L303-L382
train
235,763
hotdoc/hotdoc
hotdoc/parsers/gtk_doc.py
GtkDocStringFormatter.comment_to_ast
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 discovery and most of the link resolution being lazily done in that second phase. If you don't care about performance, you should simply use `translate`. Args: text: unicode, the docstring to parse. link_resolver: hotdoc.core.links.LinkResolver, an object which will be called to retrieve `hotdoc.core.links.Link` objects. Returns: capsule: A PyCapsule wrapping an opaque C pointer, which can be passed to `ast_to_html` afterwards. diagnostics: A list of diagnostics as output by the gtk-doc cmark extension """ assert comment is not None text = comment.description if (self.remove_xml_tags or comment.filename in self.gdbus_codegen_sources): text = re.sub('<.*?>', '', text) if self.escape_html: # pylint: disable=deprecated-method text = cgi.escape(text) ast, diagnostics = cmark.gtkdoc_to_ast(text, link_resolver) for diag in diagnostics: if (comment.filename and comment.filename not in self.gdbus_codegen_sources): column = diag.column + comment.col_offset if diag.lineno == 0: column += comment.initial_col_offset lines = text.split('\n') line = lines[diag.lineno] i = 0 while line[i] == ' ': i += 1 column += i - 1 if diag.lineno > 0 and any([c != ' ' for c in lines[diag.lineno - 1]]): column += 1 lineno = -1 if comment.lineno != -1: lineno = (comment.lineno - 1 + comment.line_offset + diag.lineno) warn( diag.code, message=diag.message, filename=comment.filename, lineno=lineno, column=column) return ast
python
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 discovery and most of the link resolution being lazily done in that second phase. If you don't care about performance, you should simply use `translate`. Args: text: unicode, the docstring to parse. link_resolver: hotdoc.core.links.LinkResolver, an object which will be called to retrieve `hotdoc.core.links.Link` objects. Returns: capsule: A PyCapsule wrapping an opaque C pointer, which can be passed to `ast_to_html` afterwards. diagnostics: A list of diagnostics as output by the gtk-doc cmark extension """ assert comment is not None text = comment.description if (self.remove_xml_tags or comment.filename in self.gdbus_codegen_sources): text = re.sub('<.*?>', '', text) if self.escape_html: # pylint: disable=deprecated-method text = cgi.escape(text) ast, diagnostics = cmark.gtkdoc_to_ast(text, link_resolver) for diag in diagnostics: if (comment.filename and comment.filename not in self.gdbus_codegen_sources): column = diag.column + comment.col_offset if diag.lineno == 0: column += comment.initial_col_offset lines = text.split('\n') line = lines[diag.lineno] i = 0 while line[i] == ' ': i += 1 column += i - 1 if diag.lineno > 0 and any([c != ' ' for c in lines[diag.lineno - 1]]): column += 1 lineno = -1 if comment.lineno != -1: lineno = (comment.lineno - 1 + comment.line_offset + diag.lineno) warn( diag.code, message=diag.message, filename=comment.filename, lineno=lineno, column=column) return ast
[ "def", "comment_to_ast", "(", "self", ",", "comment", ",", "link_resolver", ")", ":", "assert", "comment", "is", "not", "None", "text", "=", "comment", ".", "description", "if", "(", "self", ".", "remove_xml_tags", "or", "comment", ".", "filename", "in", "self", ".", "gdbus_codegen_sources", ")", ":", "text", "=", "re", ".", "sub", "(", "'<.*?>'", ",", "''", ",", "text", ")", "if", "self", ".", "escape_html", ":", "# pylint: disable=deprecated-method", "text", "=", "cgi", ".", "escape", "(", "text", ")", "ast", ",", "diagnostics", "=", "cmark", ".", "gtkdoc_to_ast", "(", "text", ",", "link_resolver", ")", "for", "diag", "in", "diagnostics", ":", "if", "(", "comment", ".", "filename", "and", "comment", ".", "filename", "not", "in", "self", ".", "gdbus_codegen_sources", ")", ":", "column", "=", "diag", ".", "column", "+", "comment", ".", "col_offset", "if", "diag", ".", "lineno", "==", "0", ":", "column", "+=", "comment", ".", "initial_col_offset", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "line", "=", "lines", "[", "diag", ".", "lineno", "]", "i", "=", "0", "while", "line", "[", "i", "]", "==", "' '", ":", "i", "+=", "1", "column", "+=", "i", "-", "1", "if", "diag", ".", "lineno", ">", "0", "and", "any", "(", "[", "c", "!=", "' '", "for", "c", "in", "lines", "[", "diag", ".", "lineno", "-", "1", "]", "]", ")", ":", "column", "+=", "1", "lineno", "=", "-", "1", "if", "comment", ".", "lineno", "!=", "-", "1", ":", "lineno", "=", "(", "comment", ".", "lineno", "-", "1", "+", "comment", ".", "line_offset", "+", "diag", ".", "lineno", ")", "warn", "(", "diag", ".", "code", ",", "message", "=", "diag", ".", "message", ",", "filename", "=", "comment", ".", "filename", ",", "lineno", "=", "lineno", ",", "column", "=", "column", ")", "return", "ast" ]
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 discovery and most of the link resolution being lazily done in that second phase. If you don't care about performance, you should simply use `translate`. Args: text: unicode, the docstring to parse. link_resolver: hotdoc.core.links.LinkResolver, an object which will be called to retrieve `hotdoc.core.links.Link` objects. Returns: capsule: A PyCapsule wrapping an opaque C pointer, which can be passed to `ast_to_html` afterwards. diagnostics: A list of diagnostics as output by the gtk-doc cmark extension
[ "Given", "a", "gtk", "-", "doc", "comment", "string", "returns", "an", "opaque", "PyCapsule", "containing", "the", "document", "root", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L396-L464
train
235,764
hotdoc/hotdoc
hotdoc/parsers/gtk_doc.py
GtkDocStringFormatter.ast_to_html
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. """ out, _ = cmark.ast_to_html(ast, link_resolver) return out
python
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. """ out, _ = cmark.ast_to_html(ast, link_resolver) return out
[ "def", "ast_to_html", "(", "self", ",", "ast", ",", "link_resolver", ")", ":", "out", ",", "_", "=", "cmark", ".", "ast_to_html", "(", "ast", ",", "link_resolver", ")", "return", "out" ]
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.
[ "See", "the", "documentation", "of", "to_ast", "for", "more", "information", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L467-L478
train
235,765
hotdoc/hotdoc
hotdoc/parsers/gtk_doc.py
GtkDocStringFormatter.translate_comment
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 += self.ast_to_html(ast, link_resolver) return out
python
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 += self.ast_to_html(ast, link_resolver) return out
[ "def", "translate_comment", "(", "self", ",", "comment", ",", "link_resolver", ")", ":", "out", "=", "u''", "self", ".", "translate_tags", "(", "comment", ",", "link_resolver", ")", "ast", "=", "self", ".", "comment_to_ast", "(", "comment", ",", "link_resolver", ")", "out", "+=", "self", ".", "ast_to_html", "(", "ast", ",", "link_resolver", ")", "return", "out" ]
Given a gtk-doc comment string, returns the comment translated to the desired format.
[ "Given", "a", "gtk", "-", "doc", "comment", "string", "returns", "the", "comment", "translated", "to", "the", "desired", "format", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L480-L490
train
235,766
hotdoc/hotdoc
hotdoc/core/comment.py
comment_from_tag
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.description}, annotations=tag.annotations) return comment
python
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.description}, annotations=tag.annotations) return comment
[ "def", "comment_from_tag", "(", "tag", ")", ":", "if", "not", "tag", ":", "return", "None", "comment", "=", "Comment", "(", "name", "=", "tag", ".", "name", ",", "meta", "=", "{", "'description'", ":", "tag", ".", "description", "}", ",", "annotations", "=", "tag", ".", "annotations", ")", "return", "comment" ]
Convenience function to create a full-fledged comment for a given tag, for example it is convenient to assign a Comment to a ReturnValueSymbol.
[ "Convenience", "function", "to", "create", "a", "full", "-", "fledged", "comment", "for", "a", "given", "tag", "for", "example", "it", "is", "convenient", "to", "assign", "a", "Comment", "to", "a", "ReturnValueSymbol", "." ]
1067cdc8482b585b364a38fb52ca5d904e486280
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/comment.py#L159-L170
train
235,767
tcalmant/python-javaobj
javaobj/modifiedutf8.py
decoder
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. :param data: a string of bytes in Modified UTF-8 encoding. :return: a generator producing a string of unicode characters :raises UnicodeDecodeError: unrecognised byte in sequence encountered. """ def next_byte(_it, start, count): try: return next(_it)[1] except StopIteration: raise UnicodeDecodeError( NAME, data, start, start + count, "incomplete byte sequence" ) it = iter(enumerate(data)) for i, d in it: if d == 0x00: # 00000000 raise UnicodeDecodeError( NAME, data, i, i + 1, "embedded zero-byte not allowed" ) elif d & 0x80: # 1xxxxxxx if d & 0x40: # 11xxxxxx if d & 0x20: # 111xxxxx if d & 0x10: # 1111xxxx raise UnicodeDecodeError( NAME, data, i, i + 1, "invalid encoding character" ) elif d == 0xED: value = 0 for i1, dm in enumerate(DECODE_MAP[6]): d1 = next_byte(it, i, i1 + 1) value = dm.apply(d1, value, data, i, i1 + 1) else: # 1110xxxx value = d & 0x0F for i1, dm in enumerate(DECODE_MAP[3]): d1 = next_byte(it, i, i1 + 1) value = dm.apply(d1, value, data, i, i1 + 1) else: # 110xxxxx value = d & 0x1F for i1, dm in enumerate(DECODE_MAP[2]): d1 = next_byte(it, i, i1 + 1) value = dm.apply(d1, value, data, i, i1 + 1) else: # 10xxxxxx raise UnicodeDecodeError( NAME, data, i, i + 1, "misplaced continuation character" ) else: # 0xxxxxxx value = d # noinspection PyCompatibility yield mutf8_unichr(value)
python
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. :param data: a string of bytes in Modified UTF-8 encoding. :return: a generator producing a string of unicode characters :raises UnicodeDecodeError: unrecognised byte in sequence encountered. """ def next_byte(_it, start, count): try: return next(_it)[1] except StopIteration: raise UnicodeDecodeError( NAME, data, start, start + count, "incomplete byte sequence" ) it = iter(enumerate(data)) for i, d in it: if d == 0x00: # 00000000 raise UnicodeDecodeError( NAME, data, i, i + 1, "embedded zero-byte not allowed" ) elif d & 0x80: # 1xxxxxxx if d & 0x40: # 11xxxxxx if d & 0x20: # 111xxxxx if d & 0x10: # 1111xxxx raise UnicodeDecodeError( NAME, data, i, i + 1, "invalid encoding character" ) elif d == 0xED: value = 0 for i1, dm in enumerate(DECODE_MAP[6]): d1 = next_byte(it, i, i1 + 1) value = dm.apply(d1, value, data, i, i1 + 1) else: # 1110xxxx value = d & 0x0F for i1, dm in enumerate(DECODE_MAP[3]): d1 = next_byte(it, i, i1 + 1) value = dm.apply(d1, value, data, i, i1 + 1) else: # 110xxxxx value = d & 0x1F for i1, dm in enumerate(DECODE_MAP[2]): d1 = next_byte(it, i, i1 + 1) value = dm.apply(d1, value, data, i, i1 + 1) else: # 10xxxxxx raise UnicodeDecodeError( NAME, data, i, i + 1, "misplaced continuation character" ) else: # 0xxxxxxx value = d # noinspection PyCompatibility yield mutf8_unichr(value)
[ "def", "decoder", "(", "data", ")", ":", "def", "next_byte", "(", "_it", ",", "start", ",", "count", ")", ":", "try", ":", "return", "next", "(", "_it", ")", "[", "1", "]", "except", "StopIteration", ":", "raise", "UnicodeDecodeError", "(", "NAME", ",", "data", ",", "start", ",", "start", "+", "count", ",", "\"incomplete byte sequence\"", ")", "it", "=", "iter", "(", "enumerate", "(", "data", ")", ")", "for", "i", ",", "d", "in", "it", ":", "if", "d", "==", "0x00", ":", "# 00000000", "raise", "UnicodeDecodeError", "(", "NAME", ",", "data", ",", "i", ",", "i", "+", "1", ",", "\"embedded zero-byte not allowed\"", ")", "elif", "d", "&", "0x80", ":", "# 1xxxxxxx", "if", "d", "&", "0x40", ":", "# 11xxxxxx", "if", "d", "&", "0x20", ":", "# 111xxxxx", "if", "d", "&", "0x10", ":", "# 1111xxxx", "raise", "UnicodeDecodeError", "(", "NAME", ",", "data", ",", "i", ",", "i", "+", "1", ",", "\"invalid encoding character\"", ")", "elif", "d", "==", "0xED", ":", "value", "=", "0", "for", "i1", ",", "dm", "in", "enumerate", "(", "DECODE_MAP", "[", "6", "]", ")", ":", "d1", "=", "next_byte", "(", "it", ",", "i", ",", "i1", "+", "1", ")", "value", "=", "dm", ".", "apply", "(", "d1", ",", "value", ",", "data", ",", "i", ",", "i1", "+", "1", ")", "else", ":", "# 1110xxxx", "value", "=", "d", "&", "0x0F", "for", "i1", ",", "dm", "in", "enumerate", "(", "DECODE_MAP", "[", "3", "]", ")", ":", "d1", "=", "next_byte", "(", "it", ",", "i", ",", "i1", "+", "1", ")", "value", "=", "dm", ".", "apply", "(", "d1", ",", "value", ",", "data", ",", "i", ",", "i1", "+", "1", ")", "else", ":", "# 110xxxxx", "value", "=", "d", "&", "0x1F", "for", "i1", ",", "dm", "in", "enumerate", "(", "DECODE_MAP", "[", "2", "]", ")", ":", "d1", "=", "next_byte", "(", "it", ",", "i", ",", "i1", "+", "1", ")", "value", "=", "dm", ".", "apply", "(", "d1", ",", "value", ",", "data", ",", "i", ",", "i1", "+", "1", ")", "else", ":", "# 10xxxxxx", "raise", "UnicodeDecodeError", "(", "NAME", ",", "data", ",", "i", ",", "i", "+", "1", ",", "\"misplaced continuation character\"", ")", "else", ":", "# 0xxxxxxx", "value", "=", "d", "# noinspection PyCompatibility", "yield", "mutf8_unichr", "(", "value", ")" ]
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. :param data: a string of bytes in Modified UTF-8 encoding. :return: a generator producing a string of unicode characters :raises UnicodeDecodeError: unrecognised byte in sequence encountered.
[ "This", "generator", "processes", "a", "sequence", "of", "bytes", "in", "Modified", "UTF", "-", "8", "encoding", "and", "produces", "a", "sequence", "of", "unicode", "string", "characters", "." ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/modifiedutf8.py#L103-L160
train
235,768
tcalmant/python-javaobj
javaobj/modifiedutf8.py
decode_modified_utf8
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 :return: unicode text and length :raises UnicodeDecodeError: sequence is invalid. """ value, length = u"", 0 it = iter(decoder(data)) while True: try: value += next(it) length += 1 except StopIteration: break except UnicodeDecodeError as e: if errors == "strict": raise e elif errors == "ignore": pass elif errors == "replace": value += u"\uFFFD" length += 1 return value, length
python
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 :return: unicode text and length :raises UnicodeDecodeError: sequence is invalid. """ value, length = u"", 0 it = iter(decoder(data)) while True: try: value += next(it) length += 1 except StopIteration: break except UnicodeDecodeError as e: if errors == "strict": raise e elif errors == "ignore": pass elif errors == "replace": value += u"\uFFFD" length += 1 return value, length
[ "def", "decode_modified_utf8", "(", "data", ",", "errors", "=", "\"strict\"", ")", ":", "value", ",", "length", "=", "u\"\"", ",", "0", "it", "=", "iter", "(", "decoder", "(", "data", ")", ")", "while", "True", ":", "try", ":", "value", "+=", "next", "(", "it", ")", "length", "+=", "1", "except", "StopIteration", ":", "break", "except", "UnicodeDecodeError", "as", "e", ":", "if", "errors", "==", "\"strict\"", ":", "raise", "e", "elif", "errors", "==", "\"ignore\"", ":", "pass", "elif", "errors", "==", "\"replace\"", ":", "value", "+=", "u\"\\uFFFD\"", "length", "+=", "1", "return", "value", ",", "length" ]
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 :return: unicode text and length :raises UnicodeDecodeError: sequence is invalid.
[ "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", "." ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/modifiedutf8.py#L163-L190
train
235,769
tcalmant/python-javaobj
javaobj/modifiedutf8.py
DecodeMap.apply
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 buffer, (array of bytes). :param i: The position within the data buffer. :param count: The position of this comparison. :return: A new value with the bits merged in. :raises UnicodeDecodeError: if marked bits don't match. """ if byte & self.mask == self.value: value <<= self.bits value |= byte & self.mask2 else: raise UnicodeDecodeError( NAME, data, i, i + count, "invalid {}-byte sequence".format(self.count) ) return value
python
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 buffer, (array of bytes). :param i: The position within the data buffer. :param count: The position of this comparison. :return: A new value with the bits merged in. :raises UnicodeDecodeError: if marked bits don't match. """ if byte & self.mask == self.value: value <<= self.bits value |= byte & self.mask2 else: raise UnicodeDecodeError( NAME, data, i, i + count, "invalid {}-byte sequence".format(self.count) ) return value
[ "def", "apply", "(", "self", ",", "byte", ",", "value", ",", "data", ",", "i", ",", "count", ")", ":", "if", "byte", "&", "self", ".", "mask", "==", "self", ".", "value", ":", "value", "<<=", "self", ".", "bits", "value", "|=", "byte", "&", "self", ".", "mask2", "else", ":", "raise", "UnicodeDecodeError", "(", "NAME", ",", "data", ",", "i", ",", "i", "+", "count", ",", "\"invalid {}-byte sequence\"", ".", "format", "(", "self", ".", "count", ")", ")", "return", "value" ]
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 buffer, (array of bytes). :param i: The position within the data buffer. :param count: The position of this comparison. :return: A new value with the bits merged in. :raises UnicodeDecodeError: if marked bits don't match.
[ "Apply", "mask", "compare", "to", "expected", "value", "shift", "and", "return", "result", ".", "Eventually", "this", "could", "become", "a", "reduce", "function", "." ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/modifiedutf8.py#L55-L75
train
235,770
tcalmant/python-javaobj
javaobj/core.py
load
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 an error when unused trailing bytes are remaining :return: The deserialized object """ # Read keyword argument ignore_remaining_data = kwargs.get("ignore_remaining_data", False) marshaller = JavaObjectUnmarshaller( file_object, kwargs.get("use_numpy_arrays", False) ) # Add custom transformers first for transformer in transformers: marshaller.add_transformer(transformer) marshaller.add_transformer(DefaultObjectTransformer()) # Read the file object return marshaller.readObject(ignore_remaining_data=ignore_remaining_data)
python
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 an error when unused trailing bytes are remaining :return: The deserialized object """ # Read keyword argument ignore_remaining_data = kwargs.get("ignore_remaining_data", False) marshaller = JavaObjectUnmarshaller( file_object, kwargs.get("use_numpy_arrays", False) ) # Add custom transformers first for transformer in transformers: marshaller.add_transformer(transformer) marshaller.add_transformer(DefaultObjectTransformer()) # Read the file object return marshaller.readObject(ignore_remaining_data=ignore_remaining_data)
[ "def", "load", "(", "file_object", ",", "*", "transformers", ",", "*", "*", "kwargs", ")", ":", "# Read keyword argument", "ignore_remaining_data", "=", "kwargs", ".", "get", "(", "\"ignore_remaining_data\"", ",", "False", ")", "marshaller", "=", "JavaObjectUnmarshaller", "(", "file_object", ",", "kwargs", ".", "get", "(", "\"use_numpy_arrays\"", ",", "False", ")", ")", "# Add custom transformers first", "for", "transformer", "in", "transformers", ":", "marshaller", ".", "add_transformer", "(", "transformer", ")", "marshaller", ".", "add_transformer", "(", "DefaultObjectTransformer", "(", ")", ")", "# Read the file object", "return", "marshaller", ".", "readObject", "(", "ignore_remaining_data", "=", "ignore_remaining_data", ")" ]
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 an error when unused trailing bytes are remaining :return: The deserialized object
[ "Deserializes", "Java", "primitive", "data", "and", "objects", "serialized", "using", "ObjectOutputStream", "from", "a", "file", "-", "like", "object", "." ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L101-L125
train
235,771
tcalmant/python-javaobj
javaobj/core.py
loads
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 trailing bytes are remaining :return: The deserialized object """ # Read keyword argument ignore_remaining_data = kwargs.get("ignore_remaining_data", False) # Reuse the load method (avoid code duplication) return load( BytesIO(string), *transformers, ignore_remaining_data=ignore_remaining_data )
python
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 trailing bytes are remaining :return: The deserialized object """ # Read keyword argument ignore_remaining_data = kwargs.get("ignore_remaining_data", False) # Reuse the load method (avoid code duplication) return load( BytesIO(string), *transformers, ignore_remaining_data=ignore_remaining_data )
[ "def", "loads", "(", "string", ",", "*", "transformers", ",", "*", "*", "kwargs", ")", ":", "# Read keyword argument", "ignore_remaining_data", "=", "kwargs", ".", "get", "(", "\"ignore_remaining_data\"", ",", "False", ")", "# Reuse the load method (avoid code duplication)", "return", "load", "(", "BytesIO", "(", "string", ")", ",", "*", "transformers", ",", "ignore_remaining_data", "=", "ignore_remaining_data", ")" ]
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 trailing bytes are remaining :return: The deserialized object
[ "Deserializes", "Java", "objects", "and", "primitive", "data", "serialized", "using", "ObjectOutputStream", "from", "a", "string", "." ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L128-L145
train
235,772
tcalmant/python-javaobj
javaobj/core.py
read
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_str) return struct.unpack(fmt_str, data[:size]), data[size:]
python
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_str) return struct.unpack(fmt_str, data[:size]), data[size:]
[ "def", "read", "(", "data", ",", "fmt_str", ")", ":", "size", "=", "struct", ".", "calcsize", "(", "fmt_str", ")", "return", "struct", ".", "unpack", "(", "fmt_str", ",", "data", "[", ":", "size", "]", ")", ",", "data", "[", "size", ":", "]" ]
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)
[ "Reads", "input", "bytes", "and", "extract", "the", "given", "structure", ".", "Returns", "both", "the", "read", "elements", "and", "the", "remaining", "data" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1666-L1676
train
235,773
tcalmant/python-javaobj
javaobj/core.py
OpCodeDebug.flags
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_CONSTANT.items() if key & flags ) return ", ".join(names)
python
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_CONSTANT.items() if key & flags ) return ", ".join(names)
[ "def", "flags", "(", "flags", ")", ":", "names", "=", "sorted", "(", "descr", "for", "key", ",", "descr", "in", "OpCodeDebug", ".", "STREAM_CONSTANT", ".", "items", "(", ")", "if", "key", "&", "flags", ")", "return", "\", \"", ".", "join", "(", "names", ")" ]
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
[ "Returns", "the", "names", "of", "the", "class", "description", "flags", "found", "in", "the", "given", "integer" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L457-L468
train
235,774
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller._readStreamHeader
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: raise IOError( "The stream is not java serialized object. " "Invalid stream header: {0:04X}{1:04X}".format(magic, version) )
python
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: raise IOError( "The stream is not java serialized object. " "Invalid stream header: {0:04X}{1:04X}".format(magic, version) )
[ "def", "_readStreamHeader", "(", "self", ")", ":", "(", "magic", ",", "version", ")", "=", "self", ".", "_readStruct", "(", "\">HH\"", ")", "if", "magic", "!=", "self", ".", "STREAM_MAGIC", "or", "version", "!=", "self", ".", "STREAM_VERSION", ":", "raise", "IOError", "(", "\"The stream is not java serialized object. \"", "\"Invalid stream header: {0:04X}{1:04X}\"", ".", "format", "(", "magic", ",", "version", ")", ")" ]
Reads the magic header of a Java serialization stream :raise IOError: Invalid magic header (not a Java stream)
[ "Reads", "the", "magic", "header", "of", "a", "Java", "serialization", "stream" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L559-L570
train
235,775
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller._read_and_exec_opcode
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 one of the expected ones :raise RuntimeError: Unknown opcode """ position = self.object_stream.tell() (opid,) = self._readStruct(">B") log_debug( "OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})".format( opid, OpCodeDebug.op_id(opid), position ), ident, ) if expect and opid not in expect: raise IOError( "Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})".format( opid, OpCodeDebug.op_id(opid), position ) ) try: handler = self.opmap[opid] except KeyError: raise RuntimeError( "Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})".format( opid, position ) ) else: return opid, handler(ident=ident)
python
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 one of the expected ones :raise RuntimeError: Unknown opcode """ position = self.object_stream.tell() (opid,) = self._readStruct(">B") log_debug( "OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})".format( opid, OpCodeDebug.op_id(opid), position ), ident, ) if expect and opid not in expect: raise IOError( "Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})".format( opid, OpCodeDebug.op_id(opid), position ) ) try: handler = self.opmap[opid] except KeyError: raise RuntimeError( "Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})".format( opid, position ) ) else: return opid, handler(ident=ident)
[ "def", "_read_and_exec_opcode", "(", "self", ",", "ident", "=", "0", ",", "expect", "=", "None", ")", ":", "position", "=", "self", ".", "object_stream", ".", "tell", "(", ")", "(", "opid", ",", ")", "=", "self", ".", "_readStruct", "(", "\">B\"", ")", "log_debug", "(", "\"OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})\"", ".", "format", "(", "opid", ",", "OpCodeDebug", ".", "op_id", "(", "opid", ")", ",", "position", ")", ",", "ident", ",", ")", "if", "expect", "and", "opid", "not", "in", "expect", ":", "raise", "IOError", "(", "\"Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})\"", ".", "format", "(", "opid", ",", "OpCodeDebug", ".", "op_id", "(", "opid", ")", ",", "position", ")", ")", "try", ":", "handler", "=", "self", ".", "opmap", "[", "opid", "]", "except", "KeyError", ":", "raise", "RuntimeError", "(", "\"Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})\"", ".", "format", "(", "opid", ",", "position", ")", ")", "else", ":", "return", "opid", ",", "handler", "(", "ident", "=", "ident", ")" ]
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 one of the expected ones :raise RuntimeError: Unknown opcode
[ "Reads", "the", "next", "opcode", "and", "executes", "its", "handler" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L572-L607
train
235,776
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller.do_string
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) return ba
python
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) return ba
[ "def", "do_string", "(", "self", ",", "parent", "=", "None", ",", "ident", "=", "0", ")", ":", "log_debug", "(", "\"[string]\"", ",", "ident", ")", "ba", "=", "JavaString", "(", "self", ".", "_readString", "(", ")", ")", "self", ".", "_add_reference", "(", "ba", ",", "ident", ")", "return", "ba" ]
Handles a TC_STRING opcode :param parent: :param ident: Log indentation level :return: A string
[ "Handles", "a", "TC_STRING", "opcode" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L941-L952
train
235,777
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller.do_array
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) _, classdesc = self._read_and_exec_opcode( ident=ident + 1, expect=( self.TC_CLASSDESC, self.TC_PROXYCLASSDESC, self.TC_NULL, self.TC_REFERENCE, ), ) array = JavaArray(classdesc) self._add_reference(array, ident) (size,) = self._readStruct(">i") log_debug("size: {0}".format(size), ident) type_char = classdesc.name[0] assert type_char == self.TYPE_ARRAY type_char = classdesc.name[1] if type_char == self.TYPE_OBJECT or type_char == self.TYPE_ARRAY: for _ in range(size): _, res = self._read_and_exec_opcode(ident=ident + 1) log_debug("Object value: {0}".format(res), ident) array.append(res) elif type_char == self.TYPE_BYTE: array = JavaByteArray(self.object_stream.read(size), classdesc) elif self.use_numpy_arrays: import numpy array = numpy.fromfile( self.object_stream, dtype=JavaObjectConstants.NUMPY_TYPE_MAP[type_char], count=size, ) else: for _ in range(size): res = self._read_value(type_char, ident) log_debug("Native value: {0}".format(repr(res)), ident) array.append(res) return array
python
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) _, classdesc = self._read_and_exec_opcode( ident=ident + 1, expect=( self.TC_CLASSDESC, self.TC_PROXYCLASSDESC, self.TC_NULL, self.TC_REFERENCE, ), ) array = JavaArray(classdesc) self._add_reference(array, ident) (size,) = self._readStruct(">i") log_debug("size: {0}".format(size), ident) type_char = classdesc.name[0] assert type_char == self.TYPE_ARRAY type_char = classdesc.name[1] if type_char == self.TYPE_OBJECT or type_char == self.TYPE_ARRAY: for _ in range(size): _, res = self._read_and_exec_opcode(ident=ident + 1) log_debug("Object value: {0}".format(res), ident) array.append(res) elif type_char == self.TYPE_BYTE: array = JavaByteArray(self.object_stream.read(size), classdesc) elif self.use_numpy_arrays: import numpy array = numpy.fromfile( self.object_stream, dtype=JavaObjectConstants.NUMPY_TYPE_MAP[type_char], count=size, ) else: for _ in range(size): res = self._read_value(type_char, ident) log_debug("Native value: {0}".format(repr(res)), ident) array.append(res) return array
[ "def", "do_array", "(", "self", ",", "parent", "=", "None", ",", "ident", "=", "0", ")", ":", "# TC_ARRAY classDesc newHandle (int)<size> values[size]", "log_debug", "(", "\"[array]\"", ",", "ident", ")", "_", ",", "classdesc", "=", "self", ".", "_read_and_exec_opcode", "(", "ident", "=", "ident", "+", "1", ",", "expect", "=", "(", "self", ".", "TC_CLASSDESC", ",", "self", ".", "TC_PROXYCLASSDESC", ",", "self", ".", "TC_NULL", ",", "self", ".", "TC_REFERENCE", ",", ")", ",", ")", "array", "=", "JavaArray", "(", "classdesc", ")", "self", ".", "_add_reference", "(", "array", ",", "ident", ")", "(", "size", ",", ")", "=", "self", ".", "_readStruct", "(", "\">i\"", ")", "log_debug", "(", "\"size: {0}\"", ".", "format", "(", "size", ")", ",", "ident", ")", "type_char", "=", "classdesc", ".", "name", "[", "0", "]", "assert", "type_char", "==", "self", ".", "TYPE_ARRAY", "type_char", "=", "classdesc", ".", "name", "[", "1", "]", "if", "type_char", "==", "self", ".", "TYPE_OBJECT", "or", "type_char", "==", "self", ".", "TYPE_ARRAY", ":", "for", "_", "in", "range", "(", "size", ")", ":", "_", ",", "res", "=", "self", ".", "_read_and_exec_opcode", "(", "ident", "=", "ident", "+", "1", ")", "log_debug", "(", "\"Object value: {0}\"", ".", "format", "(", "res", ")", ",", "ident", ")", "array", ".", "append", "(", "res", ")", "elif", "type_char", "==", "self", ".", "TYPE_BYTE", ":", "array", "=", "JavaByteArray", "(", "self", ".", "object_stream", ".", "read", "(", "size", ")", ",", "classdesc", ")", "elif", "self", ".", "use_numpy_arrays", ":", "import", "numpy", "array", "=", "numpy", ".", "fromfile", "(", "self", ".", "object_stream", ",", "dtype", "=", "JavaObjectConstants", ".", "NUMPY_TYPE_MAP", "[", "type_char", "]", ",", "count", "=", "size", ",", ")", "else", ":", "for", "_", "in", "range", "(", "size", ")", ":", "res", "=", "self", ".", "_read_value", "(", "type_char", ",", "ident", ")", "log_debug", "(", "\"Native value: {0}\"", ".", "format", "(", "repr", "(", "res", ")", ")", ",", "ident", ")", "array", ".", "append", "(", "res", ")", "return", "array" ]
Handles a TC_ARRAY opcode :param parent: :param ident: Log indentation level :return: A list of deserialized objects
[ "Handles", "a", "TC_ARRAY", "opcode" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L967-L1019
train
235,778
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller.do_reference
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), ident) ref = self.references[handle - self.BASE_REFERENCE_IDX] log_debug("###-> Type: {0} - Value: {1}".format(type(ref), ref), ident) return ref
python
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), ident) ref = self.references[handle - self.BASE_REFERENCE_IDX] log_debug("###-> Type: {0} - Value: {1}".format(type(ref), ref), ident) return ref
[ "def", "do_reference", "(", "self", ",", "parent", "=", "None", ",", "ident", "=", "0", ")", ":", "(", "handle", ",", ")", "=", "self", ".", "_readStruct", "(", "\">L\"", ")", "log_debug", "(", "\"## Reference handle: 0x{0:X}\"", ".", "format", "(", "handle", ")", ",", "ident", ")", "ref", "=", "self", ".", "references", "[", "handle", "-", "self", ".", "BASE_REFERENCE_IDX", "]", "log_debug", "(", "\"###-> Type: {0} - Value: {1}\"", ".", "format", "(", "type", "(", "ref", ")", ",", "ref", ")", ",", "ident", ")", "return", "ref" ]
Handles a TC_REFERENCE opcode :param parent: :param ident: Log indentation level :return: The referenced object
[ "Handles", "a", "TC_REFERENCE", "opcode" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1021-L1033
train
235,779
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller.do_enum
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_exec_opcode( ident=ident + 1, expect=( self.TC_CLASSDESC, self.TC_PROXYCLASSDESC, self.TC_NULL, self.TC_REFERENCE, ), ) enum.classdesc = classdesc self._add_reference(enum, ident) _, enumConstantName = self._read_and_exec_opcode( ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE) ) enum.constant = enumConstantName return enum
python
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_exec_opcode( ident=ident + 1, expect=( self.TC_CLASSDESC, self.TC_PROXYCLASSDESC, self.TC_NULL, self.TC_REFERENCE, ), ) enum.classdesc = classdesc self._add_reference(enum, ident) _, enumConstantName = self._read_and_exec_opcode( ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE) ) enum.constant = enumConstantName return enum
[ "def", "do_enum", "(", "self", ",", "parent", "=", "None", ",", "ident", "=", "0", ")", ":", "# TC_ENUM classDesc newHandle enumConstantName", "enum", "=", "JavaEnum", "(", ")", "_", ",", "classdesc", "=", "self", ".", "_read_and_exec_opcode", "(", "ident", "=", "ident", "+", "1", ",", "expect", "=", "(", "self", ".", "TC_CLASSDESC", ",", "self", ".", "TC_PROXYCLASSDESC", ",", "self", ".", "TC_NULL", ",", "self", ".", "TC_REFERENCE", ",", ")", ",", ")", "enum", ".", "classdesc", "=", "classdesc", "self", ".", "_add_reference", "(", "enum", ",", "ident", ")", "_", ",", "enumConstantName", "=", "self", ".", "_read_and_exec_opcode", "(", "ident", "=", "ident", "+", "1", ",", "expect", "=", "(", "self", ".", "TC_STRING", ",", "self", ".", "TC_REFERENCE", ")", ")", "enum", ".", "constant", "=", "enumConstantName", "return", "enum" ]
Handles a TC_ENUM opcode :param parent: :param ident: Log indentation level :return: A JavaEnum object
[ "Handles", "a", "TC_ENUM", "opcode" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1046-L1071
train
235,780
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller._create_hexdump
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 """ FILTER = "".join((len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256)) pattern = "{{0:04X}} {{1:<{0}}} {{2}}\n".format(length * 3) # Convert raw data to str (Python 3 compatibility) src = to_str(src, "latin-1") result = [] for i in range(0, len(src), length): s = src[i : i + length] hexa = " ".join("{0:02X}".format(ord(x)) for x in s) printable = s.translate(FILTER) result.append(pattern.format(i + start_offset, hexa, printable)) return "".join(result)
python
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 """ FILTER = "".join((len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256)) pattern = "{{0:04X}} {{1:<{0}}} {{2}}\n".format(length * 3) # Convert raw data to str (Python 3 compatibility) src = to_str(src, "latin-1") result = [] for i in range(0, len(src), length): s = src[i : i + length] hexa = " ".join("{0:02X}".format(ord(x)) for x in s) printable = s.translate(FILTER) result.append(pattern.format(i + start_offset, hexa, printable)) return "".join(result)
[ "def", "_create_hexdump", "(", "src", ",", "start_offset", "=", "0", ",", "length", "=", "16", ")", ":", "FILTER", "=", "\"\"", ".", "join", "(", "(", "len", "(", "repr", "(", "chr", "(", "x", ")", ")", ")", "==", "3", ")", "and", "chr", "(", "x", ")", "or", "\".\"", "for", "x", "in", "range", "(", "256", ")", ")", "pattern", "=", "\"{{0:04X}} {{1:<{0}}} {{2}}\\n\"", ".", "format", "(", "length", "*", "3", ")", "# Convert raw data to str (Python 3 compatibility)", "src", "=", "to_str", "(", "src", ",", "\"latin-1\"", ")", "result", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "src", ")", ",", "length", ")", ":", "s", "=", "src", "[", "i", ":", "i", "+", "length", "]", "hexa", "=", "\" \"", ".", "join", "(", "\"{0:02X}\"", ".", "format", "(", "ord", "(", "x", ")", ")", "for", "x", "in", "s", ")", "printable", "=", "s", ".", "translate", "(", "FILTER", ")", "result", ".", "append", "(", "pattern", ".", "format", "(", "i", "+", "start_offset", ",", "hexa", ",", "printable", ")", ")", "return", "\"\"", ".", "join", "(", "result", ")" ]
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
[ "Prepares", "an", "hexadecimal", "dump", "string" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1074-L1096
train
235,781
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller._convert_char_to_type
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: typecode = chr(type_char) if typecode in self.TYPECODES_LIST: return typecode else: raise RuntimeError( "Typecode {0} ({1}) isn't supported.".format(type_char, typecode) )
python
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: typecode = chr(type_char) if typecode in self.TYPECODES_LIST: return typecode else: raise RuntimeError( "Typecode {0} ({1}) isn't supported.".format(type_char, typecode) )
[ "def", "_convert_char_to_type", "(", "self", ",", "type_char", ")", ":", "typecode", "=", "type_char", "if", "type", "(", "type_char", ")", "is", "int", ":", "typecode", "=", "chr", "(", "type_char", ")", "if", "typecode", "in", "self", ".", "TYPECODES_LIST", ":", "return", "typecode", "else", ":", "raise", "RuntimeError", "(", "\"Typecode {0} ({1}) isn't supported.\"", ".", "format", "(", "type_char", ",", "typecode", ")", ")" ]
Ensures a read character is a typecode. :param type_char: Read typecode :return: The typecode as a string (using chr) :raise RuntimeError: Unknown typecode
[ "Ensures", "a", "read", "character", "is", "a", "typecode", "." ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1140-L1157
train
235,782
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller._add_reference
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.references) + self.BASE_REFERENCE_IDX, type(obj).__name__, repr(obj), ), ident, ) self.references.append(obj)
python
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.references) + self.BASE_REFERENCE_IDX, type(obj).__name__, repr(obj), ), ident, ) self.references.append(obj)
[ "def", "_add_reference", "(", "self", ",", "obj", ",", "ident", "=", "0", ")", ":", "log_debug", "(", "\"## New reference handle 0x{0:X}: {1} -> {2}\"", ".", "format", "(", "len", "(", "self", ".", "references", ")", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "type", "(", "obj", ")", ".", "__name__", ",", "repr", "(", "obj", ")", ",", ")", ",", "ident", ",", ")", "self", ".", "references", ".", "append", "(", "obj", ")" ]
Adds a read reference to the marshaler storage :param obj: Reference to add :param ident: Log indentation level
[ "Adds", "a", "read", "reference", "to", "the", "marshaler", "storage" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1159-L1174
train
235,783
tcalmant/python-javaobj
javaobj/core.py
JavaObjectUnmarshaller._oops_dump_state
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)) log_error("References: {0}".format(self.references)) log_error("Stream seeking back at -16 byte (2nd line is an actual position!):") # Do not use a keyword argument self.object_stream.seek(-16, os.SEEK_CUR) position = self.object_stream.tell() the_rest = self.object_stream.read() if not ignore_remaining_data and len(the_rest): log_error( "Warning!!!!: Stream still has {0} bytes left:\n{1}".format( len(the_rest), self._create_hexdump(the_rest, position) ) ) log_error("=" * 30)
python
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)) log_error("References: {0}".format(self.references)) log_error("Stream seeking back at -16 byte (2nd line is an actual position!):") # Do not use a keyword argument self.object_stream.seek(-16, os.SEEK_CUR) position = self.object_stream.tell() the_rest = self.object_stream.read() if not ignore_remaining_data and len(the_rest): log_error( "Warning!!!!: Stream still has {0} bytes left:\n{1}".format( len(the_rest), self._create_hexdump(the_rest, position) ) ) log_error("=" * 30)
[ "def", "_oops_dump_state", "(", "self", ",", "ignore_remaining_data", "=", "False", ")", ":", "log_error", "(", "\"==Oops state dump\"", "+", "\"=\"", "*", "(", "30", "-", "17", ")", ")", "log_error", "(", "\"References: {0}\"", ".", "format", "(", "self", ".", "references", ")", ")", "log_error", "(", "\"Stream seeking back at -16 byte (2nd line is an actual position!):\"", ")", "# Do not use a keyword argument", "self", ".", "object_stream", ".", "seek", "(", "-", "16", ",", "os", ".", "SEEK_CUR", ")", "position", "=", "self", ".", "object_stream", ".", "tell", "(", ")", "the_rest", "=", "self", ".", "object_stream", ".", "read", "(", ")", "if", "not", "ignore_remaining_data", "and", "len", "(", "the_rest", ")", ":", "log_error", "(", "\"Warning!!!!: Stream still has {0} bytes left:\\n{1}\"", ".", "format", "(", "len", "(", "the_rest", ")", ",", "self", ".", "_create_hexdump", "(", "the_rest", ",", "position", ")", ")", ")", "log_error", "(", "\"=\"", "*", "30", ")" ]
Log a deserialization error :param ignore_remaining_data: If True, don't log an error when unused trailing bytes are remaining
[ "Log", "a", "deserialization", "error" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1176-L1199
train
235,784
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.dump
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()
python
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", "dump", "(", "self", ",", "obj", ")", ":", "self", ".", "references", "=", "[", "]", "self", ".", "object_obj", "=", "obj", "self", ".", "object_stream", "=", "BytesIO", "(", ")", "self", ".", "_writeStreamHeader", "(", ")", "self", ".", "writeObject", "(", "obj", ")", "return", "self", ".", "object_stream", ".", "getvalue", "(", ")" ]
Dumps the given object in the Java serialization format
[ "Dumps", "the", "given", "object", "in", "the", "Java", "serialization", "format" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1229-L1238
train
235,785
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.writeObject
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, JavaArray): # Deserialized Java array self.write_array(obj) elif isinstance(obj, JavaEnum): # Deserialized Java Enum self.write_enum(obj) elif isinstance(obj, JavaObject): # Deserialized Java object self.write_object(obj) elif isinstance(obj, JavaString): # Deserialized String self.write_string(obj) elif isinstance(obj, JavaClass): # Java class self.write_class(obj) elif obj is None: # Null self.write_null() elif type(obj) is str: # String value self.write_blockdata(obj) else: # Unhandled type raise RuntimeError( "Object serialization of type {0} is not " "supported.".format(type(obj)) )
python
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, JavaArray): # Deserialized Java array self.write_array(obj) elif isinstance(obj, JavaEnum): # Deserialized Java Enum self.write_enum(obj) elif isinstance(obj, JavaObject): # Deserialized Java object self.write_object(obj) elif isinstance(obj, JavaString): # Deserialized String self.write_string(obj) elif isinstance(obj, JavaClass): # Java class self.write_class(obj) elif obj is None: # Null self.write_null() elif type(obj) is str: # String value self.write_blockdata(obj) else: # Unhandled type raise RuntimeError( "Object serialization of type {0} is not " "supported.".format(type(obj)) )
[ "def", "writeObject", "(", "self", ",", "obj", ")", ":", "log_debug", "(", "\"Writing object of type {0}\"", ".", "format", "(", "type", "(", "obj", ")", ".", "__name__", ")", ")", "if", "isinstance", "(", "obj", ",", "JavaArray", ")", ":", "# Deserialized Java array", "self", ".", "write_array", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "JavaEnum", ")", ":", "# Deserialized Java Enum", "self", ".", "write_enum", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "JavaObject", ")", ":", "# Deserialized Java object", "self", ".", "write_object", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "JavaString", ")", ":", "# Deserialized String", "self", ".", "write_string", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "JavaClass", ")", ":", "# Java class", "self", ".", "write_class", "(", "obj", ")", "elif", "obj", "is", "None", ":", "# Null", "self", ".", "write_null", "(", ")", "elif", "type", "(", "obj", ")", "is", "str", ":", "# String value", "self", ".", "write_blockdata", "(", "obj", ")", "else", ":", "# Unhandled type", "raise", "RuntimeError", "(", "\"Object serialization of type {0} is not \"", "\"supported.\"", ".", "format", "(", "type", "(", "obj", ")", ")", ")" ]
Appends an object to the serialization stream :param obj: A string or a deserialized Java object :raise RuntimeError: Unsupported type
[ "Appends", "an", "object", "to", "the", "serialization", "stream" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1246-L1280
train
235,786
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller._writeString
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/docs/api/java/io/DataInput.html#modified-utf-8 string = to_bytes(obj, "utf-8") if use_reference and isinstance(obj, JavaString): try: idx = self.references.index(obj) except ValueError: # First appearance of the string self.references.append(obj) logging.debug( "*** Adding ref 0x%X for string: %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) self._writeStruct(">H", 2, (len(string),)) self.object_stream.write(string) else: # Write a reference to the previous type logging.debug( "*** Reusing ref 0x%X for string: %s", idx + self.BASE_REFERENCE_IDX, obj, ) self.write_reference(idx) else: self._writeStruct(">H", 2, (len(string),)) self.object_stream.write(string)
python
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/docs/api/java/io/DataInput.html#modified-utf-8 string = to_bytes(obj, "utf-8") if use_reference and isinstance(obj, JavaString): try: idx = self.references.index(obj) except ValueError: # First appearance of the string self.references.append(obj) logging.debug( "*** Adding ref 0x%X for string: %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) self._writeStruct(">H", 2, (len(string),)) self.object_stream.write(string) else: # Write a reference to the previous type logging.debug( "*** Reusing ref 0x%X for string: %s", idx + self.BASE_REFERENCE_IDX, obj, ) self.write_reference(idx) else: self._writeStruct(">H", 2, (len(string),)) self.object_stream.write(string)
[ "def", "_writeString", "(", "self", ",", "obj", ",", "use_reference", "=", "True", ")", ":", "# TODO: Convert to \"modified UTF-8\"", "# http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8", "string", "=", "to_bytes", "(", "obj", ",", "\"utf-8\"", ")", "if", "use_reference", "and", "isinstance", "(", "obj", ",", "JavaString", ")", ":", "try", ":", "idx", "=", "self", ".", "references", ".", "index", "(", "obj", ")", "except", "ValueError", ":", "# First appearance of the string", "self", ".", "references", ".", "append", "(", "obj", ")", "logging", ".", "debug", "(", "\"*** Adding ref 0x%X for string: %s\"", ",", "len", "(", "self", ".", "references", ")", "-", "1", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "obj", ",", ")", "self", ".", "_writeStruct", "(", "\">H\"", ",", "2", ",", "(", "len", "(", "string", ")", ",", ")", ")", "self", ".", "object_stream", ".", "write", "(", "string", ")", "else", ":", "# Write a reference to the previous type", "logging", ".", "debug", "(", "\"*** Reusing ref 0x%X for string: %s\"", ",", "idx", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "obj", ",", ")", "self", ".", "write_reference", "(", "idx", ")", "else", ":", "self", ".", "_writeStruct", "(", "\">H\"", ",", "2", ",", "(", "len", "(", "string", ")", ",", ")", ")", "self", ".", "object_stream", ".", "write", "(", "string", ")" ]
Appends a string to the serialization stream :param obj: String to serialize :param use_reference: If True, allow writing a reference
[ "Appends", "a", "string", "to", "the", "serialization", "stream" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1293-L1328
train
235,787
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_string
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: idx = self.references.index(obj) except ValueError: # String is not referenced: let _writeString store it self._writeStruct(">B", 1, (self.TC_STRING,)) self._writeString(obj, use_reference) else: # Reuse the referenced string logging.debug( "*** Reusing ref 0x%X for String: %s", idx + self.BASE_REFERENCE_IDX, obj, ) self.write_reference(idx) else: # Don't use references self._writeStruct(">B", 1, (self.TC_STRING,)) self._writeString(obj, use_reference)
python
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: idx = self.references.index(obj) except ValueError: # String is not referenced: let _writeString store it self._writeStruct(">B", 1, (self.TC_STRING,)) self._writeString(obj, use_reference) else: # Reuse the referenced string logging.debug( "*** Reusing ref 0x%X for String: %s", idx + self.BASE_REFERENCE_IDX, obj, ) self.write_reference(idx) else: # Don't use references self._writeStruct(">B", 1, (self.TC_STRING,)) self._writeString(obj, use_reference)
[ "def", "write_string", "(", "self", ",", "obj", ",", "use_reference", "=", "True", ")", ":", "if", "use_reference", "and", "isinstance", "(", "obj", ",", "JavaString", ")", ":", "try", ":", "idx", "=", "self", ".", "references", ".", "index", "(", "obj", ")", "except", "ValueError", ":", "# String is not referenced: let _writeString store it", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_STRING", ",", ")", ")", "self", ".", "_writeString", "(", "obj", ",", "use_reference", ")", "else", ":", "# Reuse the referenced string", "logging", ".", "debug", "(", "\"*** Reusing ref 0x%X for String: %s\"", ",", "idx", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "obj", ",", ")", "self", ".", "write_reference", "(", "idx", ")", "else", ":", "# Don't use references", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_STRING", ",", ")", ")", "self", ".", "_writeString", "(", "obj", ",", "use_reference", ")" ]
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
[ "Writes", "a", "Java", "string", "with", "the", "TC_STRING", "type", "marker" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1330-L1355
train
235,788
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_enum
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.index(obj) except ValueError: # New reference self.references.append(obj) logging.debug( "*** Adding ref 0x%X for enum: %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) self.write_classdesc(obj.get_class()) else: self.write_reference(idx) self.write_string(obj.constant)
python
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.index(obj) except ValueError: # New reference self.references.append(obj) logging.debug( "*** Adding ref 0x%X for enum: %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) self.write_classdesc(obj.get_class()) else: self.write_reference(idx) self.write_string(obj.constant)
[ "def", "write_enum", "(", "self", ",", "obj", ")", ":", "# 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", ".", "index", "(", "obj", ")", "except", "ValueError", ":", "# New reference", "self", ".", "references", ".", "append", "(", "obj", ")", "logging", ".", "debug", "(", "\"*** Adding ref 0x%X for enum: %s\"", ",", "len", "(", "self", ".", "references", ")", "-", "1", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "obj", ",", ")", "self", ".", "write_classdesc", "(", "obj", ".", "get_class", "(", ")", ")", "else", ":", "self", ".", "write_reference", "(", "idx", ")", "self", ".", "write_string", "(", "obj", ".", "constant", ")" ]
Writes an Enum value :param obj: A JavaEnum object
[ "Writes", "an", "Enum", "value" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1357-L1382
train
235,789
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_blockdata
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) if length <= 256: # Small block data # TC_BLOCKDATA (unsigned byte)<size> (byte)[size] self._writeStruct(">B", 1, (self.TC_BLOCKDATA,)) self._writeStruct(">B", 1, (length,)) else: # Large block data # TC_BLOCKDATALONG (unsigned int)<size> (byte)[size] self._writeStruct(">B", 1, (self.TC_BLOCKDATALONG,)) self._writeStruct(">I", 1, (length,)) self.object_stream.write(obj)
python
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) if length <= 256: # Small block data # TC_BLOCKDATA (unsigned byte)<size> (byte)[size] self._writeStruct(">B", 1, (self.TC_BLOCKDATA,)) self._writeStruct(">B", 1, (length,)) else: # Large block data # TC_BLOCKDATALONG (unsigned int)<size> (byte)[size] self._writeStruct(">B", 1, (self.TC_BLOCKDATALONG,)) self._writeStruct(">I", 1, (length,)) self.object_stream.write(obj)
[ "def", "write_blockdata", "(", "self", ",", "obj", ",", "parent", "=", "None", ")", ":", "if", "type", "(", "obj", ")", "is", "str", ":", "# Latin-1: keep bytes as is", "obj", "=", "to_bytes", "(", "obj", ",", "\"latin-1\"", ")", "length", "=", "len", "(", "obj", ")", "if", "length", "<=", "256", ":", "# Small block data", "# TC_BLOCKDATA (unsigned byte)<size> (byte)[size]", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_BLOCKDATA", ",", ")", ")", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "length", ",", ")", ")", "else", ":", "# Large block data", "# TC_BLOCKDATALONG (unsigned int)<size> (byte)[size]", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_BLOCKDATALONG", ",", ")", ")", "self", ".", "_writeStruct", "(", "\">I\"", ",", "1", ",", "(", "length", ",", ")", ")", "self", ".", "object_stream", ".", "write", "(", "obj", ")" ]
Appends a block of data to the serialization stream :param obj: String form of the data block
[ "Appends", "a", "block", "of", "data", "to", "the", "serialization", "stream" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1384-L1406
train
235,790
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_object
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.transform(obj) if tmp_object is not obj: obj = tmp_object break self._writeStruct(">B", 1, (self.TC_OBJECT,)) cls = obj.get_class() self.write_classdesc(cls) # Add reference self.references.append([]) logging.debug( "*** Adding ref 0x%X for object %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) all_names = collections.deque() all_types = collections.deque() tmpcls = cls while tmpcls: all_names.extendleft(reversed(tmpcls.fields_names)) all_types.extendleft(reversed(tmpcls.fields_types)) tmpcls = tmpcls.superclass del tmpcls logging.debug("<=> Field names: %s", all_names) logging.debug("<=> Field types: %s", all_types) for field_name, field_type in zip(all_names, all_types): try: logging.debug( "Writing field %s (%s): %s", field_name, field_type, getattr(obj, field_name), ) self._write_value(field_type, getattr(obj, field_name)) except AttributeError as ex: log_error( "No attribute {0} for object {1}\nDir: {2}".format( ex, repr(obj), dir(obj) ) ) raise del all_names, all_types if ( cls.flags & self.SC_SERIALIZABLE and cls.flags & self.SC_WRITE_METHOD or cls.flags & self.SC_EXTERNALIZABLE and cls.flags & self.SC_BLOCK_DATA ): for annotation in obj.annotations: log_debug( "Write annotation {0} for {1}".format(repr(annotation), repr(obj)) ) if annotation is None: self.write_null() else: self.writeObject(annotation) self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
python
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.transform(obj) if tmp_object is not obj: obj = tmp_object break self._writeStruct(">B", 1, (self.TC_OBJECT,)) cls = obj.get_class() self.write_classdesc(cls) # Add reference self.references.append([]) logging.debug( "*** Adding ref 0x%X for object %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) all_names = collections.deque() all_types = collections.deque() tmpcls = cls while tmpcls: all_names.extendleft(reversed(tmpcls.fields_names)) all_types.extendleft(reversed(tmpcls.fields_types)) tmpcls = tmpcls.superclass del tmpcls logging.debug("<=> Field names: %s", all_names) logging.debug("<=> Field types: %s", all_types) for field_name, field_type in zip(all_names, all_types): try: logging.debug( "Writing field %s (%s): %s", field_name, field_type, getattr(obj, field_name), ) self._write_value(field_type, getattr(obj, field_name)) except AttributeError as ex: log_error( "No attribute {0} for object {1}\nDir: {2}".format( ex, repr(obj), dir(obj) ) ) raise del all_names, all_types if ( cls.flags & self.SC_SERIALIZABLE and cls.flags & self.SC_WRITE_METHOD or cls.flags & self.SC_EXTERNALIZABLE and cls.flags & self.SC_BLOCK_DATA ): for annotation in obj.annotations: log_debug( "Write annotation {0} for {1}".format(repr(annotation), repr(obj)) ) if annotation is None: self.write_null() else: self.writeObject(annotation) self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
[ "def", "write_object", "(", "self", ",", "obj", ",", "parent", "=", "None", ")", ":", "# Transform object", "for", "transformer", "in", "self", ".", "object_transformers", ":", "tmp_object", "=", "transformer", ".", "transform", "(", "obj", ")", "if", "tmp_object", "is", "not", "obj", ":", "obj", "=", "tmp_object", "break", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_OBJECT", ",", ")", ")", "cls", "=", "obj", ".", "get_class", "(", ")", "self", ".", "write_classdesc", "(", "cls", ")", "# Add reference", "self", ".", "references", ".", "append", "(", "[", "]", ")", "logging", ".", "debug", "(", "\"*** Adding ref 0x%X for object %s\"", ",", "len", "(", "self", ".", "references", ")", "-", "1", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "obj", ",", ")", "all_names", "=", "collections", ".", "deque", "(", ")", "all_types", "=", "collections", ".", "deque", "(", ")", "tmpcls", "=", "cls", "while", "tmpcls", ":", "all_names", ".", "extendleft", "(", "reversed", "(", "tmpcls", ".", "fields_names", ")", ")", "all_types", ".", "extendleft", "(", "reversed", "(", "tmpcls", ".", "fields_types", ")", ")", "tmpcls", "=", "tmpcls", ".", "superclass", "del", "tmpcls", "logging", ".", "debug", "(", "\"<=> Field names: %s\"", ",", "all_names", ")", "logging", ".", "debug", "(", "\"<=> Field types: %s\"", ",", "all_types", ")", "for", "field_name", ",", "field_type", "in", "zip", "(", "all_names", ",", "all_types", ")", ":", "try", ":", "logging", ".", "debug", "(", "\"Writing field %s (%s): %s\"", ",", "field_name", ",", "field_type", ",", "getattr", "(", "obj", ",", "field_name", ")", ",", ")", "self", ".", "_write_value", "(", "field_type", ",", "getattr", "(", "obj", ",", "field_name", ")", ")", "except", "AttributeError", "as", "ex", ":", "log_error", "(", "\"No attribute {0} for object {1}\\nDir: {2}\"", ".", "format", "(", "ex", ",", "repr", "(", "obj", ")", ",", "dir", "(", "obj", ")", ")", ")", "raise", "del", "all_names", ",", "all_types", "if", "(", "cls", ".", "flags", "&", "self", ".", "SC_SERIALIZABLE", "and", "cls", ".", "flags", "&", "self", ".", "SC_WRITE_METHOD", "or", "cls", ".", "flags", "&", "self", ".", "SC_EXTERNALIZABLE", "and", "cls", ".", "flags", "&", "self", ".", "SC_BLOCK_DATA", ")", ":", "for", "annotation", "in", "obj", ".", "annotations", ":", "log_debug", "(", "\"Write annotation {0} for {1}\"", ".", "format", "(", "repr", "(", "annotation", ")", ",", "repr", "(", "obj", ")", ")", ")", "if", "annotation", "is", "None", ":", "self", ".", "write_null", "(", ")", "else", ":", "self", ".", "writeObject", "(", "annotation", ")", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_ENDBLOCKDATA", ",", ")", ")" ]
Writes an object header to the serialization stream :param obj: Not yet used :param parent: Not yet used
[ "Writes", "an", "object", "header", "to", "the", "serialization", "stream" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1414-L1484
train
235,791
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_class
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)
python
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_class", "(", "self", ",", "obj", ",", "parent", "=", "None", ")", ":", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_CLASS", ",", ")", ")", "self", ".", "write_classdesc", "(", "obj", ")" ]
Writes a class to the stream :param obj: A JavaClass object :param parent:
[ "Writes", "a", "class", "to", "the", "stream" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1486-L1494
train
235,792
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_classdesc
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( "*** Adding ref 0x%X for classdesc %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj.name, ) self._writeStruct(">B", 1, (self.TC_CLASSDESC,)) self._writeString(obj.name) self._writeStruct(">qB", 1, (obj.serialVersionUID, obj.flags)) self._writeStruct(">H", 1, (len(obj.fields_names),)) for field_name, field_type in zip(obj.fields_names, obj.fields_types): self._writeStruct(">B", 1, (self._convert_type_to_char(field_type),)) self._writeString(field_name) if field_type[0] in (self.TYPE_OBJECT, self.TYPE_ARRAY): try: idx = self.references.index(field_type) except ValueError: # First appearance of the type self.references.append(field_type) logging.debug( "*** Adding ref 0x%X for field type %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, field_type, ) self.write_string(field_type, False) else: # Write a reference to the previous type logging.debug( "*** Reusing ref 0x%X for %s (%s)", idx + self.BASE_REFERENCE_IDX, field_type, field_name, ) self.write_reference(idx) self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,)) if obj.superclass: self.write_classdesc(obj.superclass) else: self.write_null() else: # Use reference self.write_reference(self.references.index(obj))
python
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( "*** Adding ref 0x%X for classdesc %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj.name, ) self._writeStruct(">B", 1, (self.TC_CLASSDESC,)) self._writeString(obj.name) self._writeStruct(">qB", 1, (obj.serialVersionUID, obj.flags)) self._writeStruct(">H", 1, (len(obj.fields_names),)) for field_name, field_type in zip(obj.fields_names, obj.fields_types): self._writeStruct(">B", 1, (self._convert_type_to_char(field_type),)) self._writeString(field_name) if field_type[0] in (self.TYPE_OBJECT, self.TYPE_ARRAY): try: idx = self.references.index(field_type) except ValueError: # First appearance of the type self.references.append(field_type) logging.debug( "*** Adding ref 0x%X for field type %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, field_type, ) self.write_string(field_type, False) else: # Write a reference to the previous type logging.debug( "*** Reusing ref 0x%X for %s (%s)", idx + self.BASE_REFERENCE_IDX, field_type, field_name, ) self.write_reference(idx) self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,)) if obj.superclass: self.write_classdesc(obj.superclass) else: self.write_null() else: # Use reference self.write_reference(self.references.index(obj))
[ "def", "write_classdesc", "(", "self", ",", "obj", ",", "parent", "=", "None", ")", ":", "if", "obj", "not", "in", "self", ".", "references", ":", "# Add reference", "self", ".", "references", ".", "append", "(", "obj", ")", "logging", ".", "debug", "(", "\"*** Adding ref 0x%X for classdesc %s\"", ",", "len", "(", "self", ".", "references", ")", "-", "1", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "obj", ".", "name", ",", ")", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_CLASSDESC", ",", ")", ")", "self", ".", "_writeString", "(", "obj", ".", "name", ")", "self", ".", "_writeStruct", "(", "\">qB\"", ",", "1", ",", "(", "obj", ".", "serialVersionUID", ",", "obj", ".", "flags", ")", ")", "self", ".", "_writeStruct", "(", "\">H\"", ",", "1", ",", "(", "len", "(", "obj", ".", "fields_names", ")", ",", ")", ")", "for", "field_name", ",", "field_type", "in", "zip", "(", "obj", ".", "fields_names", ",", "obj", ".", "fields_types", ")", ":", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "_convert_type_to_char", "(", "field_type", ")", ",", ")", ")", "self", ".", "_writeString", "(", "field_name", ")", "if", "field_type", "[", "0", "]", "in", "(", "self", ".", "TYPE_OBJECT", ",", "self", ".", "TYPE_ARRAY", ")", ":", "try", ":", "idx", "=", "self", ".", "references", ".", "index", "(", "field_type", ")", "except", "ValueError", ":", "# First appearance of the type", "self", ".", "references", ".", "append", "(", "field_type", ")", "logging", ".", "debug", "(", "\"*** Adding ref 0x%X for field type %s\"", ",", "len", "(", "self", ".", "references", ")", "-", "1", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "field_type", ",", ")", "self", ".", "write_string", "(", "field_type", ",", "False", ")", "else", ":", "# Write a reference to the previous type", "logging", ".", "debug", "(", "\"*** Reusing ref 0x%X for %s (%s)\"", ",", "idx", "+", "self", ".", "BASE_REFERENCE_IDX", ",", "field_type", ",", "field_name", ",", ")", "self", ".", "write_reference", "(", "idx", ")", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_ENDBLOCKDATA", ",", ")", ")", "if", "obj", ".", "superclass", ":", "self", ".", "write_classdesc", "(", "obj", ".", "superclass", ")", "else", ":", "self", ".", "write_null", "(", ")", "else", ":", "# Use reference", "self", ".", "write_reference", "(", "self", ".", "references", ".", "index", "(", "obj", ")", ")" ]
Writes a class description :param obj: Class description to write :param parent:
[ "Writes", "a", "class", "description" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1496-L1550
train
235,793
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller.write_array
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 self.references.append(obj) logging.debug( "*** Adding ref 0x%X for array []", len(self.references) - 1 + self.BASE_REFERENCE_IDX, ) type_char = classdesc.name[0] assert type_char == self.TYPE_ARRAY type_char = classdesc.name[1] if type_char == self.TYPE_OBJECT: for o in obj: self._write_value(classdesc.name[1:], o) elif type_char == self.TYPE_ARRAY: for a in obj: self.write_array(a) else: log_debug("Write array of type %s" % type_char) for v in obj: log_debug("Writing: %s" % v) self._write_value(type_char, v)
python
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 self.references.append(obj) logging.debug( "*** Adding ref 0x%X for array []", len(self.references) - 1 + self.BASE_REFERENCE_IDX, ) type_char = classdesc.name[0] assert type_char == self.TYPE_ARRAY type_char = classdesc.name[1] if type_char == self.TYPE_OBJECT: for o in obj: self._write_value(classdesc.name[1:], o) elif type_char == self.TYPE_ARRAY: for a in obj: self.write_array(a) else: log_debug("Write array of type %s" % type_char) for v in obj: log_debug("Writing: %s" % v) self._write_value(type_char, v)
[ "def", "write_array", "(", "self", ",", "obj", ")", ":", "classdesc", "=", "obj", ".", "get_class", "(", ")", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "self", ".", "TC_ARRAY", ",", ")", ")", "self", ".", "write_classdesc", "(", "classdesc", ")", "self", ".", "_writeStruct", "(", "\">i\"", ",", "1", ",", "(", "len", "(", "obj", ")", ",", ")", ")", "# Add reference", "self", ".", "references", ".", "append", "(", "obj", ")", "logging", ".", "debug", "(", "\"*** Adding ref 0x%X for array []\"", ",", "len", "(", "self", ".", "references", ")", "-", "1", "+", "self", ".", "BASE_REFERENCE_IDX", ",", ")", "type_char", "=", "classdesc", ".", "name", "[", "0", "]", "assert", "type_char", "==", "self", ".", "TYPE_ARRAY", "type_char", "=", "classdesc", ".", "name", "[", "1", "]", "if", "type_char", "==", "self", ".", "TYPE_OBJECT", ":", "for", "o", "in", "obj", ":", "self", ".", "_write_value", "(", "classdesc", ".", "name", "[", "1", ":", "]", ",", "o", ")", "elif", "type_char", "==", "self", ".", "TYPE_ARRAY", ":", "for", "a", "in", "obj", ":", "self", ".", "write_array", "(", "a", ")", "else", ":", "log_debug", "(", "\"Write array of type %s\"", "%", "type_char", ")", "for", "v", "in", "obj", ":", "log_debug", "(", "\"Writing: %s\"", "%", "v", ")", "self", ".", "_write_value", "(", "type_char", ",", "v", ")" ]
Writes a JavaArray :param obj: A JavaArray object
[ "Writes", "a", "JavaArray" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1561-L1593
train
235,794
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller._write_value
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] if field_type == self.TYPE_BOOLEAN: self._writeStruct(">B", 1, (1 if value else 0,)) elif field_type == self.TYPE_BYTE: self._writeStruct(">b", 1, (value,)) elif field_type == self.TYPE_CHAR: self._writeStruct(">H", 1, (ord(value),)) elif field_type == self.TYPE_SHORT: self._writeStruct(">h", 1, (value,)) elif field_type == self.TYPE_INTEGER: self._writeStruct(">i", 1, (value,)) elif field_type == self.TYPE_LONG: self._writeStruct(">q", 1, (value,)) elif field_type == self.TYPE_FLOAT: self._writeStruct(">f", 1, (value,)) elif field_type == self.TYPE_DOUBLE: self._writeStruct(">d", 1, (value,)) elif field_type == self.TYPE_OBJECT or field_type == self.TYPE_ARRAY: if value is None: self.write_null() elif isinstance(value, JavaEnum): self.write_enum(value) elif isinstance(value, (JavaArray, JavaByteArray)): self.write_array(value) elif isinstance(value, JavaObject): self.write_object(value) elif isinstance(value, JavaString): self.write_string(value) elif isinstance(value, str): self.write_blockdata(value) else: raise RuntimeError("Unknown typecode: {0}".format(field_type)) else: raise RuntimeError("Unknown typecode: {0}".format(field_type))
python
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] if field_type == self.TYPE_BOOLEAN: self._writeStruct(">B", 1, (1 if value else 0,)) elif field_type == self.TYPE_BYTE: self._writeStruct(">b", 1, (value,)) elif field_type == self.TYPE_CHAR: self._writeStruct(">H", 1, (ord(value),)) elif field_type == self.TYPE_SHORT: self._writeStruct(">h", 1, (value,)) elif field_type == self.TYPE_INTEGER: self._writeStruct(">i", 1, (value,)) elif field_type == self.TYPE_LONG: self._writeStruct(">q", 1, (value,)) elif field_type == self.TYPE_FLOAT: self._writeStruct(">f", 1, (value,)) elif field_type == self.TYPE_DOUBLE: self._writeStruct(">d", 1, (value,)) elif field_type == self.TYPE_OBJECT or field_type == self.TYPE_ARRAY: if value is None: self.write_null() elif isinstance(value, JavaEnum): self.write_enum(value) elif isinstance(value, (JavaArray, JavaByteArray)): self.write_array(value) elif isinstance(value, JavaObject): self.write_object(value) elif isinstance(value, JavaString): self.write_string(value) elif isinstance(value, str): self.write_blockdata(value) else: raise RuntimeError("Unknown typecode: {0}".format(field_type)) else: raise RuntimeError("Unknown typecode: {0}".format(field_type))
[ "def", "_write_value", "(", "self", ",", "field_type", ",", "value", ")", ":", "if", "len", "(", "field_type", ")", ">", "1", ":", "# We don't need details for arrays and objects", "field_type", "=", "field_type", "[", "0", "]", "if", "field_type", "==", "self", ".", "TYPE_BOOLEAN", ":", "self", ".", "_writeStruct", "(", "\">B\"", ",", "1", ",", "(", "1", "if", "value", "else", "0", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_BYTE", ":", "self", ".", "_writeStruct", "(", "\">b\"", ",", "1", ",", "(", "value", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_CHAR", ":", "self", ".", "_writeStruct", "(", "\">H\"", ",", "1", ",", "(", "ord", "(", "value", ")", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_SHORT", ":", "self", ".", "_writeStruct", "(", "\">h\"", ",", "1", ",", "(", "value", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_INTEGER", ":", "self", ".", "_writeStruct", "(", "\">i\"", ",", "1", ",", "(", "value", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_LONG", ":", "self", ".", "_writeStruct", "(", "\">q\"", ",", "1", ",", "(", "value", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_FLOAT", ":", "self", ".", "_writeStruct", "(", "\">f\"", ",", "1", ",", "(", "value", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_DOUBLE", ":", "self", ".", "_writeStruct", "(", "\">d\"", ",", "1", ",", "(", "value", ",", ")", ")", "elif", "field_type", "==", "self", ".", "TYPE_OBJECT", "or", "field_type", "==", "self", ".", "TYPE_ARRAY", ":", "if", "value", "is", "None", ":", "self", ".", "write_null", "(", ")", "elif", "isinstance", "(", "value", ",", "JavaEnum", ")", ":", "self", ".", "write_enum", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "JavaArray", ",", "JavaByteArray", ")", ")", ":", "self", ".", "write_array", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "JavaObject", ")", ":", "self", ".", "write_object", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "JavaString", ")", ":", "self", ".", "write_string", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "self", ".", "write_blockdata", "(", "value", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unknown typecode: {0}\"", ".", "format", "(", "field_type", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Unknown typecode: {0}\"", ".", "format", "(", "field_type", ")", ")" ]
Writes an item of an array :param field_type: Value type :param value: The value itself
[ "Writes", "an", "item", "of", "an", "array" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1595-L1638
train
235,795
tcalmant/python-javaobj
javaobj/core.py
JavaObjectMarshaller._convert_type_to_char
def _convert_type_to_char(self, type_char): """ Converts the given type code to an int :param type_char: A type code character """ typecode = type_char if type(type_char) is int: typecode = chr(type_char) if typecode in self.TYPECODES_LIST: return ord(typecode) elif len(typecode) > 1: if typecode[0] == "L": return ord(self.TYPE_OBJECT) elif typecode[0] == "[": return ord(self.TYPE_ARRAY) raise RuntimeError( "Typecode {0} ({1}) isn't supported.".format(type_char, typecode) )
python
def _convert_type_to_char(self, type_char): """ Converts the given type code to an int :param type_char: A type code character """ typecode = type_char if type(type_char) is int: typecode = chr(type_char) if typecode in self.TYPECODES_LIST: return ord(typecode) elif len(typecode) > 1: if typecode[0] == "L": return ord(self.TYPE_OBJECT) elif typecode[0] == "[": return ord(self.TYPE_ARRAY) raise RuntimeError( "Typecode {0} ({1}) isn't supported.".format(type_char, typecode) )
[ "def", "_convert_type_to_char", "(", "self", ",", "type_char", ")", ":", "typecode", "=", "type_char", "if", "type", "(", "type_char", ")", "is", "int", ":", "typecode", "=", "chr", "(", "type_char", ")", "if", "typecode", "in", "self", ".", "TYPECODES_LIST", ":", "return", "ord", "(", "typecode", ")", "elif", "len", "(", "typecode", ")", ">", "1", ":", "if", "typecode", "[", "0", "]", "==", "\"L\"", ":", "return", "ord", "(", "self", ".", "TYPE_OBJECT", ")", "elif", "typecode", "[", "0", "]", "==", "\"[\"", ":", "return", "ord", "(", "self", ".", "TYPE_ARRAY", ")", "raise", "RuntimeError", "(", "\"Typecode {0} ({1}) isn't supported.\"", ".", "format", "(", "type_char", ",", "typecode", ")", ")" ]
Converts the given type code to an int :param type_char: A type code character
[ "Converts", "the", "given", "type", "code", "to", "an", "int" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1640-L1660
train
235,796
tcalmant/python-javaobj
javaobj/core.py
DefaultObjectTransformer.create
def create(self, classdesc, unmarshaller=None): # type: (JavaClass, JavaObjectUnmarshaller) -> JavaObject """ Transforms a deserialized Java object into a Python object :param classdesc: The description of a Java class :return: The Python form of the object, or the original JavaObject """ try: mapped_type = self.TYPE_MAPPER[classdesc.name] except KeyError: # Return a JavaObject by default return JavaObject() else: log_debug("---") log_debug(classdesc.name) log_debug("---") java_object = mapped_type(unmarshaller) log_debug(">>> java_object: {0}".format(java_object)) return java_object
python
def create(self, classdesc, unmarshaller=None): # type: (JavaClass, JavaObjectUnmarshaller) -> JavaObject """ Transforms a deserialized Java object into a Python object :param classdesc: The description of a Java class :return: The Python form of the object, or the original JavaObject """ try: mapped_type = self.TYPE_MAPPER[classdesc.name] except KeyError: # Return a JavaObject by default return JavaObject() else: log_debug("---") log_debug(classdesc.name) log_debug("---") java_object = mapped_type(unmarshaller) log_debug(">>> java_object: {0}".format(java_object)) return java_object
[ "def", "create", "(", "self", ",", "classdesc", ",", "unmarshaller", "=", "None", ")", ":", "# type: (JavaClass, JavaObjectUnmarshaller) -> JavaObject", "try", ":", "mapped_type", "=", "self", ".", "TYPE_MAPPER", "[", "classdesc", ".", "name", "]", "except", "KeyError", ":", "# Return a JavaObject by default", "return", "JavaObject", "(", ")", "else", ":", "log_debug", "(", "\"---\"", ")", "log_debug", "(", "classdesc", ".", "name", ")", "log_debug", "(", "\"---\"", ")", "java_object", "=", "mapped_type", "(", "unmarshaller", ")", "log_debug", "(", "\">>> java_object: {0}\"", ".", "format", "(", "java_object", ")", ")", "return", "java_object" ]
Transforms a deserialized Java object into a Python object :param classdesc: The description of a Java class :return: The Python form of the object, or the original JavaObject
[ "Transforms", "a", "deserialized", "Java", "object", "into", "a", "Python", "object" ]
e042c2cbf1ce9de659b6cb9290b5ccd5442514d1
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L2002-L2023
train
235,797
UDST/urbansim
urbansim/urbanchoice/mnl.py
mnl_simulate
def mnl_simulate(data, coeff, numalts, GPU=False, returnprobs=True): """ Get the probabilities for each chooser choosing between `numalts` alternatives. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alternative. Alternatives are in groups of `numalts` rows per choosers. Alternatives must be in the same order for each chooser. coeff : 1D array The model coefficients corresponding to each column in `data`. numalts : int The number of alternatives available to each chooser. GPU : bool, optional returnprobs : bool, optional If True, return the probabilities for each chooser/alternative instead of actual choices. Returns ------- probs or choices: 2D array If `returnprobs` is True the probabilities are a 2D array with a row for each chooser and columns for each alternative. """ logger.debug( 'start: MNL simulation with len(data)={} and numalts={}'.format( len(data), numalts)) atype = 'numpy' if not GPU else 'cuda' data = np.transpose(data) coeff = np.reshape(np.array(coeff), (1, len(coeff))) data, coeff = PMAT(data, atype), PMAT(coeff, atype) probs = mnl_probs(data, coeff, numalts) if returnprobs: return np.transpose(probs.get_mat()) # convert to cpu from here on - gpu doesn't currently support these ops if probs.typ == 'cuda': probs = PMAT(probs.get_mat()) probs = probs.cumsum(axis=0) r = pmat.random(probs.size() // numalts) choices = probs.subtract(r, inplace=True).firstpositive(axis=0) logger.debug('finish: MNL simulation') return choices.get_mat()
python
def mnl_simulate(data, coeff, numalts, GPU=False, returnprobs=True): """ Get the probabilities for each chooser choosing between `numalts` alternatives. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alternative. Alternatives are in groups of `numalts` rows per choosers. Alternatives must be in the same order for each chooser. coeff : 1D array The model coefficients corresponding to each column in `data`. numalts : int The number of alternatives available to each chooser. GPU : bool, optional returnprobs : bool, optional If True, return the probabilities for each chooser/alternative instead of actual choices. Returns ------- probs or choices: 2D array If `returnprobs` is True the probabilities are a 2D array with a row for each chooser and columns for each alternative. """ logger.debug( 'start: MNL simulation with len(data)={} and numalts={}'.format( len(data), numalts)) atype = 'numpy' if not GPU else 'cuda' data = np.transpose(data) coeff = np.reshape(np.array(coeff), (1, len(coeff))) data, coeff = PMAT(data, atype), PMAT(coeff, atype) probs = mnl_probs(data, coeff, numalts) if returnprobs: return np.transpose(probs.get_mat()) # convert to cpu from here on - gpu doesn't currently support these ops if probs.typ == 'cuda': probs = PMAT(probs.get_mat()) probs = probs.cumsum(axis=0) r = pmat.random(probs.size() // numalts) choices = probs.subtract(r, inplace=True).firstpositive(axis=0) logger.debug('finish: MNL simulation') return choices.get_mat()
[ "def", "mnl_simulate", "(", "data", ",", "coeff", ",", "numalts", ",", "GPU", "=", "False", ",", "returnprobs", "=", "True", ")", ":", "logger", ".", "debug", "(", "'start: MNL simulation with len(data)={} and numalts={}'", ".", "format", "(", "len", "(", "data", ")", ",", "numalts", ")", ")", "atype", "=", "'numpy'", "if", "not", "GPU", "else", "'cuda'", "data", "=", "np", ".", "transpose", "(", "data", ")", "coeff", "=", "np", ".", "reshape", "(", "np", ".", "array", "(", "coeff", ")", ",", "(", "1", ",", "len", "(", "coeff", ")", ")", ")", "data", ",", "coeff", "=", "PMAT", "(", "data", ",", "atype", ")", ",", "PMAT", "(", "coeff", ",", "atype", ")", "probs", "=", "mnl_probs", "(", "data", ",", "coeff", ",", "numalts", ")", "if", "returnprobs", ":", "return", "np", ".", "transpose", "(", "probs", ".", "get_mat", "(", ")", ")", "# convert to cpu from here on - gpu doesn't currently support these ops", "if", "probs", ".", "typ", "==", "'cuda'", ":", "probs", "=", "PMAT", "(", "probs", ".", "get_mat", "(", ")", ")", "probs", "=", "probs", ".", "cumsum", "(", "axis", "=", "0", ")", "r", "=", "pmat", ".", "random", "(", "probs", ".", "size", "(", ")", "//", "numalts", ")", "choices", "=", "probs", ".", "subtract", "(", "r", ",", "inplace", "=", "True", ")", ".", "firstpositive", "(", "axis", "=", "0", ")", "logger", ".", "debug", "(", "'finish: MNL simulation'", ")", "return", "choices", ".", "get_mat", "(", ")" ]
Get the probabilities for each chooser choosing between `numalts` alternatives. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alternative. Alternatives are in groups of `numalts` rows per choosers. Alternatives must be in the same order for each chooser. coeff : 1D array The model coefficients corresponding to each column in `data`. numalts : int The number of alternatives available to each chooser. GPU : bool, optional returnprobs : bool, optional If True, return the probabilities for each chooser/alternative instead of actual choices. Returns ------- probs or choices: 2D array If `returnprobs` is True the probabilities are a 2D array with a row for each chooser and columns for each alternative.
[ "Get", "the", "probabilities", "for", "each", "chooser", "choosing", "between", "numalts", "alternatives", "." ]
79f815a6503e109f50be270cee92d0f4a34f49ef
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/urbanchoice/mnl.py#L124-L175
train
235,798
UDST/urbansim
urbansim/urbanchoice/mnl.py
mnl_estimate
def mnl_estimate(data, chosen, numalts, GPU=False, coeffrange=(-3, 3), weights=None, lcgrad=False, beta=None): """ Calculate coefficients of the MNL model. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alternative. Alternatives are in groups of `numalts` rows per choosers. Alternatives must be in the same order for each chooser. chosen : 2D array This boolean array has a row for each chooser and a column for each alternative. The column ordering for alternatives is expected to be the same as their row ordering in the `data` array. A one (True) indicates which alternative each chooser has chosen. numalts : int The number of alternatives. GPU : bool, optional coeffrange : tuple of floats, optional Limits of (min, max) to which coefficients are clipped. weights : ndarray, optional lcgrad : bool, optional beta : 1D array, optional Any initial guess for the coefficients. Returns ------- log_likelihood : dict Dictionary of log-likelihood values describing the quality of the model fit. fit_parameters : pandas.DataFrame Table of fit parameters with columns 'Coefficient', 'Std. Error', 'T-Score'. Each row corresponds to a column in `data` and are given in the same order as in `data`. See Also -------- scipy.optimize.fmin_l_bfgs_b : The optimization routine used. """ logger.debug( 'start: MNL fit with len(data)={} and numalts={}'.format( len(data), numalts)) atype = 'numpy' if not GPU else 'cuda' numvars = data.shape[1] numobs = data.shape[0] // numalts if chosen is None: chosen = np.ones((numobs, numalts)) # used for latent classes data = np.transpose(data) chosen = np.transpose(chosen) data, chosen = PMAT(data, atype), PMAT(chosen, atype) if weights is not None: weights = PMAT(np.transpose(weights), atype) if beta is None: beta = np.zeros(numvars) bounds = [coeffrange] * numvars with log_start_finish('scipy optimization for MNL fit', logger): args = (data, chosen, numalts, weights, lcgrad) bfgs_result = scipy.optimize.fmin_l_bfgs_b(mnl_loglik, beta, args=args, fprime=None, factr=10, approx_grad=False, bounds=bounds ) if bfgs_result[2]['warnflag'] > 0: logger.warn("mnl did not converge correctly: %s", bfgs_result) beta = bfgs_result[0] stderr = mnl_loglik( beta, data, chosen, numalts, weights, stderr=1, lcgrad=lcgrad) l0beta = np.zeros(numvars) l0 = -1 * mnl_loglik(l0beta, *args)[0] l1 = -1 * mnl_loglik(beta, *args)[0] log_likelihood = { 'null': float(l0[0][0]), 'convergence': float(l1[0][0]), 'ratio': float((1 - (l1 / l0))[0][0]) } fit_parameters = pd.DataFrame({ 'Coefficient': beta, 'Std. Error': stderr, 'T-Score': beta / stderr}) logger.debug('finish: MNL fit') return log_likelihood, fit_parameters
python
def mnl_estimate(data, chosen, numalts, GPU=False, coeffrange=(-3, 3), weights=None, lcgrad=False, beta=None): """ Calculate coefficients of the MNL model. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alternative. Alternatives are in groups of `numalts` rows per choosers. Alternatives must be in the same order for each chooser. chosen : 2D array This boolean array has a row for each chooser and a column for each alternative. The column ordering for alternatives is expected to be the same as their row ordering in the `data` array. A one (True) indicates which alternative each chooser has chosen. numalts : int The number of alternatives. GPU : bool, optional coeffrange : tuple of floats, optional Limits of (min, max) to which coefficients are clipped. weights : ndarray, optional lcgrad : bool, optional beta : 1D array, optional Any initial guess for the coefficients. Returns ------- log_likelihood : dict Dictionary of log-likelihood values describing the quality of the model fit. fit_parameters : pandas.DataFrame Table of fit parameters with columns 'Coefficient', 'Std. Error', 'T-Score'. Each row corresponds to a column in `data` and are given in the same order as in `data`. See Also -------- scipy.optimize.fmin_l_bfgs_b : The optimization routine used. """ logger.debug( 'start: MNL fit with len(data)={} and numalts={}'.format( len(data), numalts)) atype = 'numpy' if not GPU else 'cuda' numvars = data.shape[1] numobs = data.shape[0] // numalts if chosen is None: chosen = np.ones((numobs, numalts)) # used for latent classes data = np.transpose(data) chosen = np.transpose(chosen) data, chosen = PMAT(data, atype), PMAT(chosen, atype) if weights is not None: weights = PMAT(np.transpose(weights), atype) if beta is None: beta = np.zeros(numvars) bounds = [coeffrange] * numvars with log_start_finish('scipy optimization for MNL fit', logger): args = (data, chosen, numalts, weights, lcgrad) bfgs_result = scipy.optimize.fmin_l_bfgs_b(mnl_loglik, beta, args=args, fprime=None, factr=10, approx_grad=False, bounds=bounds ) if bfgs_result[2]['warnflag'] > 0: logger.warn("mnl did not converge correctly: %s", bfgs_result) beta = bfgs_result[0] stderr = mnl_loglik( beta, data, chosen, numalts, weights, stderr=1, lcgrad=lcgrad) l0beta = np.zeros(numvars) l0 = -1 * mnl_loglik(l0beta, *args)[0] l1 = -1 * mnl_loglik(beta, *args)[0] log_likelihood = { 'null': float(l0[0][0]), 'convergence': float(l1[0][0]), 'ratio': float((1 - (l1 / l0))[0][0]) } fit_parameters = pd.DataFrame({ 'Coefficient': beta, 'Std. Error': stderr, 'T-Score': beta / stderr}) logger.debug('finish: MNL fit') return log_likelihood, fit_parameters
[ "def", "mnl_estimate", "(", "data", ",", "chosen", ",", "numalts", ",", "GPU", "=", "False", ",", "coeffrange", "=", "(", "-", "3", ",", "3", ")", ",", "weights", "=", "None", ",", "lcgrad", "=", "False", ",", "beta", "=", "None", ")", ":", "logger", ".", "debug", "(", "'start: MNL fit with len(data)={} and numalts={}'", ".", "format", "(", "len", "(", "data", ")", ",", "numalts", ")", ")", "atype", "=", "'numpy'", "if", "not", "GPU", "else", "'cuda'", "numvars", "=", "data", ".", "shape", "[", "1", "]", "numobs", "=", "data", ".", "shape", "[", "0", "]", "//", "numalts", "if", "chosen", "is", "None", ":", "chosen", "=", "np", ".", "ones", "(", "(", "numobs", ",", "numalts", ")", ")", "# used for latent classes", "data", "=", "np", ".", "transpose", "(", "data", ")", "chosen", "=", "np", ".", "transpose", "(", "chosen", ")", "data", ",", "chosen", "=", "PMAT", "(", "data", ",", "atype", ")", ",", "PMAT", "(", "chosen", ",", "atype", ")", "if", "weights", "is", "not", "None", ":", "weights", "=", "PMAT", "(", "np", ".", "transpose", "(", "weights", ")", ",", "atype", ")", "if", "beta", "is", "None", ":", "beta", "=", "np", ".", "zeros", "(", "numvars", ")", "bounds", "=", "[", "coeffrange", "]", "*", "numvars", "with", "log_start_finish", "(", "'scipy optimization for MNL fit'", ",", "logger", ")", ":", "args", "=", "(", "data", ",", "chosen", ",", "numalts", ",", "weights", ",", "lcgrad", ")", "bfgs_result", "=", "scipy", ".", "optimize", ".", "fmin_l_bfgs_b", "(", "mnl_loglik", ",", "beta", ",", "args", "=", "args", ",", "fprime", "=", "None", ",", "factr", "=", "10", ",", "approx_grad", "=", "False", ",", "bounds", "=", "bounds", ")", "if", "bfgs_result", "[", "2", "]", "[", "'warnflag'", "]", ">", "0", ":", "logger", ".", "warn", "(", "\"mnl did not converge correctly: %s\"", ",", "bfgs_result", ")", "beta", "=", "bfgs_result", "[", "0", "]", "stderr", "=", "mnl_loglik", "(", "beta", ",", "data", ",", "chosen", ",", "numalts", ",", "weights", ",", "stderr", "=", "1", ",", "lcgrad", "=", "lcgrad", ")", "l0beta", "=", "np", ".", "zeros", "(", "numvars", ")", "l0", "=", "-", "1", "*", "mnl_loglik", "(", "l0beta", ",", "*", "args", ")", "[", "0", "]", "l1", "=", "-", "1", "*", "mnl_loglik", "(", "beta", ",", "*", "args", ")", "[", "0", "]", "log_likelihood", "=", "{", "'null'", ":", "float", "(", "l0", "[", "0", "]", "[", "0", "]", ")", ",", "'convergence'", ":", "float", "(", "l1", "[", "0", "]", "[", "0", "]", ")", ",", "'ratio'", ":", "float", "(", "(", "1", "-", "(", "l1", "/", "l0", ")", ")", "[", "0", "]", "[", "0", "]", ")", "}", "fit_parameters", "=", "pd", ".", "DataFrame", "(", "{", "'Coefficient'", ":", "beta", ",", "'Std. Error'", ":", "stderr", ",", "'T-Score'", ":", "beta", "/", "stderr", "}", ")", "logger", ".", "debug", "(", "'finish: MNL fit'", ")", "return", "log_likelihood", ",", "fit_parameters" ]
Calculate coefficients of the MNL model. Parameters ---------- data : 2D array The data are expected to be in "long" form where each row is for one alternative. Alternatives are in groups of `numalts` rows per choosers. Alternatives must be in the same order for each chooser. chosen : 2D array This boolean array has a row for each chooser and a column for each alternative. The column ordering for alternatives is expected to be the same as their row ordering in the `data` array. A one (True) indicates which alternative each chooser has chosen. numalts : int The number of alternatives. GPU : bool, optional coeffrange : tuple of floats, optional Limits of (min, max) to which coefficients are clipped. weights : ndarray, optional lcgrad : bool, optional beta : 1D array, optional Any initial guess for the coefficients. Returns ------- log_likelihood : dict Dictionary of log-likelihood values describing the quality of the model fit. fit_parameters : pandas.DataFrame Table of fit parameters with columns 'Coefficient', 'Std. Error', 'T-Score'. Each row corresponds to a column in `data` and are given in the same order as in `data`. See Also -------- scipy.optimize.fmin_l_bfgs_b : The optimization routine used.
[ "Calculate", "coefficients", "of", "the", "MNL", "model", "." ]
79f815a6503e109f50be270cee92d0f4a34f49ef
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/urbanchoice/mnl.py#L178-L275
train
235,799