code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_params_info(nb: int, proto: str) -> str:
"""return a string of parameter info given a function prototype (proto)
:param nb: the number of parameters
:param proto: the function prototype with parameters
:returns: a string representation of the parameter info
"""
i_buffer = "# Parameters:... | return a string of parameter info given a function prototype (proto)
:param nb: the number of parameters
:param proto: the function prototype with parameters
:returns: a string representation of the parameter info
| get_params_info | python | androguard/androguard | androguard/core/dex/__init__.py | https://github.com/androguard/androguard/blob/master/androguard/core/dex/__init__.py | Apache-2.0 |
def get_bytecodes_method(
dex_object, analysis_object: Analysis, method: EncodedMethod
) -> str:
"""return a string representation of method and its code. Wraps [get_bytecodes_methodx][androguard.core.dex.get_bytecodes_methodx]
:param dex_object: unused
:param analysis_object: the `Analysis` object... | return a string representation of method and its code. Wraps [get_bytecodes_methodx][androguard.core.dex.get_bytecodes_methodx]
:param dex_object: unused
:param analysis_object: the `Analysis` object containing the class
:param method: the `EncodedMethod` to get
| get_bytecodes_method | python | androguard/androguard | androguard/core/dex/__init__.py | https://github.com/androguard/androguard/blob/master/androguard/core/dex/__init__.py | Apache-2.0 |
def get_bytecodes_methodx(method: EncodedMethod, mx: MethodAnalysis) -> str:
"""return a string representation of a method and its code
:param method: the associated`EncodedMethod` to get
:param mx: the associated `MethodAnalysis` to get
:returns: the string representation
"""
basic_blocks = mx... | return a string representation of a method and its code
:param method: the associated`EncodedMethod` to get
:param mx: the associated `MethodAnalysis` to get
:returns: the string representation
| get_bytecodes_methodx | python | androguard/androguard | androguard/core/dex/__init__.py | https://github.com/androguard/androguard/blob/master/androguard/core/dex/__init__.py | Apache-2.0 |
def intervals(graph):
"""
Compute the intervals of the graph
Returns
interval_graph: a graph of the intervals of G
interv_heads: a dict of (header node, interval)
"""
interval_graph = Graph() # graph of intervals
heads = [graph.entry] # list of header nodes
interv_heads = {} # int... |
Compute the intervals of the graph
Returns
interval_graph: a graph of the intervals of G
interv_heads: a dict of (header node, interval)
| intervals | python | androguard/androguard | androguard/decompiler/control_flow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/control_flow.py | Apache-2.0 |
def derived_sequence(graph):
"""
Compute the derived sequence of the graph G
The intervals of G are collapsed into nodes, intervals of these nodes are
built, and the process is repeated iteratively until we obtain a single
node (if the graph is not irreducible)
"""
deriv_seq = [graph]
de... |
Compute the derived sequence of the graph G
The intervals of G are collapsed into nodes, intervals of these nodes are
built, and the process is repeated iteratively until we obtain a single
node (if the graph is not irreducible)
| derived_sequence | python | androguard/androguard | androguard/decompiler/control_flow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/control_flow.py | Apache-2.0 |
def update_chain(graph, loc, du, ud):
"""
Updates the DU chain of the instruction located at loc such that there is
no more reference to it so that we can remove it.
When an instruction is found to be dead (i.e it has no side effect, and the
register defined is not used) we have to update the DU cha... |
Updates the DU chain of the instruction located at loc such that there is
no more reference to it so that we can remove it.
When an instruction is found to be dead (i.e it has no side effect, and the
register defined is not used) we have to update the DU chain of all the
variables that may me used ... | update_chain | python | androguard/androguard | androguard/decompiler/dataflow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/dataflow.py | Apache-2.0 |
def dead_code_elimination(graph, du, ud):
"""
Run a dead code elimination pass.
Instructions are checked to be dead. If it is the case, we remove them and
we update the DU & UD chains of its variables to check for further dead
instructions.
"""
for node in graph.rpo:
for i, ins in no... |
Run a dead code elimination pass.
Instructions are checked to be dead. If it is the case, we remove them and
we update the DU & UD chains of its variables to check for further dead
instructions.
| dead_code_elimination | python | androguard/androguard | androguard/decompiler/dataflow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/dataflow.py | Apache-2.0 |
def clear_path(graph, reg, loc1, loc2):
"""
Check that the path from loc1 to loc2 is clear.
We have to check that there is no side effect between the two location
points. We also have to check that the variable `reg` is not redefined
along one of the possible pathes from loc1 to loc2.
"""
lo... |
Check that the path from loc1 to loc2 is clear.
We have to check that there is no side effect between the two location
points. We also have to check that the variable `reg` is not redefined
along one of the possible pathes from loc1 to loc2.
| clear_path | python | androguard/androguard | androguard/decompiler/dataflow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/dataflow.py | Apache-2.0 |
def register_propagation(graph, du, ud):
"""
Propagate the temporary registers between instructions and remove them if
necessary.
We process the nodes of the graph in reverse post order. For each
instruction in the node, we look at the variables that it uses. For each of
these variables we look ... |
Propagate the temporary registers between instructions and remove them if
necessary.
We process the nodes of the graph in reverse post order. For each
instruction in the node, we look at the variables that it uses. For each of
these variables we look where it is defined and if we can replace it wit... | register_propagation | python | androguard/androguard | androguard/decompiler/dataflow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/dataflow.py | Apache-2.0 |
def build_def_use(graph, lparams):
"""
Builds the Def-Use and Use-Def (DU/UD) chains of the variables of the
method.
"""
analysis = reach_def_analysis(graph, lparams)
UD = defaultdict(list)
for node in graph.rpo:
for i, ins in node.get_loc_with_ins():
for var in ins.get_... |
Builds the Def-Use and Use-Def (DU/UD) chains of the variables of the
method.
| build_def_use | python | androguard/androguard | androguard/decompiler/dataflow.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/dataflow.py | Apache-2.0 |
def process(self, doAST: bool = False) -> None:
"""
Processes the method and decompile the code.
There are two modes of operation:
1) Normal Decompilation to Java Code
2) Decompilation into an abstract syntax tree (AST)
The Decompilation is done twice. First, a rough d... |
Processes the method and decompile the code.
There are two modes of operation:
1) Normal Decompilation to Java Code
2) Decompilation into an abstract syntax tree (AST)
The Decompilation is done twice. First, a rough decompilation is created,
which is then optimized. S... | process | python | androguard/androguard | androguard/decompiler/decompile.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/decompile.py | Apache-2.0 |
def get_class(self, class_name: str) -> DvClass:
"""
Return the :class:`DvClass` with the given name
The name is partially matched against the known class names and the first result is returned.
For example, the input `foobar` will match on Lfoobar/bla/foo;
:param str class_nam... |
Return the :class:`DvClass` with the given name
The name is partially matched against the known class names and the first result is returned.
For example, the input `foobar` will match on Lfoobar/bla/foo;
:param str class_name:
:return: the class matching on the name
:... | get_class | python | androguard/androguard | androguard/decompiler/decompile.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/decompile.py | Apache-2.0 |
def process(self) -> None:
"""
Process all classes inside the machine.
This calls :meth:`~androgaurd.decompiler.decompile.DvClass.process` on each :class:`DvClass`.
"""
for name, klass in self.classes.items():
logger.debug('Processing class: %s', name)
if... |
Process all classes inside the machine.
This calls :meth:`~androgaurd.decompiler.decompile.DvClass.process` on each :class:`DvClass`.
| process | python | androguard/androguard | androguard/decompiler/decompile.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/decompile.py | Apache-2.0 |
def process_and_show(self) -> None:
"""
Run :meth:`process` and :meth:`show_source` after each other.
"""
for name, klass in sorted(self.classes.items()):
logger.debug('Processing class: %s', name)
if not isinstance(klass, DvClass):
klass = DvClass... |
Run :meth:`process` and :meth:`show_source` after each other.
| process_and_show | python | androguard/androguard | androguard/decompiler/decompile.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/decompile.py | Apache-2.0 |
def get_ast(self) -> dict:
"""
Processes each class with AST enabled and returns a dictionary with all single ASTs
Classnames as keys.
:return: an dictionary for all classes
:rtype: dict
"""
ret = dict()
for name, cls in sorted(self.classes.items()):
... |
Processes each class with AST enabled and returns a dictionary with all single ASTs
Classnames as keys.
:return: an dictionary for all classes
:rtype: dict
| get_ast | python | androguard/androguard | androguard/decompiler/decompile.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/decompile.py | Apache-2.0 |
def __init__(self, vm: DEX, vmx: Analysis) -> None:
"""
Decompiler wrapper for DAD: **D**AD is **A** **D**ecompiler
DAD is the androguard internal decompiler.
This Method does not use the :class:`~androguard.decompiler.decompile.DvMachine` but
creates :class:`~androguard.decompi... |
Decompiler wrapper for DAD: **D**AD is **A** **D**ecompiler
DAD is the androguard internal decompiler.
This Method does not use the :class:`~androguard.decompiler.decompile.DvMachine` but
creates :class:`~androguard.decompiler.decompile.DvClass` and
:class:`~androguard.decompil... | __init__ | python | androguard/androguard | androguard/decompiler/decompiler.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/decompiler.py | Apache-2.0 |
def remove_node(self, node):
"""
Remove the node from the graph, removes also all connections.
:param androguard.decompiler.node.Node node: the node to remove
"""
preds = self.reverse_edges.get(node, [])
for pred in preds:
self.edges[pred].remove(node)
... |
Remove the node from the graph, removes also all connections.
:param androguard.decompiler.node.Node node: the node to remove
| remove_node | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def compute_rpo(self):
"""
Number the nodes in reverse post order.
An RPO traversal visit as many predecessors of a node as possible
before visiting the node itself.
"""
nb = len(self.nodes) + 1
for node in self.post_order():
node.num = nb - node.po
... |
Number the nodes in reverse post order.
An RPO traversal visit as many predecessors of a node as possible
before visiting the node itself.
| compute_rpo | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def post_order(self):
"""
Yields the :class`~androguard.decompiler.node.Node`s of the graph in post-order i.e we visit all the
children of a node before visiting the node itself.
"""
def _visit(n, cnt):
visited.add(n)
for suc in self.all_sucs(n):
... |
Yields the :class`~androguard.decompiler.node.Node`s of the graph in post-order i.e we visit all the
children of a node before visiting the node itself.
| post_order | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def draw(self, name, dname, draw_branches=True):
"""
Writes the current graph as a PNG file
:param str name: filename (without .png)
:param str dname: directory of the output png
:param draw_branches:
:return:
"""
import os
from pydot import Dot,... |
Writes the current graph as a PNG file
:param str name: filename (without .png)
:param str dname: directory of the output png
:param draw_branches:
:return:
| draw | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def split_if_nodes(graph):
"""
Split IfNodes in two nodes, the first node is the header node, the
second one is only composed of the jump condition.
"""
node_map = {n: n for n in graph}
to_update = set()
for node in graph.nodes[:]:
if node.type.is_cond:
if len(node.get_in... |
Split IfNodes in two nodes, the first node is the header node, the
second one is only composed of the jump condition.
| split_if_nodes | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def simplify(graph):
"""
Simplify the CFG by merging/deleting statement nodes when possible:
If statement B follows statement A and if B has no other predecessor
besides A, then we can merge A and B into a new statement node.
We also remove nodes which do nothing except redirecting the control
f... |
Simplify the CFG by merging/deleting statement nodes when possible:
If statement B follows statement A and if B has no other predecessor
besides A, then we can merge A and B into a new statement node.
We also remove nodes which do nothing except redirecting the control
flow (nodes which only contai... | simplify | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def bfs(start):
"""
Breadth first search
Yields all nodes found from the starting point
:param start: start node
"""
to_visit = [start]
visited = {start}
while to_visit:
node = to_visit.pop(0)
yield node
if node.exception_analysis:
for _, _, exceptio... |
Breadth first search
Yields all nodes found from the starting point
:param start: start node
| bfs | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def construct(start_block, vmap, exceptions):
"""
Constructs a CFG
:param androguard.core.analysis.analysis.DEXBasicBlock start_block: The startpoint
:param vmap: variable mapping
:param exceptions: list of androguard.core.analysis.analysis.ExceptionAnalysis
:rtype: Graph
"""
bfs_block... |
Constructs a CFG
:param androguard.core.analysis.analysis.DEXBasicBlock start_block: The startpoint
:param vmap: variable mapping
:param exceptions: list of androguard.core.analysis.analysis.ExceptionAnalysis
:rtype: Graph
| construct | python | androguard/androguard | androguard/decompiler/graph.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/graph.py | Apache-2.0 |
def __init__(self, value, atype, int_value=None, descriptor=None):
"""
:param value:
:param atype: the type of the constant as described in https://source.android.com/devices/tech/dalvik/dex-format.html#typedescriptor
:param int_value:
:param descriptor:
"""
self... |
:param value:
:param atype: the type of the constant as described in https://source.android.com/devices/tech/dalvik/dex-format.html#typedescriptor
:param int_value:
:param descriptor:
| __init__ | python | androguard/androguard | androguard/decompiler/instruction.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/instruction.py | Apache-2.0 |
def build_path(graph, node1, node2, path=None):
"""
Build the path from node1 to node2.
The path is composed of all the nodes between node1 and node2,
node1 excluded. Although if there is a loop starting from node1, it will be
included in the path.
"""
if path is None:
path = []
... |
Build the path from node1 to node2.
The path is composed of all the nodes between node1 and node2,
node1 excluded. Although if there is a loop starting from node1, it will be
included in the path.
| build_path | python | androguard/androguard | androguard/decompiler/util.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/util.py | Apache-2.0 |
def merge_inner(clsdict):
"""
Merge the inner class(es) of a class:
e.g class A { ... } class A$foo{ ... } class A$bar{ ... }
==> class A { class foo{...} class bar{...} ... }
"""
samelist = False
done = {}
while not samelist:
samelist = True
classlist = list(clsdict.keys... |
Merge the inner class(es) of a class:
e.g class A { ... } class A$foo{ ... } class A$bar{ ... }
==> class A { class foo{...} class bar{...} ... }
| merge_inner | python | androguard/androguard | androguard/decompiler/util.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/util.py | Apache-2.0 |
def get_type(atype: str, size: int = None) -> str:
"""
Retrieve the java type of a descriptor (e.g : I)
"""
res = TYPE_DESCRIPTOR.get(atype)
if res is None:
if atype[0] == 'L':
if atype.startswith('Ljava/lang'):
res = atype[1:-1].lstrip('java/lang/').replace('/', ... |
Retrieve the java type of a descriptor (e.g : I)
| get_type | python | androguard/androguard | androguard/decompiler/util.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/util.py | Apache-2.0 |
def get_params_type(descriptor: str) -> list[str]:
"""
Return the parameters type of a descriptor (e.g (IC)V)
"""
params = descriptor.split(')')[0][1:].split()
if params:
return [param for param in params]
return [] |
Return the parameters type of a descriptor (e.g (IC)V)
| get_params_type | python | androguard/androguard | androguard/decompiler/util.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/util.py | Apache-2.0 |
def create_png(
cls_name: str, meth_name: str, graph: Graph, dir_name: str = 'graphs2'
) -> None:
"""
Creates a PNG from a given :class:`~androguard.decompiler.graph.Graph`.
:param str cls_name: name of the class
:param str meth_name: name of the method
:param androguard.decompiler.graph.Graph ... |
Creates a PNG from a given :class:`~androguard.decompiler.graph.Graph`.
:param str cls_name: name of the class
:param str meth_name: name of the method
:param androguard.decompiler.graph.Graph graph:
:param str dir_name: output directory
| create_png | python | androguard/androguard | androguard/decompiler/util.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/util.py | Apache-2.0 |
def string(s):
"""
Convert a string to a escaped ASCII representation including quotation marks
:param s: a string
:return: ASCII escaped string
"""
ret = ['"']
for c in s:
if ' ' <= c < '\x7f':
if c == "'" or c == '"' or c == '\\':
ret.append('\\')
... |
Convert a string to a escaped ASCII representation including quotation marks
:param s: a string
:return: ASCII escaped string
| string | python | androguard/androguard | androguard/decompiler/writer.py | https://github.com/androguard/androguard/blob/master/androguard/decompiler/writer.py | Apache-2.0 |
def type(self) -> str:
"""Gets the type of the Block as a simple short string for use in pattern matching"""
return "oneway"
if self.unsupported_call:
type_name = "unsupported type"
elif self.block.errors:
type_name = "error"
elif self.block.direction == ... | Gets the type of the Block as a simple short string for use in pattern matching | type | python | androguard/androguard | androguard/ui/data_types.py | https://github.com/androguard/androguard/blob/master/androguard/ui/data_types.py | Apache-2.0 |
def passes(self):
"""
FUNCTION passes
Brief - Returns whether a block should be displayed
Description -
Returns TRUE if the block should be shown
Returns FALSE if the block should no be shown
The code checks if the filter passes th... |
FUNCTION passes
Brief - Returns whether a block should be displayed
Description -
Returns TRUE if the block should be shown
Returns FALSE if the block should no be shown
The code checks if the filter passes the checks, and then tailors th... | passes | python | androguard/androguard | androguard/ui/filter.py | https://github.com/androguard/androguard/blob/master/androguard/ui/filter.py | Apache-2.0 |
def _all_children(self):
"""
List of child objects, including padding & borders.
"""
def get():
result = []
# Padding top.
if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM):
result.append(Window(width=D(preferred=0)))
... |
List of child objects, including padding & borders.
| _all_children | python | androguard/androguard | androguard/ui/table.py | https://github.com/androguard/androguard/blob/master/androguard/ui/table.py | Apache-2.0 |
def testMultiDexExternal(self):
"""
Test if classes are noted as external if not both zips are opened
"""
from zipfile import ZipFile
with ZipFile(os.path.join(test_dir, "data/APK/multidex.apk")) as myzip:
c1 = myzip.read("classes.dex")
c2 = myzip.read("c... |
Test if classes are noted as external if not both zips are opened
| testMultiDexExternal | python | androguard/androguard | tests/test_analysis.py | https://github.com/androguard/androguard/blob/master/tests/test_analysis.py | Apache-2.0 |
def testXrefs(self):
"""Test if XREFs produce the correct results"""
with open(os.path.join(test_dir, "data/APK/classes.dex"), "rb") as fd:
d = DEX(fd.read())
dx = analysis.Analysis(d)
dx.create_xref()
testcls = dx.classes['Ltests/androguard/TestActivity;']
... | Test if XREFs produce the correct results | testXrefs | python | androguard/androguard | tests/test_analysis.py | https://github.com/androguard/androguard/blob/master/tests/test_analysis.py | Apache-2.0 |
def testXrefOffsets(self):
"""Tests if String offsets in bytecode are correctly stored"""
_, _, dx = AnalyzeDex(
os.path.join(test_dir, "data/APK/AnalysisTest.dex")
)
self.assertEqual(len(dx.get_strings()), 21)
self.assertIsInstance(
dx.strings['Hello wor... | Tests if String offsets in bytecode are correctly stored | testXrefOffsets | python | androguard/androguard | tests/test_analysis.py | https://github.com/androguard/androguard/blob/master/tests/test_analysis.py | Apache-2.0 |
def testXrefOffsetsFields(self):
"""Tests if Field offsets in bytecode are correctly stored"""
_, _, dx = AnalyzeDex(
os.path.join(test_dir, "data/APK/FieldsTest.dex")
)
self.assertEqual(len(dx.get_strings()), 20)
self.assertIn('hello world', dx.strings.keys())
... | Tests if Field offsets in bytecode are correctly stored | testXrefOffsetsFields | python | androguard/androguard | tests/test_analysis.py | https://github.com/androguard/androguard/blob/master/tests/test_analysis.py | Apache-2.0 |
def testAPKCert(self):
"""
Test if certificates are correctly unpacked from the SignatureBlock files
:return:
"""
a = APK(
os.path.join(test_dir, 'data/APK/TestActivity.apk'),
skip_analysis=True,
)
cert = a.get_certificate_der(a.get_signatu... |
Test if certificates are correctly unpacked from the SignatureBlock files
:return:
| testAPKCert | python | androguard/androguard | tests/test_apk.py | https://github.com/androguard/androguard/blob/master/tests/test_apk.py | Apache-2.0 |
def testAPKCertFingerprint(self):
"""
Test if certificates are correctly unpacked from the SignatureBlock files
Check if fingerprints matches
:return:
"""
from hashlib import md5, sha1, sha256
a = APK(
os.path.join(test_dir, 'data/APK/TestActivity.ap... |
Test if certificates are correctly unpacked from the SignatureBlock files
Check if fingerprints matches
:return:
| testAPKCertFingerprint | python | androguard/androguard | tests/test_apk.py | https://github.com/androguard/androguard/blob/master/tests/test_apk.py | Apache-2.0 |
def testPermissionLoading(self):
"""Test if fallbacks for permission lists are working"""
import re
from androguard.core.androconf import (
CONF,
InvalidResourceError,
load_api_specific_resource_module,
)
from androguard.core.api_specific_reso... | Test if fallbacks for permission lists are working | testPermissionLoading | python | androguard/androguard | tests/test_apk.py | https://github.com/androguard/androguard/blob/master/tests/test_apk.py | Apache-2.0 |
def testShortNamesInManifest(self):
"""Test if shortnames are correctly handled"""
a = apk.APK(
os.path.join(test_dir, 'data/APK/AndroidManifest_ShortName.apk')
)
self.assertEqual(a.get_package(), 'com.android.galaxy4')
self.assertEqual(len(a.get_activities()), 1)
... | Test if shortnames are correctly handled | testShortNamesInManifest | python | androguard/androguard | tests/test_apk.py | https://github.com/androguard/androguard/blob/master/tests/test_apk.py | Apache-2.0 |
def testResourceNames(self):
"""
Test if the resource name translation works
"""
arsc = self.apk.get_android_resources()
self.assertEqual(
arsc.get_resource_xml_name(0x7F040001),
"@tests.androguard:string/app_name",
)
self.assertEqual(
... |
Test if the resource name translation works
| testResourceNames | python | androguard/androguard | tests/test_arsc.py | https://github.com/androguard/androguard/blob/master/tests/test_arsc.py | Apache-2.0 |
def xml_compare(x1, x2, reporter=None):
"""
Compare two XML files
x1 must be the plain version
x2 must be the version generated by aapt
"""
if x1.tag != x2.tag:
if reporter:
reporter('Tags do not match: {} and {}'.format(x1.tag, x2.tag))
return False
for name, val... |
Compare two XML files
x1 must be the plain version
x2 must be the version generated by aapt
| xml_compare | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testReplacement(self):
"""
Test that the replacements for attributes, names and values are working
:return:
"""
# Fake, Empty AXML file
a = axml.AXMLPrinter(
b"\x03\x00\x08\x00\x24\x00\x00\x00"
b"\x01\x00\x1c\x00\x1c\x00\x00\x00"
b"... |
Test that the replacements for attributes, names and values are working
:return:
| testReplacement | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testNoStringPool(self):
"""Test if a single header without string pool is rejected"""
# |TYPE |LENGTH |FILE LENGTH
a = axml.AXMLPrinter(b"\x03\x00\x08\x00\x08\x00\x00\x00")
self.assertFalse(a.is_valid()) | Test if a single header without string pool is rejected | testNoStringPool | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testTooSmallFile(self):
"""Test if a very short file is rejected"""
# |TYPE |LENGTH |FILE LENGTH
a = axml.AXMLPrinter(b"\x03\x00\x08\x00\x08\x00\x00")
self.assertFalse(a.is_valid()) | Test if a very short file is rejected | testTooSmallFile | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testWrongHeaderSize(self):
"""Test if a wrong header size is rejected"""
a = axml.AXMLPrinter(
b"\x03\x00\x10\x00\x2c\x00\x00\x00"
b"\x00\x00\x00\x00\x00\x00\x00\x00"
b"\x01\x00\x1c\x00\x1c\x00\x00\x00"
b"\x00\x00\x00\x00\x00\x00\x00\x00"
b... | Test if a wrong header size is rejected | testWrongHeaderSize | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testWrongStringPoolHeader(self):
"""Test if a wrong header type is rejected"""
a = axml.AXMLPrinter(
b"\x03\x00\x08\x00\x24\x00\x00\x00"
b"\xDE\xAD\x1c\x00\x1c\x00\x00\x00"
b"\x00\x00\x00\x00\x00\x00\x00\x00"
b"\x00\x00\x00\x00"
b"\x00\x00\... | Test if a wrong header type is rejected | testWrongStringPoolHeader | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testWrongStringPoolSize(self):
"""Test if a wrong string pool header size is rejected"""
a = axml.AXMLPrinter(
b"\x03\x00\x08\x00\x2c\x00\x00\x00"
b"\x01\x00\x24\x00\x24\x00\x00\x00"
b"\x00\x00\x00\x00\x00\x00\x00\x00"
b"\x00\x00\x00\x00\x00\x00\x00\x0... | Test if a wrong string pool header size is rejected | testWrongStringPoolSize | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testArscHeader(self):
"""Test if wrong arsc headers are rejected"""
with self.assertRaises(axml.ResParserError) as cnx:
axml.ARSCHeader(io.BufferedReader(io.BytesIO(b"\x02\x01")))
self.assertIn("Can not read over the buffer size", str(cnx.exception))
with self.assertRais... | Test if wrong arsc headers are rejected | testArscHeader | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testNonZeroStyleOffset(self):
"""
Test if a nonzero style offset in the string section causes problems
if the counter is 0
"""
filename = "data/AXML/AndroidManifestNonZeroStyle.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap = axml.AXMLPri... |
Test if a nonzero style offset in the string section causes problems
if the counter is 0
| testNonZeroStyleOffset | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testNonTerminatedString(self):
"""
Test if non-null terminated strings are detected.
This sample even segfaults aapt...
"""
filename = "data/AXML/AndroidManifest_StringNotTerminated.xml"
with self.assertRaises(axml.ResParserError) as cnx:
with open(os.pat... |
Test if non-null terminated strings are detected.
This sample even segfaults aapt...
| testNonTerminatedString | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testExtraNamespace(self):
"""
Test if extra namespaces cause problems
"""
filename = "data/AXML/AndroidManifestExtraNamespace.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap = axml.AXMLPrinter(f.read())
self.assertIsInstance(ap, axml.AXMLP... |
Test if extra namespaces cause problems
| testExtraNamespace | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testTextChunksWithXML(self):
"""
Test for Text chunks containing XML
"""
filename = "data/AXML/AndroidManifestTextChunksXML.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap = axml.AXMLPrinter(f.read())
self.assertIsInstance(ap, axml.AXMLPri... |
Test for Text chunks containing XML
| testTextChunksWithXML | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testWrongFilesize(self):
"""
Assert that files with a broken filesize are not parsed
"""
filename = "data/AXML/AndroidManifestWrongFilesize.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
a = axml.AXMLPrinter(f.read())
self.assertFalse(a.is_v... |
Assert that files with a broken filesize are not parsed
| testWrongFilesize | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testNullbytes(self):
"""
Assert that Strings with nullbytes are handled correctly
"""
filename = "data/AXML/AndroidManifestNullbytes.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap = axml.AXMLPrinter(f.read())
self.assertIsInstance(ap, axm... |
Assert that Strings with nullbytes are handled correctly
| testNullbytes | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testMaskingNamespace(self):
"""
Assert that Namespaces which are used in a tag and the tag is closed
are actually correctly parsed.
"""
filename = "data/AXML/AndroidManifestMaskingNamespace.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap =... |
Assert that Namespaces which are used in a tag and the tag is closed
are actually correctly parsed.
| testMaskingNamespace | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testDoubleNamespace(self):
"""
Test if weird namespace constelations cause problems
"""
filename = "data/AXML/AndroidManifestDoubleNamespace.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap = axml.AXMLPrinter(f.read())
self.assertIsInstance... |
Test if weird namespace constelations cause problems
| testDoubleNamespace | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testPackers(self):
"""
Assert that Packed files are read
"""
filename = "data/AXML/AndroidManifestLiapp.xml"
with open(os.path.join(test_dir, filename), "rb") as f:
ap = axml.AXMLPrinter(f.read())
self.assertIsInstance(ap, axml.AXMLPrinter)
self.a... |
Assert that Packed files are read
| testPackers | python | androguard/androguard | tests/test_axml.py | https://github.com/androguard/androguard/blob/master/tests/test_axml.py | Apache-2.0 |
def testCallgraphTotalNodesEdges(self):
"""test callgraph generated with default parameter values"""
callgraph = self.dx.get_call_graph()
total_nodes, total_external_nodes, total_internal_nodes = (
self._get_num_nodes(callgraph)
)
# ensure total of internal and exte... | test callgraph generated with default parameter values | testCallgraphTotalNodesEdges | python | androguard/androguard | tests/test_callgraph.py | https://github.com/androguard/androguard/blob/master/tests/test_callgraph.py | Apache-2.0 |
def testCallgraphFilterClassname(self):
"""test callgraph with classname filter parameter"""
callgraph = self.dx.get_call_graph(classname='Ltests/androguard/*')
total_nodes, total_external_nodes, total_internal_nodes = (
self._get_num_nodes(callgraph)
)
self.assertE... | test callgraph with classname filter parameter | testCallgraphFilterClassname | python | androguard/androguard | tests/test_callgraph.py | https://github.com/androguard/androguard/blob/master/tests/test_callgraph.py | Apache-2.0 |
def testCallgraphFilterMethodname(self):
"""test callgraph with methodname filter parameter"""
callgraph = self.dx.get_call_graph(methodname='Test*')
total_nodes, total_external_nodes, total_internal_nodes = (
self._get_num_nodes(callgraph)
)
self.assertEqual(total_... | test callgraph with methodname filter parameter | testCallgraphFilterMethodname | python | androguard/androguard | tests/test_callgraph.py | https://github.com/androguard/androguard/blob/master/tests/test_callgraph.py | Apache-2.0 |
def testCallgraphFilterDescriptor(self):
"""test callgraph with descriptor filter parameter"""
callgraph = self.dx.get_call_graph(
descriptor='\(LTestDefaultPackage;\sI\sI\sLTestDefaultPackage\$TestInnerClass;\)V'
)
total_nodes, total_external_nodes, total_internal_nodes = (... | test callgraph with descriptor filter parameter | testCallgraphFilterDescriptor | python | androguard/androguard | tests/test_callgraph.py | https://github.com/androguard/androguard/blob/master/tests/test_callgraph.py | Apache-2.0 |
def testDecompileDefaults(self):
"""test decompile command using default cli settings"""
export_apps_to_format(
None,
self.s,
os.path.join(test_dir, 'tmp_TestActivity_decompilation'),
None,
False,
None,
None,
) | test decompile command using default cli settings | testDecompileDefaults | python | androguard/androguard | tests/test_cli_decompile.py | https://github.com/androguard/androguard/blob/master/tests/test_cli_decompile.py | Apache-2.0 |
def testDefUseGCD(self, mock_reach_def):
"""Test def use with the GCD function above."""
n1 = self._CreateMockNode('n1', 0, [(['a'], 'c'), (['b'], 'd')])
n2 = self._CreateMockNode('n2', 2, [(['c'], None)])
n3 = self._CreateMockNode('n3', 3, [(['d'], 'ret')])
n4 = self._CreateMock... | Test def use with the GCD function above. | testDefUseGCD | python | androguard/androguard | tests/test_decompiler_dataflow.py | https://github.com/androguard/androguard/blob/master/tests/test_decompiler_dataflow.py | Apache-2.0 |
def testVMClass(self):
"""test number of ClassDefItems, StringDataItems, FieldIdItems, and MethodIdItems"""
num_class_def_items = 0
num_strings_data_items = 0
num_field_id_items = 0
num_method_id_items = 0
# the below field exists in the fieldIds list, but
# the... | test number of ClassDefItems, StringDataItems, FieldIdItems, and MethodIdItems | testVMClass | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testInstructions(self):
"""Tests if all instructions are at least covered"""
# Set the seed here, so we have reproduceable results later
random.seed(1337)
for op_value in range(0, 256):
ins = dex.DALVIK_OPCODES_FORMAT[op_value][0]
name = dex.DALVIK_OPCODES_FO... | Tests if all instructions are at least covered | testInstructions | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testNOP(self):
"""test if NOP instructions are parsed"""
instruction = dex.Instruction10x(
MockClassManager(), bytearray(b"\x00\x00")
)
self.assertEqual(instruction.get_name(), "nop") | test if NOP instructions are parsed | testNOP | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testLinearSweepSwitch(self):
"""test if switch payloads are unpacked correctly"""
bytecode = bytearray(
binascii.unhexlify(
'2B02140000001300110038030400130063000F001300170028F913002A0028F6'
'1300480028F3000000010300010000000A0000000D00000010000000'
... | test if switch payloads are unpacked correctly | testLinearSweepSwitch | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testLSAArrays(self):
"""Test if fill-array-data-payload is parsed"""
bytecode = bytearray(
binascii.unhexlify(
'12412310030026002D0000005B30000012702300050026002B0000005B300300'
'1250230004002600350000005B300100231007002600380000005B3002001220'
... | Test if fill-array-data-payload is parsed | testLSAArrays | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testWrongInstructions(self):
"""Test if unknown instructions raise an InvalidInstruction error"""
with self.assertRaises(dex.InvalidInstruction):
ins = list(
dex.LinearSweepAlgorithm.get_instructions(
MockClassManager(), 1, bytearray(b"\xff\xab"), 0
... | Test if unknown instructions raise an InvalidInstruction error | testWrongInstructions | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testIncompleteInstruction(self):
"""Test if incomplete bytecode log an error"""
# Test if instruction can be parsed
self.assertIsInstance(
dex.Instruction51l(
MockClassManager(),
bytearray(b'\x18\x01\x23\x23\x00\xff\x99\x11\x22\x22'),
)... | Test if incomplete bytecode log an error | testIncompleteInstruction | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testInstruction21h(self):
"""Test function of Instruction 21h used for const{,-wide}/high16"""
ins = dex.Instruction21h(
MockClassManager(), bytearray([0x15, 0x00, 0x42, 0x11])
)
self.assertEqual(ins.get_op_value(), 0x15)
self.assertEqual(ins.get_literals(), [0x11... | Test function of Instruction 21h used for const{,-wide}/high16 | testInstruction21h | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testInstruction51l(self):
"""test the functionality of const-wide"""
ins = dex.Instruction51l(
MockClassManager(),
bytearray(
[0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
),
)
self.assertEqual(ins.get_op_value(), 0x1... | test the functionality of const-wide | testInstruction51l | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testInstruction11n(self):
"""Test the functionality for Instruction 11n (only used for const/4)"""
tests = [
(0x00, 0, 0),
(0x13, 3, 1),
(0x10, 0, 1),
(0x11, 1, 1),
(0x71, 1, 7),
(0xF0, 0, -1),
(0x61, 1, 6),
... | Test the functionality for Instruction 11n (only used for const/4) | testInstruction11n | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testInstruction21s(self):
"""Test functionality of Instruction 21s (const/16, const-wide/16)"""
# Both instructions have the same format, the difference is that they either write into 32bit or 64bit registers
# But this does not matter for us...
tests = [
([0x01, 0x0E, 0... | Test functionality of Instruction 21s (const/16, const-wide/16) | testInstruction21s | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testInstruction31i(self):
"""Test functionality of Instruction31i (const, const-wide/32)"""
# const is often used to load resources...
tests = [
([0x00, 0xFF, 0xFF, 0xFF, 0x1F], 0, 0x1FFFFFFF),
([0x00, 0x62, 0x00, 0x07, 0x7F], 0, 0x7F070062),
([0x00, 0x74... | Test functionality of Instruction31i (const, const-wide/32) | testInstruction31i | python | androguard/androguard | tests/test_dex.py | https://github.com/androguard/androguard/blob/master/tests/test_dex.py | Apache-2.0 |
def testClassManager(self):
"""Test if the classmanager has the same items"""
from androguard.core.mutf8 import decode
fname = os.path.join(test_dir, 'data/APK/classes.dex')
parsed = parse_dex.read_dex(fname)
with open(fname, "rb") as f:
d = dex.DEX(f.read())
... | Test if the classmanager has the same items | testClassManager | python | androguard/androguard | tests/test_dexcodeparsing.py | https://github.com/androguard/androguard/blob/master/tests/test_dexcodeparsing.py | Apache-2.0 |
def visible_gpu(gpus):
"""
set visible gpu.
can be a single id, or a list
return a list of new gpus ids
"""
gpus = [gpus] if isinstance(gpus, int) else list(gpus)
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(list(map(str, gpus)))
return list(range(len(gpus))) |
set visible gpu.
can be a single id, or a list
return a list of new gpus ids
| visible_gpu | python | open-mmlab/mmskeleton | deprecated/origin_stgcn_repo/torchlight/torchlight/gpu.py | https://github.com/open-mmlab/mmskeleton/blob/master/deprecated/origin_stgcn_repo/torchlight/torchlight/gpu.py | Apache-2.0 |
def occupy_gpu(gpus=None):
"""
make program appear on nvidia-smi.
"""
if gpus is None:
torch.zeros(1).cuda()
else:
gpus = [gpus] if isinstance(gpus, int) else list(gpus)
for g in gpus:
torch.zeros(1).cuda(g) |
make program appear on nvidia-smi.
| occupy_gpu | python | open-mmlab/mmskeleton | deprecated/origin_stgcn_repo/torchlight/torchlight/gpu.py | https://github.com/open-mmlab/mmskeleton/blob/master/deprecated/origin_stgcn_repo/torchlight/torchlight/gpu.py | Apache-2.0 |
def generate(
self,
n: int = 1,
prompt: str = "",
prepend_bos: bool = None,
min_length: int = None,
max_length: int = 256,
temperature: float = 0.7,
do_sample: bool = True,
return_as_list: bool = False,
seed: int = None,
pad_token_i... |
Generates texts using the stored Transformers model.
Currently generates text using the model's generate() function.
:param n: Numbers of texts to generate.
:param prompt: Text to force the generated text to start with
:param max_length: Maximum length for the generated text
... | generate | python | minimaxir/aitextgen | aitextgen/aitextgen.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/aitextgen.py | MIT |
def generate_samples(
self, n: int = 3, temperatures: List[float] = [0.7, 1.0, 1.2], **kwargs
) -> None:
"""
Prints multiple samples to console at specified temperatures.
"""
for temperature in temperatures:
print("#" * 20 + f"\nTemperature: {temperature}\n" + "#... |
Prints multiple samples to console at specified temperatures.
| generate_samples | python | minimaxir/aitextgen | aitextgen/aitextgen.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/aitextgen.py | MIT |
def train(
self,
train_data: Union[str, TokenDataset],
output_dir: str = "trained_model",
fp16: bool = False,
fp16_opt_level: str = "O1",
n_gpu: int = -1,
tpu_cores: int = 0,
max_grad_norm: float = 0.5,
gradient_accumulation_steps: int = 1,
... |
Trains/finetunes the model on the provided file/dataset using pytorch-lightning.
:param train_data: Either a TokenDataset containing the samples to be trained, or
a string containing the text to be trained (shortcut instead of dataset)
:param output_dir: A string indicating where to st... | train | python | minimaxir/aitextgen | aitextgen/aitextgen.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/aitextgen.py | MIT |
def cross_train(
self,
inputs: List[TokenDataset],
learning_rate: Union[float, List[float]] = 1e-4,
num_steps: Union[int, List[int]] = 4000,
run_id: str = f"ATG_{datetime.utcnow():%Y%m%d_%H%M%S}",
**kwargs,
) -> None:
"""Trains a model across multiple input da... | Trains a model across multiple input datasets, with automatic
decay after each run. | cross_train | python | minimaxir/aitextgen | aitextgen/aitextgen.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/aitextgen.py | MIT |
def export(
self,
quantize: bool = True,
) -> None:
"""
Exports the model, with optional quantization
""" |
Exports the model, with optional quantization
| export | python | minimaxir/aitextgen | aitextgen/aitextgen.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/aitextgen.py | MIT |
def generate_cli(to_file: bool = True, **kwargs):
"""Generate from a trained model, or download one if not present."""
ai = aitextgen(**kwargs)
if to_file:
ai.generate_to_file(**kwargs)
else:
ai.generate(**kwargs) | Generate from a trained model, or download one if not present. | generate_cli | python | minimaxir/aitextgen | aitextgen/cli.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/cli.py | MIT |
def mount_gdrive():
"""Mounts the user's Google Drive in Colaboratory."""
assert (
"google.colab" in sys.modules
), "You must be in Colaboratory to mount your Google Drive"
drive.mount("/content/drive") | Mounts the user's Google Drive in Colaboratory. | mount_gdrive | python | minimaxir/aitextgen | aitextgen/colab.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/colab.py | MIT |
def copy_file_to_gdrive(file_path, to_folder=None):
"""Copies a file to a mounted Google Drive."""
is_mounted()
if to_folder:
dest_path = os.path.join("/content/drive/MyDrive/", to_folder, file_path)
else:
dest_path = os.path.join("/content/drive/MyDrive/", file_path)
shutil.copyfi... | Copies a file to a mounted Google Drive. | copy_file_to_gdrive | python | minimaxir/aitextgen | aitextgen/colab.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/colab.py | MIT |
def copy_file_from_gdrive(file_path, from_folder=None):
"""Copies a file from a mounted Google Drive."""
is_mounted()
if from_folder:
source_path = os.path.join("/content/drive/MyDrive/", from_folder, file_path)
else:
source_path = os.path.join("/content/drive/MyDrive/", file_path)
... | Copies a file from a mounted Google Drive. | copy_file_from_gdrive | python | minimaxir/aitextgen | aitextgen/colab.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/colab.py | MIT |
def create_gdrive_folder(folder_name):
"""Creates a folder in a mounted Google Drive."""
is_mounted()
folder_path = os.path.join("/content/drive/MyDrive/", folder_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path) | Creates a folder in a mounted Google Drive. | create_gdrive_folder | python | minimaxir/aitextgen | aitextgen/colab.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/colab.py | MIT |
def get_lines_in_file(file_path: str, newline: str = None) -> int:
"""
Returns the number of lines in a file to build progress bar.
c.f. https://stackoverflow.com/a/16108605/9314418
"""
with open(file_path, "r", encoding="utf-8", newline=newline) as f:
return sum(1 for row in f) |
Returns the number of lines in a file to build progress bar.
c.f. https://stackoverflow.com/a/16108605/9314418
| get_lines_in_file | python | minimaxir/aitextgen | aitextgen/TokenDataset.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/TokenDataset.py | MIT |
def get_lines_in_file_csv(file_path: str, header: bool = True) -> int:
"""
Returns the number of lines in a CSV to build progress bar.
c.f. https://stackoverflow.com/a/16108605/9314418
"""
with open(file_path, "r", encoding="utf-8") as f:
if header:
f.readline()
reader =... |
Returns the number of lines in a CSV to build progress bar.
c.f. https://stackoverflow.com/a/16108605/9314418
| get_lines_in_file_csv | python | minimaxir/aitextgen | aitextgen/TokenDataset.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/TokenDataset.py | MIT |
def get_dtype(vocab_size: int):
"""
Finds the appropriate numpy dtype depending on vocab size.
The highest value for the dtype serves as a placeholder.
"""
if vocab_size < 2**8 - 1:
return np.uint8
elif vocab_size < 2**16 - 1:
return np.uint16
elif vocab_size < 2**32 - 1:
... |
Finds the appropriate numpy dtype depending on vocab size.
The highest value for the dtype serves as a placeholder.
| get_dtype | python | minimaxir/aitextgen | aitextgen/TokenDataset.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/TokenDataset.py | MIT |
def merge_datasets(datasets: List[TokenDataset], equalize: bool = True) -> TokenDataset:
"""
Merges multiple TokenDatasets into a single TokenDataset.
This assumes that you are using the same tokenizer for all TokenDatasets.
:param datasets: A list of TokenDatasets.
:param equalize: Whether to take... |
Merges multiple TokenDatasets into a single TokenDataset.
This assumes that you are using the same tokenizer for all TokenDatasets.
:param datasets: A list of TokenDatasets.
:param equalize: Whether to take an equal amount of samples from all
input datasets (by taking random samples from
each ... | merge_datasets | python | minimaxir/aitextgen | aitextgen/TokenDataset.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/TokenDataset.py | MIT |
def train_tokenizer(
files: Union[str, List[str]],
dropout: float = None,
vocab_size: int = 1000,
min_frequency: int = 2,
prefix: str = "aitextgen",
save_path: str = "",
added_tokens: List[str] = [],
bos_token: str = "<|endoftext|>",
eos_token: str = "<|endoftext|>",
unk_token: s... |
Tokenizes the text(s) as a tokenizer, wrapping the tokenizer package.
See: https://huggingface.co/blog/how-to-train
For consistency, this function makes opinionated assuptions.
:param files: path to file(s) to train tokenizer on
:param dropout: Training dropout
:param vocab_size: Final vocabu... | train_tokenizer | python | minimaxir/aitextgen | aitextgen/tokenizers.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/tokenizers.py | MIT |
def download_gpt2(model_dir: str = "tf_model", model_name: str = "124M") -> None:
"""
Downloads the GPT-2 model (weights only) into the specified directory
from Google Cloud Storage.
If running in Colaboratory or Google Compute Engine,
this is substantially faster (and cheaper for HuggingFace) than... |
Downloads the GPT-2 model (weights only) into the specified directory
from Google Cloud Storage.
If running in Colaboratory or Google Compute Engine,
this is substantially faster (and cheaper for HuggingFace) than using the
default model downloading. However, the model is in TensorFlow,
so the... | download_gpt2 | python | minimaxir/aitextgen | aitextgen/utils.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py | MIT |
def download_file_with_progress(
url_base: str, sub_dir: str, model_name: str, file_name: str
):
"""
General utility for incrementally downloading files from the internet
with progress bar.
Adapted from gpt-2-simple.
"""
# set to download 1MB at a time. This could be much larger with no is... |
General utility for incrementally downloading files from the internet
with progress bar.
Adapted from gpt-2-simple.
| download_file_with_progress | python | minimaxir/aitextgen | aitextgen/utils.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py | MIT |
def set_seed(seed: int):
"""
Sets the seed for all potential generation libraries.
"""
assert isinstance(seed, int), "seed must be an integer."
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) |
Sets the seed for all potential generation libraries.
| set_seed | python | minimaxir/aitextgen | aitextgen/utils.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py | MIT |
def reset_seed():
"""
Resets the seed for all potential generation libraries.
"""
random.seed()
np.random.seed()
# torch.seed()
# torch.cuda.seed_all() |
Resets the seed for all potential generation libraries.
| reset_seed | python | minimaxir/aitextgen | aitextgen/utils.py | https://github.com/minimaxir/aitextgen/blob/master/aitextgen/utils.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.