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 log_image(self, key: str, images: List[Any], step: Optional[int] = None, **kwargs: Any) -> None:
"""Log images (tensors, numpy arrays, PIL Images or file paths).
Optional kwargs are lists passed to each image (ex: caption).
"""
if not isinstance(images, list):
raise Typ... | Log images (tensors, numpy arrays, PIL Images or file paths).
Optional kwargs are lists passed to each image (ex: caption).
| log_image | python | SwanHubX/SwanLab | swanlab/integration/pytorch_lightning.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/pytorch_lightning.py | Apache-2.0 |
def log_audio(self, key: str, audios: List[Any], step: Optional[int] = None, **kwargs: Any) -> None:
r"""Log audios (numpy arrays, or file paths).
Args:
key: The key to be used for logging the audio files
audios: The list of audio file paths, or numpy arrays to be logged
... | Log audios (numpy arrays, or file paths).
Args:
key: The key to be used for logging the audio files
audios: The list of audio file paths, or numpy arrays to be logged
step: The step number to be used for logging the audio files
\**kwargs: Optional kwargs are list... | log_audio | python | SwanHubX/SwanLab | swanlab/integration/pytorch_lightning.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/pytorch_lightning.py | Apache-2.0 |
def log_text(self, key: str, texts: List[Any], step: Optional[int] = None, **kwargs: Any) -> None:
r"""Log texts (numpy arrays, or file paths).
Args:
key: The key to be used for logging the string
audios: The list of string to be logged
step: The step number to be us... | Log texts (numpy arrays, or file paths).
Args:
key: The key to be used for logging the string
audios: The list of string to be logged
step: The step number to be used for logging the string
\**kwargs: Optional kwargs are lists passed to each ``swanlab.Audio`` ins... | log_text | python | SwanHubX/SwanLab | swanlab/integration/pytorch_lightning.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/pytorch_lightning.py | Apache-2.0 |
def after_iteration(self, model: Booster, epoch: int, evals_log: dict) -> bool:
"""Run after each iteration. Return True when training should stop."""
# Log metrics
for data, metric in evals_log.items():
for metric_name, log in metric.items():
swanlab.log({f"{data... | Run after each iteration. Return True when training should stop. | after_iteration | python | SwanHubX/SwanLab | swanlab/integration/xgboost.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/xgboost.py | Apache-2.0 |
def __init__(
self, name: str, symbols: Sequence[str], resolver: ArgumentResponseResolver, client, lib_version
) -> None:
"""Patches the API to log SwanLab Media or metrics."""
# name of the LLM provider, e.g. "Cohere" or "OpenAI" or package name like "Transformers"
self.name = name
... | Patches the API to log SwanLab Media or metrics. | __init__ | python | SwanHubX/SwanLab | swanlab/integration/integration_utils/autologging.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/integration_utils/autologging.py | Apache-2.0 |
def patch(self, run: "SwanLabRun") -> None:
"""Patches the API to log media or metrics to SwanLab."""
for symbol in self.symbols:
# split on dots, e.g. "Client.generate" -> ["Client", "generate"]
symbol_parts = symbol.split(".")
# and get the attribute from the modul... | Patches the API to log media or metrics to SwanLab. | patch | python | SwanHubX/SwanLab | swanlab/integration/integration_utils/autologging.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/integration_utils/autologging.py | Apache-2.0 |
def enable(self, init: AutologInitArgs = None) -> None:
"""Enable autologging.
Args:
init: Optional dictionary of arguments to pass to SwanLab.init().
"""
if self._is_enabled:
print(f"{self._name} autologging is already enabled, disabling and re-enabling.")
... | Enable autologging.
Args:
init: Optional dictionary of arguments to pass to SwanLab.init().
| enable | python | SwanHubX/SwanLab | swanlab/integration/integration_utils/autologging.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/integration_utils/autologging.py | Apache-2.0 |
def import_module_lazy(name: str) -> types.ModuleType:
"""Import a module lazily, only when it is used.
Inspired by importlib.util.LazyLoader, but improved so that the module loading is
thread-safe. Circular dependency between modules can lead to a deadlock if the two
modules are loaded from different ... | Import a module lazily, only when it is used.
Inspired by importlib.util.LazyLoader, but improved so that the module loading is
thread-safe. Circular dependency between modules can lead to a deadlock if the two
modules are loaded from different threads.
| import_module_lazy | python | SwanHubX/SwanLab | swanlab/integration/integration_utils/get_modules.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/integration_utils/get_modules.py | Apache-2.0 |
def get_module(
name: str,
required: Optional[Union[str, bool]] = None,
lazy: bool = True,
) -> Any:
"""Return module or None. Absolute import is required.
:param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
:param (str) required: A string to raise a ValueError if missing
:pa... | Return module or None. Absolute import is required.
:param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
:param (str) required: A string to raise a ValueError if missing
:param (bool) lazy: If True, return a lazy loader for the module.
:return: (module|None) If import succeeds, the module... | get_module | python | SwanHubX/SwanLab | swanlab/integration/integration_utils/get_modules.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/integration_utils/get_modules.py | Apache-2.0 |
def _resolve_edit(
self,
request: Dict[str, Any],
response: Response,
lib_version: str,
time_elapsed: float,
) -> Dict[str, Any]:
"""Resolves the request and response objects for `openai.Edit`."""
request_str = f"\n\n**Instruction**: {request['instruction']}\n... | Resolves the request and response objects for `openai.Edit`. | _resolve_edit | python | SwanHubX/SwanLab | swanlab/integration/openai/resolver.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/openai/resolver.py | Apache-2.0 |
def _resolve_completion(
self,
request: Dict[str, Any],
response: Response,
lib_version: str,
time_elapsed: float,
) -> Dict[str, Any]:
"""Resolves the request and response objects for `openai.Completion`."""
request_str = f"\n\n**Prompt**: {request['prompt']}... | Resolves the request and response objects for `openai.Completion`. | _resolve_completion | python | SwanHubX/SwanLab | swanlab/integration/openai/resolver.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/openai/resolver.py | Apache-2.0 |
def _get_usage_metrics(response: Response, time_elapsed: float) -> UsageMetrics:
"""Gets the usage stats from the response object."""
if response.get("usage"):
usage_stats = UsageMetrics(**response["usage"])
else:
usage_stats = UsageMetrics()
usage_stats.elapsed_t... | Gets the usage stats from the response object. | _get_usage_metrics | python | SwanHubX/SwanLab | swanlab/integration/openai/resolver.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/openai/resolver.py | Apache-2.0 |
def _resolve_completion(
self,
request: Dict[str, Any],
response: Response,
lib_version: str,
time_elapsed: float,
) -> Dict[str, Any]:
"""Resolves the request and response objects for `openai.OpenAI().Completion`."""
request_str = f"\n\n**Prompt**: {request['... | Resolves the request and response objects for `openai.OpenAI().Completion`. | _resolve_completion | python | SwanHubX/SwanLab | swanlab/integration/openai/resolver.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/openai/resolver.py | Apache-2.0 |
def _resolve_chat_completion(
self,
request: Dict[str, Any],
response: Response,
lib_version: str,
time_elapsed: float,
) -> Dict[str, Any]:
"""Resolves the request and response objects for `zhipuai.ZhipuAI().Completion`."""
prompt = io.StringIO()
for ... | Resolves the request and response objects for `zhipuai.ZhipuAI().Completion`. | _resolve_chat_completion | python | SwanHubX/SwanLab | swanlab/integration/zhipuai/resolver.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/integration/zhipuai/resolver.py | Apache-2.0 |
def __init__(
self,
sender_email: str,
receiver_email: str,
password: str,
smtp_server: str = "smtp.gmail.com",
port: int = 587,
language: str = "en",
):
"""
Initialize email callback configuration.
:param sender_email: SMTP account em... |
Initialize email callback configuration.
:param sender_email: SMTP account email address
:param receiver_email: Recipient email address
:param password: SMTP account password
:param smtp_server: SMTP server address
:param port: SMTP server port
:param language: ... | __init__ | python | SwanHubX/SwanLab | swanlab/plugin/notification.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/notification.py | Apache-2.0 |
def _create_email_content(self, error: Optional[str] = None) -> Dict[str, str]:
"""Generate bilingual email content based on experiment status."""
templates = self.DEFAULT_TEMPLATES[self.language]
# Determine email subject and body based on error status
if error:
subject = t... | Generate bilingual email content based on experiment status. | _create_email_content | python | SwanHubX/SwanLab | swanlab/plugin/notification.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/notification.py | Apache-2.0 |
def gen_sign(self, timesteamp: int) -> str:
"""
docs: https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot?lang=zh-CN#9ff32e8e
If the user has configured the signature verification function, this method is required to generate the signature
"""
if not self.secret:
... |
docs: https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot?lang=zh-CN#9ff32e8e
If the user has configured the signature verification function, this method is required to generate the signature
| gen_sign | python | SwanHubX/SwanLab | swanlab/plugin/notification.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/notification.py | Apache-2.0 |
def _initialize_dataframe(self):
"""Initialize the DataFrame based on file existence."""
if self.file_exists:
try:
df = pd.read_csv(self.save_path)
if df.empty:
return self._create_empty_dataframe()
return df
exc... | Initialize the DataFrame based on file existence. | _initialize_dataframe | python | SwanHubX/SwanLab | swanlab/plugin/writer.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/writer.py | Apache-2.0 |
def _create_empty_dataframe(self):
"""Create an empty DataFrame with default columns."""
self.file_exists = False # Treat as a new file
return pd.DataFrame(columns=["project", "exp_name", "description", "datetime", "run_id", "workspace", "logdir", "url"]) | Create an empty DataFrame with default columns. | _create_empty_dataframe | python | SwanHubX/SwanLab | swanlab/plugin/writer.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/writer.py | Apache-2.0 |
def on_run(self, *args, **kwargs):
"""Handle actions to perform on run."""
run = swanlab.get_run()
config = run.config
self.logdir = run.public.swanlog_dir
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# Set experiment URL if available
... | Handle actions to perform on run. | on_run | python | SwanHubX/SwanLab | swanlab/plugin/writer.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/writer.py | Apache-2.0 |
def _handle_existing_file(self, config, headers, row_data):
"""Handle writing to an existing file."""
headers = self.original_headers.copy()
headers_metadata = headers[:8]
headers_config = [header for header in headers[8:] if header.startswith("config/")]
headers_config_dict = {k... | Handle writing to an existing file. | _handle_existing_file | python | SwanHubX/SwanLab | swanlab/plugin/writer.py | https://github.com/SwanHubX/SwanLab/blob/master/swanlab/plugin/writer.py | Apache-2.0 |
def test_from_mol(self, mol):
"""Tests creating a Molecule from an RDKit Mol object."""
if mol:
molecule = Molecule.from_mol(mol, caption="Ethanol")
assert molecule.caption == "Ethanol"
assert isinstance(molecule.pdb_data, str) | Tests creating a Molecule from an RDKit Mol object. | test_from_mol | python | SwanHubX/SwanLab | test/unit/data/modules/object3d/test_molecule.py | https://github.com/SwanHubX/SwanLab/blob/master/test/unit/data/modules/object3d/test_molecule.py | Apache-2.0 |
def test_from_pdb_file(self, pdb_file):
"""Tests creating a Molecule from a PDB file."""
molecule = Molecule.from_pdb_file(pdb_file, caption="Test PDB")
assert molecule.caption == "Test PDB"
assert isinstance(molecule.pdb_data, str)
with open(pdb_file) as f:
assert mo... | Tests creating a Molecule from a PDB file. | test_from_pdb_file | python | SwanHubX/SwanLab | test/unit/data/modules/object3d/test_molecule.py | https://github.com/SwanHubX/SwanLab/blob/master/test/unit/data/modules/object3d/test_molecule.py | Apache-2.0 |
def test_from_sdf_file(self, sdf_file):
"""Tests creating a Molecule from an SDF file."""
molecule = Molecule.from_sdf_file(sdf_file, caption="Test SDF")
assert molecule.caption == "Test SDF"
assert isinstance(molecule.pdb_data, str) | Tests creating a Molecule from an SDF file. | test_from_sdf_file | python | SwanHubX/SwanLab | test/unit/data/modules/object3d/test_molecule.py | https://github.com/SwanHubX/SwanLab/blob/master/test/unit/data/modules/object3d/test_molecule.py | Apache-2.0 |
def test_from_mol_file(self, mol_file):
"""Tests creating a Molecule from a Mol file."""
molecule = Molecule.from_mol_file(mol_file, caption="Test Mol")
assert molecule.caption == "Test Mol"
assert isinstance(molecule.pdb_data, str) | Tests creating a Molecule from a Mol file. | test_from_mol_file | python | SwanHubX/SwanLab | test/unit/data/modules/object3d/test_molecule.py | https://github.com/SwanHubX/SwanLab/blob/master/test/unit/data/modules/object3d/test_molecule.py | Apache-2.0 |
def test_from_smiles(self):
"""Tests creating a Molecule from a SMILES string."""
molecule = Molecule.from_smiles("CCO", caption="Test SMILES")
assert molecule.caption == "Test SMILES"
assert isinstance(molecule.pdb_data, str) | Tests creating a Molecule from a SMILES string. | test_from_smiles | python | SwanHubX/SwanLab | test/unit/data/modules/object3d/test_molecule.py | https://github.com/SwanHubX/SwanLab/blob/master/test/unit/data/modules/object3d/test_molecule.py | Apache-2.0 |
def enum_blocks_static(instructions):
"""
Return a list of basicblock after
statically parsing given instructions
"""
basicblocks = list()
index = 0
# create the first block
new_block = False
end_block = False
block = BasicBlock(instructions[0].offset,
i... |
Return a list of basicblock after
statically parsing given instructions
| enum_blocks_static | python | FuzzingLabs/octopus | octopus/arch/evm/cfg.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/cfg.py | MIT |
def runtime_code_detector(self):
'''Check for presence of runtime code
'''
result = list(re.finditer('60.{2}604052', self.bytecode))
if len(result) > 1:
position = result[1].start()
logging.info("[+] Runtime code detected")
self.loader_code = self.byte... | Check for presence of runtime code
| runtime_code_detector | python | FuzzingLabs/octopus | octopus/arch/evm/disassembler.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/disassembler.py | MIT |
def swarm_hash_detector(self):
'''Check for presence of Swarm hash at the end of bytecode
https://github.com/ethereum/wiki/wiki/Swarm-Hash
'''
#swarm_hash_off = self.bytecode.find('a165627a7a72.*0029')
result = list(re.finditer('a165627a7a7230.*0029', self.bytecode))
... | Check for presence of Swarm hash at the end of bytecode
https://github.com/ethereum/wiki/wiki/Swarm-Hash
| swarm_hash_detector | python | FuzzingLabs/octopus | octopus/arch/evm/disassembler.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/disassembler.py | MIT |
def disassemble(self, bytecode=None, offset=0, r_format='list',
analysis=True):
'''
creation code remove if analysis param is set to True (default)
r_format: ('list' | 'text' | 'reverse')
'''
self.bytecode = bytecode if bytecode else self.bytecode
if... |
creation code remove if analysis param is set to True (default)
r_format: ('list' | 'text' | 'reverse')
| disassemble | python | FuzzingLabs/octopus | octopus/arch/evm/disassembler.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/disassembler.py | MIT |
def emul_sha3_instruction(self, instr, state):
'''Symbolic execution of SHA3 group of opcode'''
# SSA STACK
s0, s1 = state.ssa_stack.pop(), state.ssa_stack.pop()
instr.ssa = SSA(self.ssa_counter, instr.name, args=[s0, s1])
state.ssa_stack.append(instr)
self.ssa_counter +... | Symbolic execution of SHA3 group of opcode | emul_sha3_instruction | python | FuzzingLabs/octopus | octopus/arch/evm/emulator.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/emulator.py | MIT |
def _get_reverse_table(self):
"""Build an internal table used in the assembler."""
reverse_table = {}
for (opcode, (mnemonic, immediate_operand_size,
pops, pushes, gas, description)) in _table.items():
reverse_table[mnemonic] = opcode, mnemonic, immediate_operan... | Build an internal table used in the assembler. | _get_reverse_table | python | FuzzingLabs/octopus | octopus/arch/evm/evm.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/evm.py | MIT |
def group(self):
'''Instruction classification as per the yellow paper'''
classes = {0: 'Stop and Arithmetic Operations',
1: 'Comparison & Bitwise Logic Operations',
2: 'SHA3',
3: 'Environmental Information',
4: 'Block Informati... | Instruction classification as per the yellow paper | group | python | FuzzingLabs/octopus | octopus/arch/evm/instruction.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/evm/instruction.py | MIT |
def __decode_header(self, header, h_data):
"""Decode wasm header
Return tuple (magic, version) of wasm module header
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#high-level-structure
"""
magic = \
h_data.magic.to_bytes(header.magic.... | Decode wasm header
Return tuple (magic, version) of wasm module header
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#high-level-structure
| __decode_header | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_type_section(self, type_section):
"""Decode wasm type section
Return a list of tuple (param_str, return_str)
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#type-section
"""
type_list = []
for idx, entry in enumerate(type_sec... | Decode wasm type section
Return a list of tuple (param_str, return_str)
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#type-section
| __decode_type_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_import_section(self, import_section):
"""Decode import section to tuple of list
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#import-section
"""
entries = import_section.payload.entries
import_list = []
import_func_list = []... | Decode import section to tuple of list
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#import-section
| __decode_import_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_table_section(self, table_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#table-section
"""
# on the MVP, table size == 1
entries = table_section.payload.entries
table_list = []
for idx, entry in enumera... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#table-section
| __decode_table_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_memory_section(self, memory_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#memory-section
"""
# on the MVP, memory size == 1
memory_l = list()
entries = memory_section.payload.entries
for idx, entry in ... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#memory-section
| __decode_memory_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_global_section(self, global_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#global-section
"""
globals_l = list()
for entry in global_section.payload.globals:
fmt = format_kind_global(entry.type.mutability,
... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#global-section
| __decode_global_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_export_section(self, export_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#export-section
"""
entries = export_section.payload.entries
export_list = []
for idx, entry in enumerate(entries):
# field_... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#export-section
| __decode_export_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_element_section(self, element_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#element-section
"""
entries = element_section.payload.entries
element_list = []
for idx, entry in enumerate(entries):
fm... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#element-section
| __decode_element_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_code_section(self, code_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#code-section
"""
bodies = code_section.payload.bodies
code_list = []
for idx, entry in enumerate(bodies):
code_raw = entry.code... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#code-section
| __decode_code_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_data_section(self, data_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#data-section
"""
entries = data_section.payload.entries
data_list = []
for idx, entry in enumerate(entries):
data = entry.data.... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#data-section
| __decode_data_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_name_section(self, name_subsection):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
"""
names_list = list()
if name_subsection.name_type == NAME_SUBSEC_FUNCTION:
subsection_function = name_subsection.pay... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
| __decode_name_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def __decode_unknown_section(self, unknown_section):
"""
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#high-level-structure
"""
sec_name = unknown_section.name.tobytes()
payload = unknown_section.payload.tobytes()
return (sec_name, paylo... |
.. seealso:: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#high-level-structure
| __decode_unknown_section | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def analyze(self):
"""analyse the complete module & extract informations """
# src: https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md
# custom 0 name, .debug_str, ...
# Type 1 Function signature declarations
# Import 2 Import declarations
... | analyse the complete module & extract informations | analyze | python | FuzzingLabs/octopus | octopus/arch/wasm/analyzer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/analyzer.py | MIT |
def enum_func(module_bytecode):
''' return a list of Function
see:: octopus.core.function
'''
functions = list()
analyzer = WasmModuleAnalyzer(module_bytecode)
protos = analyzer.func_prototypes
import_len = len(analyzer.imports_func)
for idx, code in enumerate(analyzer.codes):
... | return a list of Function
see:: octopus.core.function
| enum_func | python | FuzzingLabs/octopus | octopus/arch/wasm/cfg.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/cfg.py | MIT |
def enum_func_name_call_indirect(functions):
''' return a list of function name if they used call_indirect
'''
func_name = list()
# iterate over functions
for func in functions:
for inst in func.instructions:
if inst.name == "call_indirect":
func_name.append(func... | return a list of function name if they used call_indirect
| enum_func_name_call_indirect | python | FuzzingLabs/octopus | octopus/arch/wasm/cfg.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/cfg.py | MIT |
def visualize(self, function=True, simplify=False, ssa=False):
"""Visualize the cfg
used CFGGraph
equivalent to:
graph = CFGGraph(cfg)
graph.view_functions()
"""
graph = CFGGraph(self)
if function:
graph.view_functions(simplify=simplify... | Visualize the cfg
used CFGGraph
equivalent to:
graph = CFGGraph(cfg)
graph.view_functions()
| visualize | python | FuzzingLabs/octopus | octopus/arch/wasm/cfg.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/cfg.py | MIT |
def visualize_call_flow(self, filename="wasm_call_graph_octopus.gv",
format_fname=False):
"""Visualize the cfg call flow graph
"""
nodes, edges = self.get_functions_call_edges()
if format_fname:
nodes_longname, edges = self.get_functions_call_edges... | Visualize the cfg call flow graph
| visualize_call_flow | python | FuzzingLabs/octopus | octopus/arch/wasm/cfg.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/cfg.py | MIT |
def visualize_instrs_per_funcs(self, show=True, save=True,
out_filename="wasm_func_analytic.png",
fontsize=8):
"""Visualize the instructions repartitions per functions
"""
import numpy as np
import matplotlib.pyplot a... | Visualize the instructions repartitions per functions
| visualize_instrs_per_funcs | python | FuzzingLabs/octopus | octopus/arch/wasm/cfg.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/cfg.py | MIT |
def decode_module(module, decode_name_subsections=False):
"""Decodes raw WASM modules, yielding `ModuleFragment`s."""
module_wnd = memoryview(module)
# Read & yield module header.
hdr = ModuleHeader()
hdr_len, hdr_data, _ = hdr.from_raw(None, module_wnd)
yield ModuleFragment(hdr, hdr_data)
... | Decodes raw WASM modules, yielding `ModuleFragment`s. | decode_module | python | FuzzingLabs/octopus | octopus/arch/wasm/decode.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/decode.py | MIT |
def disassemble_opcode(self, bytecode=None, offset=0):
'''
based on decode_bytecode()
https://github.com/athre0z/wasm/blob/master/wasm/decode.py
'''
bytecode_wnd = memoryview(bytecode)
opcode_id = byte2int(bytecode_wnd[0])
# default value
# opcode:(mnem... |
based on decode_bytecode()
https://github.com/athre0z/wasm/blob/master/wasm/decode.py
| disassemble_opcode | python | FuzzingLabs/octopus | octopus/arch/wasm/disassembler.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/disassembler.py | MIT |
def __eq__(self, other):
""" Instructions are equal if all features match """
return self.opcode == other.opcode and\
self.name == other.name and\
self.offset == other.offset and\
self.insn_byte == other.insn_byte and\
self.operand_size == other.operand_s... | Instructions are equal if all features match | __eq__ | python | FuzzingLabs/octopus | octopus/arch/wasm/instruction.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/arch/wasm/instruction.py | MIT |
def disassemble(self, bytecode=None, offset=0, r_format='list'):
"""Generic method to disassemble bytecode
:param bytecode: bytecode sequence
:param offset: start offset
:param r_format: output format ('list'/'text'/'reverse')
:type bytecode: bytes, str
:type offset: int... | Generic method to disassemble bytecode
:param bytecode: bytecode sequence
:param offset: start offset
:param r_format: output format ('list'/'text'/'reverse')
:type bytecode: bytes, str
:type offset: int
:type r_format: list, str, dict
:return: dissassembly resul... | disassemble | python | FuzzingLabs/octopus | octopus/engine/disassembler.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/engine/disassembler.py | MIT |
def gettxoutproof(self, txids, blockhash=None):
'''
TESTED
http://chainquery.com/bitcoin-api/gettxoutproof
Returns a hex-encoded proof that "txid" was included in a block.
NOTE: By default this function only works sometimes. This is when there is an
unspent output in ... |
TESTED
http://chainquery.com/bitcoin-api/gettxoutproof
Returns a hex-encoded proof that "txid" was included in a block.
NOTE: By default this function only works sometimes. This is when there is an
unspent output in the utxo for this transaction. To make it always work,
... | gettxoutproof | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def help(self, command=None):
'''
TESTED
http://chainquery.com/bitcoin-api/help
List all commands, or get help for a specified command.
Arguments:
1. "command" (string, optional) The command to get help on
Result:
"text" (string) The help text... |
TESTED
http://chainquery.com/bitcoin-api/help
List all commands, or get help for a specified command.
Arguments:
1. "command" (string, optional) The command to get help on
Result:
"text" (string) The help text
| help | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def lockunspent(self, unlock, transactions=None):
'''
TESTED
http://chainquery.com/bitcoin-api/lockunspent
Updates list of temporarily unspendable outputs.
Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.
If no transaction outputs ... |
TESTED
http://chainquery.com/bitcoin-api/lockunspent
Updates list of temporarily unspendable outputs.
Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.
If no transaction outputs are specified when unlocking then all current locked transact... | lockunspent | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def sendfrom(self, fromaccount, toaddress, amount, minconf=1, comment=None, comment_to=None):
'''
http://chainquery.com/bitcoin-api/sendfrom
NOT TESTED
DEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address.
Requires wallet passphrase to be set with... |
http://chainquery.com/bitcoin-api/sendfrom
NOT TESTED
DEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address.
Requires wallet passphrase to be set with walletpassphrase call.
Arguments:
1. "fromaccount" (string, required) The name of... | sendfrom | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def sendmany(self, fromaccount, amounts, minconf=1, comment=None, subtractfeefrom=None, replaceable=None, conf_target=None, estimate_mode="UNSET"):
'''
http://chainquery.com/bitcoin-api/sendmany
NOT TESTED
Send multiple times. Amounts are double-precision floating point numbers.
... |
http://chainquery.com/bitcoin-api/sendmany
NOT TESTED
Send multiple times. Amounts are double-precision floating point numbers.
Requires wallet passphrase to be set with walletpassphrase call.
Arguments:
1. "fromaccount" (string, required) DEPRECATED. The acco... | sendmany | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def sendtoaddress(self, address, amount, comment=None, comment_to=None, subtractfeefromamount=False, replaceable=None, estimate_mode="UNSET"):
'''
http://chainquery.com/bitcoin-api/sendtoaddress
NOT TESTED
Send an amount to a given address.
Requires wallet passphrase to be set... |
http://chainquery.com/bitcoin-api/sendtoaddress
NOT TESTED
Send an amount to a given address.
Requires wallet passphrase to be set with walletpassphrase call.
Arguments:
1. "address" (string, required) The bitcoin address to send to.
2. "amount" ... | sendtoaddress | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def signrawtransaction(self, hexstring, prevtxs=None, privkeys=None, sighashtype="ALL"):
'''
http://chainquery.com/bitcoin-api/signrawtransaction
NOT TESTED
Sign inputs for raw transaction (serialized, hex-encoded).
The second optional argument (may be null) is an array of prev... |
http://chainquery.com/bitcoin-api/signrawtransaction
NOT TESTED
Sign inputs for raw transaction (serialized, hex-encoded).
The second optional argument (may be null) is an array of previous transaction outputs that
this transaction depends on but may not yet be in the block ch... | signrawtransaction | python | FuzzingLabs/octopus | octopus/platforms/BTC/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py | MIT |
def get_block(self, block_num_or_id):
'''Get information related to a block.
TESTED
'''
data = {'block_num_or_id': block_num_or_id}
return self.call('get_block', data) | Get information related to a block.
TESTED
| get_block | python | FuzzingLabs/octopus | octopus/platforms/EOS/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py | MIT |
def get_account(self, account_name):
'''Get information related to an account.
TESTED
'''
data = {'account_name': account_name}
return self.call('get_account', data) | Get information related to an account.
TESTED
| get_account | python | FuzzingLabs/octopus | octopus/platforms/EOS/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py | MIT |
def get_table_rows(self, scope, code, table, json=False, lower_bound=None, upper_bound=None, limit=None):
'''Fetch smart contract data from an account.
NOT TESTED
'''
data = {'scope': scope,
'code': code,
'table': table,
'json': json}
... | Fetch smart contract data from an account.
NOT TESTED
| get_table_rows | python | FuzzingLabs/octopus | octopus/platforms/EOS/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py | MIT |
def abi_json_to_bin(self, code, action, args):
'''Serialize json to binary hex. The resulting binary hex is usually used for the data field in push_transaction.
NOT TESTED
'''
data = {'code': code,
'action': action,
'args': args}
print(data)
... | Serialize json to binary hex. The resulting binary hex is usually used for the data field in push_transaction.
NOT TESTED
| abi_json_to_bin | python | FuzzingLabs/octopus | octopus/platforms/EOS/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py | MIT |
def abi_bin_to_json(self, code, action, binargs):
'''Serialize back binary hex to json.
NOT TESTED
'''
data = {'code': code,
'action': action,
'binargs': binargs}
return self.call('abi_bin_to_json', data) | Serialize back binary hex to json.
NOT TESTED
| abi_bin_to_json | python | FuzzingLabs/octopus | octopus/platforms/EOS/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py | MIT |
def get_required_keys(self, transaction):
'''Get required keys to sign a transaction from list of your keys.
NOT TESTED
'''
data = {'transaction': transaction}
return self.call('get_required_keys', data) | Get required keys to sign a transaction from list of your keys.
NOT TESTED
| get_required_keys | python | FuzzingLabs/octopus | octopus/platforms/EOS/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py | MIT |
def decode_tx(self, transaction_id):
""" Return dict with important information about
the given transaction
"""
tx_data = self.eth_getTransactionByHash(transaction_id)
return tx_data
#TODO | Return dict with important information about
the given transaction
| decode_tx | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def create_contract(self, from_, code, gas, sig=None, args=None):
"""
Create a contract on the blockchain from compiled EVM code. Returns the
transaction hash.
"""
'''
from_ = from_ or self.eth_coinbase()
if sig is not None and args is not None:
types ... |
Create a contract on the blockchain from compiled EVM code. Returns the
transaction hash.
| create_contract | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def call_without_transaction(self, address, sig, args, result_types):
"""
Call a contract function on the RPC server, without sending a
transaction (useful for reading data)
"""
'''
data = self._encode_function(sig, args)
data_hex = data.encode('hex')
resp... |
Call a contract function on the RPC server, without sending a
transaction (useful for reading data)
| call_without_transaction | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def call_with_transaction(self, from_, address, sig, args, gas=None, gas_price=None, value=None):
"""
Call a contract function by sending a transaction (useful for storing
data)
"""
'''
gas = gas or DEFAULT_GAS_PER_TX
gas_price = gas_price or DEFAULT_GAS_PRICE
... |
Call a contract function by sending a transaction (useful for storing
data)
| call_with_transaction | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def web3_sha3(self, data):
""" Returns Keccak-256 (not the standardized SHA3-256) of the given data.
:param data: the data to convert into a SHA3 hash
:type data: hex string
:return: The SHA3 result of the given string.
:rtype: hex string
:Example:
>>> explorer... | Returns Keccak-256 (not the standardized SHA3-256) of the given data.
:param data: the data to convert into a SHA3 hash
:type data: hex string
:return: The SHA3 result of the given string.
:rtype: hex string
:Example:
>>> explorer = EthereumExplorerRPC()
>>> e... | web3_sha3 | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getBalance(self, address=None, block=BLOCK_TAG_LATEST):
""" Returns the balance of the account of given address.
:param address: 20 Bytes - address to check for balance.
:type address: str
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pen... | Returns the balance of the account of given address.
:param address: 20 Bytes - address to check for balance.
:type address: str
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: integer of the curr... | eth_getBalance | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getStorageAt(self, address=None, position=0, block=BLOCK_TAG_LATEST):
""" Returns the value from a storage position at a given address.
:param address: 20 Bytes - address to check for balance.
:type address: str
:param address: (optionnal) integer of the position in the storage.... | Returns the value from a storage position at a given address.
:param address: 20 Bytes - address to check for balance.
:type address: str
:param address: (optionnal) integer of the position in the storage. default is 0
:type address: int
:param block: (optionnal) integer block ... | eth_getStorageAt | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getTransactionCount(self, address, block=BLOCK_TAG_LATEST):
""" Returns the number of transactions sent from an address.
:param address: 20 Bytes - address.
:type address: str
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
... | Returns the number of transactions sent from an address.
:param address: 20 Bytes - address.
:type address: str
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: integer of the number of transactions... | eth_getTransactionCount | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getBlockTransactionCountByNumber(self, block=BLOCK_TAG_LATEST):
""" Returns the number of transactions in a block matching the given block number.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: in... | Returns the number of transactions in a block matching the given block number.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: integer of the number of transactions in this block.
:rtype: int
:Ex... | eth_getBlockTransactionCountByNumber | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getUncleCountByBlockNumber(self, block=BLOCK_TAG_LATEST):
""" Returns the number of uncles in a block from a block matching the given block number.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: in... | Returns the number of uncles in a block from a block matching the given block number.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: integer of the number of uncles in this block.
:rtype: int
:Ex... | eth_getUncleCountByBlockNumber | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getCode(self, address, default_block=BLOCK_TAG_LATEST):
""" Returns code at a given address.
:param address: 20 Bytes - address.
:type address: str
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
... | Returns code at a given address.
:param address: 20 Bytes - address.
:type address: str
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:return: the code from the given address.
:rtype: hex str
... | eth_getCode | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_sendTransaction(self, to_address=None, from_address=None, gas=None, gas_price=None, value=None, data=None,
nonce=None):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction
NEEDS TESTING
"""
params = {}
params['from']... | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction\n\n NEEDS TESTING\n " | eth_sendTransaction | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_call(self, to_address, from_address=None, gas=None, gas_price=None, value=None, data=None,
default_block=BLOCK_TAG_LATEST):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call
NEEDS TESTING
"""
default_block = validate_block(default_block)
... | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call\n\n NEEDS TESTING\n " | eth_call | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_estimateGas(self, to_address=None, from_address=None, gas=None, gas_price=None, value=None, data=None,
default_block=BLOCK_TAG_LATEST):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas
NEEDS TESTING
"""
if isinstance(default_bloc... | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas\n\n NEEDS TESTING\n " | eth_estimateGas | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getTransactionByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST, index=0):
""" Returns information about a transaction by block number and transaction index position.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str... | Returns information about a transaction by block number and transaction index position.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:param index: (optionnal) integer of the transaction index position.
:type ind... | eth_getTransactionByBlockNumberAndIndex | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_getUncleByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST, index=0):
""" Returns information about a uncle of a block by number and uncle index position.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:par... | Returns information about a uncle of a block by number and uncle index position.
:param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending"
:type block: int or str
:param index: (optionnal) the uncle's index position.
:type index: int
:retur... | eth_getUncleByBlockNumberAndIndex | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def eth_newFilter(self, from_block=BLOCK_TAG_LATEST, to_block=BLOCK_TAG_LATEST, address=None, topics=None):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter
NEEDS TESTING
"""
_filter = {
'fromBlock': from_block,
'toBlock': to_block,
... | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter\n\n NEEDS TESTING\n " | eth_newFilter | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def db_putString(self, db_name, key, value):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring
TESTED
"""
warnings.warn('deprecated', DeprecationWarning)
return self.call('db_putString', [db_name, key, value]) | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring\n\n TESTED\n " | db_putString | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def db_getString(self, db_name, key):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_getstring
TESTED
"""
warnings.warn('deprecated', DeprecationWarning)
return self.call('db_getString', [db_name, key]) | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_getstring\n\n TESTED\n " | db_getString | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def db_putHex(self, db_name, key, value):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex
TESTED
"""
if not value.startswith('0x'):
value = '0x{}'.format(value)
warnings.warn('deprecated', DeprecationWarning)
return self.call('db_putHex',... | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex\n\n TESTED\n " | db_putHex | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def db_getHex(self, db_name, key):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex
TESTED
"""
warnings.warn('deprecated', DeprecationWarning)
return self.call('db_getHex', [db_name, key]) | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex\n\n TESTED\n " | db_getHex | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def shh_post(self, topics, payload, priority, ttl, from_=None, to=None):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_post
NEEDS TESTING
"""
whisper_object = {
'from': from_,
'to': to,
'topics': topics,
'payload': payload... | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_post\n\n NEEDS TESTING\n " | shh_post | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def shh_newFilter(self, to, topics):
"""
https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_newfilter
NEEDS TESTING
"""
_filter = {
'to': to,
'topics': topics,
}
return self.call('shh_newFilter', [_filter]) | ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_newfilter\n\n NEEDS TESTING\n " | shh_newFilter | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def trace_filter(self, from_block=None, to_block=None, from_addresses=None, to_addresses=None):
"""
https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_filter
TESTED
"""
params = {}
if from_block is not None:
from_block = validate_block(from_blo... | ERROR: type should be string, got "\n https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_filter\n\n TESTED\n " | trace_filter | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def trace_get(self, tx_hash, positions):
"""
https://wiki.parity.io/JSONRPC
https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_get
NEEDS TESTING
"""
if not isinstance(positions, list):
positions = [positions]
return self.call('trace_get... | ERROR: type should be string, got "\n https://wiki.parity.io/JSONRPC\n https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_get\n\n NEEDS TESTING\n " | trace_get | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def trace_block(self, block=BLOCK_TAG_LATEST):
"""
https://wiki.parity.io/JSONRPC
https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_block
NEEDS TESTING
"""
block = validate_block(block)
return self.call('trace_block', [block]) | ERROR: type should be string, got "\n https://wiki.parity.io/JSONRPC\n https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_block\n\n NEEDS TESTING\n " | trace_block | python | FuzzingLabs/octopus | octopus/platforms/ETH/explorer.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py | MIT |
def clean_hex(d):
'''
Convert decimal to hex and remove the "L" suffix that is appended to large
numbers
'''
try:
return hex(d).rstrip('L')
except:
return None |
Convert decimal to hex and remove the "L" suffix that is appended to large
numbers
| clean_hex | python | FuzzingLabs/octopus | octopus/platforms/ETH/util.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/util.py | MIT |
def validate_block(block):
'''
Test if the block tag is valid
'''
if isinstance(block, str):
if block not in BLOCK_TAGS:
raise ValueError('invalid block tag')
if isinstance(block, int):
block = hex(block)
return block |
Test if the block tag is valid
| validate_block | python | FuzzingLabs/octopus | octopus/platforms/ETH/util.py | https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/util.py | MIT |
def get_stats(ids, counts=None):
"""
Given a list of integers, return a dictionary of counts of consecutive pairs
Example: [1, 2, 3, 1, 2] -> {(1, 2): 2, (2, 3): 1, (3, 1): 1}
Optionally allows to update an existing dictionary of counts
"""
counts = {} if counts is None else counts
for pair ... |
Given a list of integers, return a dictionary of counts of consecutive pairs
Example: [1, 2, 3, 1, 2] -> {(1, 2): 2, (2, 3): 1, (3, 1): 1}
Optionally allows to update an existing dictionary of counts
| get_stats | python | karpathy/minbpe | minbpe/base.py | https://github.com/karpathy/minbpe/blob/master/minbpe/base.py | MIT |
def merge(ids, pair, idx):
"""
In the list of integers (ids), replace all consecutive occurrences
of pair with the new integer token idx
Example: ids=[1, 2, 3, 1, 2], pair=(1, 2), idx=4 -> [4, 3, 4]
"""
newids = []
i = 0
while i < len(ids):
# if not at the very last position AND ... |
In the list of integers (ids), replace all consecutive occurrences
of pair with the new integer token idx
Example: ids=[1, 2, 3, 1, 2], pair=(1, 2), idx=4 -> [4, 3, 4]
| merge | python | karpathy/minbpe | minbpe/base.py | https://github.com/karpathy/minbpe/blob/master/minbpe/base.py | MIT |
def load(self, model_file):
"""Inverse of save() but only for the model file"""
assert model_file.endswith(".model")
# read the model file
merges = {}
special_tokens = {}
idx = 256
with open(model_file, 'r', encoding="utf-8") as f:
# read the version
... | Inverse of save() but only for the model file | load | python | karpathy/minbpe | minbpe/base.py | https://github.com/karpathy/minbpe/blob/master/minbpe/base.py | MIT |
def __init__(self, pattern=None):
"""
- pattern: optional string to override the default (GPT-4 split pattern)
- special_tokens: str -> int dictionary of special tokens
example: {'<|endoftext|>': 100257}
"""
super().__init__()
self.pattern = GPT4_SPLIT_PATTERN i... |
- pattern: optional string to override the default (GPT-4 split pattern)
- special_tokens: str -> int dictionary of special tokens
example: {'<|endoftext|>': 100257}
| __init__ | python | karpathy/minbpe | minbpe/regex.py | https://github.com/karpathy/minbpe/blob/master/minbpe/regex.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.