id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
15,275
import numpy as np import torch from medpy import metric from scipy.ndimage import zoom import torch.nn as nn import SimpleITK as sitk def calculate_metric_percase(pred, gt): def test_single_volume(image, label, net, classes, patch_size=[256, 256], test_save_path=None, case=None, z_spacing=1): image, label = image...
null
15,276
import argparse import logging import os import random import sys import time import numpy as np import torch import torch.nn as nn import torch.optim as optim from tensorboardX import SummaryWriter from torch.nn.modules.loss import CrossEntropyLoss from torch.utils.data import DataLoader from tqdm import tqdm from uti...
null
15,277
import os import yaml from yacs.config import CfgNode as CN _C = CN() _C.BASE = [''] _C.DATA = CN() _C.DATA.BATCH_SIZE = 128 _C.DATA.DATA_PATH = '' _C.DATA.DATASET = 'imagenet' _C.DATA.IMG_SIZE = 224 _C.DATA.INTERPOLATION = 'bicubic' _C.DATA.ZIP_MODE = False _C.DATA.CACHE_MODE = 'part' _C.DATA.PIN_MEMORY = True _C.DATA...
Get a yacs CfgNode object with default values.
15,278
import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, to_2tuple, trunc_normal_ The provided code snippet includes necessary dependencies for implementing the `window_partition` function. Write a Python function `def window_p...
Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C)
15,279
import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, to_2tuple, trunc_normal_ The provided code snippet includes necessary dependencies for implementing the `window_reverse` function. Write a Python function `def window_rev...
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
15,280
import os import random import h5py import numpy as np import torch from scipy import ndimage from scipy.ndimage.interpolation import zoom from torch.utils.data import Dataset def random_rot_flip(image, label): k = np.random.randint(0, 4) image = np.rot90(image, k) label = np.rot90(label, k) axis = np....
null
15,281
import os import random import h5py import numpy as np import torch from scipy import ndimage from scipy.ndimage.interpolation import zoom from torch.utils.data import Dataset def random_rotate(image, label): angle = np.random.randint(-20, 20) image = ndimage.rotate(image, angle, order=0, reshape=False) la...
null
15,282
from pathlib import Path from typing import List import mkdocs_gen_files import yaml SELECTIONS = {} animals = list(Path("docs/assets").glob("square_*.png")) def indent(s, num_spaces): """ Indent every line of s by num_spaces spaces """ return ("\n" + " " * num_spaces).join(s.splitlines()) nav = mkdocs_...
null
15,283
from dataclasses import dataclass import sys from typing import Iterable, List class Range: """ Range of addresses. :ivar start: The start address of the Range :ivar end: The end address of the Range """ start: int end: int MAX = sys.maxsize def __post_init__(self): if self.s...
Break a list of Ranges into equal sized regions of Ranges, assuming each range is evenly divisible by chunk_size. :param ranges: :param chunk_size: :return: equal sized regions of Ranges
15,284
from dataclasses import dataclass import sys from typing import Iterable, List class Range: """ Range of addresses. :ivar start: The start address of the Range :ivar end: The end address of the Range """ start: int end: int MAX = sys.maxsize def __post_init__(self): if self.s...
Subtract one set of addresses from another, both expressed as a list of non-overlapping ranges. :param ranges: A list of non-overlapping ranges. :param to_remove: A list of non-overlapping ranges to be removed from the first argument. :return: A list of ranges covering the input ranges with the subranges removed.
15,285
import setuptools import pkg_resources from setuptools.command.egg_info import egg_info with open("LICENSE") as f: license = "".join(["\n", f.read()]) def read_requirements(requirements_path): with open(requirements_path) as requirements_handle: return [ str(requirement) for req...
null
15,286
import os HELLO_WORLD_SOURCE = r""" #include <stdio.h> int main() { printf("Hello, World!\n"); return 0; } """ def create_binary(c_program: str, executable_filename: str) -> None: """Compile `c_program` into a binary at `executable_filename`.""" c_source_filename = f"{executable_filename}.c" with open...
Create a simple binary printing "Hello, World!\n" to stdout.
15,287
import os The provided code snippet includes necessary dependencies for implementing the `get_descendants_tags` function. Write a Python function `async def get_descendants_tags(resource)` to solve the following problem: Return an alphabetically sorted list of all the tags of the descendants of `resource`. Here is th...
Return an alphabetically sorted list of all the tags of the descendants of `resource`.
15,288
import argparse import os from ofrak import OFRAK, OFRAKContext from ofrak.core import ( Elf, ElfProgramHeader, ElfProgramHeaderType, ElfProgramHeaderModifier, ElfProgramHeaderModifierConfig, ) from ofrak_type.memory_permissions import MemoryPermissions The provided code snippet includes necessary ...
Return the first executable LOAD program header in `elf_view`.
15,289
import argparse import os from ofrak_patch_maker.toolchain.llvm_12 import LLVM_12_0_1_Toolchain import ofrak_ghidra from ofrak import OFRAK, OFRAKContext, Resource, ResourceFilter, ResourceAttributeValueFilter from ofrak.core import ( Allocatable, CodeRegion, ComplexBlock, Instruction, LiefAddSegmen...
Add a segment to `elf_resource`, of size `size` at virtual address `vaddr`, returning this new segment resource after unpacking.
15,290
import argparse import os from ofrak_patch_maker.toolchain.llvm_12 import LLVM_12_0_1_Toolchain import ofrak_ghidra from ofrak import OFRAK, OFRAKContext, Resource, ResourceFilter, ResourceAttributeValueFilter from ofrak.core import ( Allocatable, CodeRegion, ComplexBlock, Instruction, LiefAddSegmen...
Replace the original `call` instruction in main with a call to the start of `new_segment`.
15,291
import argparse import os from ofrak_patch_maker.toolchain.llvm_12 import LLVM_12_0_1_Toolchain import ofrak_ghidra from ofrak import OFRAK, OFRAKContext, Resource, ResourceFilter, ResourceAttributeValueFilter from ofrak.core import ( Allocatable, CodeRegion, ComplexBlock, Instruction, LiefAddSegmen...
null
15,292
import logging from typing import Iterable, Tuple, List from typing import Optional from warnings import warn from angr.knowledge_plugins.functions.function import Function as AngrFunction from archinfo.arch_arm import get_real_address_if_arm, is_arm_arch from ofrak.component.unpacker import UnpackerError from ofrak_ty...
Get exit address info needed for BasicBlock creation: BasicBlock.is_exit_point, BasicBlock.exit_addr.
15,293
import setuptools import pkg_resources from setuptools.command.egg_info import egg_info with open("README.md") as f: long_description = f.read() def read_requirements(requirements_path): with open(requirements_path) as requirements_handle: return [ str(requirement) for requireme...
null
15,295
import os from dataclasses import dataclass from io import StringIO import yaml GHIDRA_CONFIG_PATH = os.path.join(os.path.dirname(__file__), "ofrak_ghidra.conf.yml") class OfrakGhidraConfig: ghidra_path: str ghidra_version: str ghidra_log_file: str ghidra_server_user: str ghidra_server_pass: str ...
null
15,296
import argparse from ofrak_ghidra.config.ofrak_ghidra_config import ( save_ghidra_config, OfrakGhidraConfig, load_ghidra_config, restore_default_ghidra_config, ) def _dump_config(args): print(load_ghidra_config().to_yaml())
null
15,297
import argparse from ofrak_ghidra.config.ofrak_ghidra_config import ( save_ghidra_config, OfrakGhidraConfig, load_ghidra_config, restore_default_ghidra_config, ) def _import_config(args): with open(args.config_path) as f: raw_new_config = f.read() new_config = OfrakGhidraConfig.from...
null
15,298
import argparse from ofrak_ghidra.config.ofrak_ghidra_config import ( save_ghidra_config, OfrakGhidraConfig, load_ghidra_config, restore_default_ghidra_config, ) def _restore_config(args): restore_default_ghidra_config()
null
15,299
import asyncio import os import re from collections import defaultdict from typing import Tuple, Dict, Union, List, Iterable from ofrak.core.architecture import ProgramAttributes from ofrak_type.architecture import InstructionSet, InstructionSetMode from ofrak.core.basic_block import BasicBlockUnpacker, BasicBlock from...
Fix up an assembly instruction from Ghidra, so that the toolchain can assemble it. :param base_mnemonic: original mnemonic from Ghidra :param base_operands: original operands from Ghidra :param program_attrs: ProgramAttributes for the binary analyzed in Ghidra :return: fixed up assembly instruction
15,300
import argparse import os import stat import subprocess import sys from ofrak_ghidra.constants import ( GHIDRA_START_SERVER_SCRIPT, GHIDRA_PATH, CORE_OFRAK_GHIDRA_SCRIPTS, GHIDRA_USER, GHIDRA_PASS, GHIDRA_REPOSITORY_HOST, GHIDRA_REPOSITORY_PORT, ) def _run_ghidra_server(*args): if sys.p...
null
15,301
import argparse import os import stat import subprocess import sys from ofrak_ghidra.constants import ( GHIDRA_START_SERVER_SCRIPT, GHIDRA_PATH, CORE_OFRAK_GHIDRA_SCRIPTS, GHIDRA_USER, GHIDRA_PASS, GHIDRA_REPOSITORY_HOST, GHIDRA_REPOSITORY_PORT, ) def _stop_ghidra_server(*args): if sys....
null
15,303
import logging import re from dataclasses import dataclass from typing import Dict, Tuple, Optional, Iterable from capstone import ( Cs, CS_ARCH_ARM64, CS_ARCH_ARM, CS_ARCH_X86, CS_ARCH_PPC, CS_ARCH_MIPS, CS_MODE_BIG_ENDIAN, CS_MODE_LITTLE_ENDIAN, CS_MODE_THUMB, CS_MODE_ARM, ...
null
15,304
import logging import re from dataclasses import dataclass from typing import Dict, Tuple, Optional, Iterable from capstone import ( Cs, CS_ARCH_ARM64, CS_ARCH_ARM, CS_ARCH_X86, CS_ARCH_PPC, CS_ARCH_MIPS, CS_MODE_BIG_ENDIAN, CS_MODE_LITTLE_ENDIAN, CS_MODE_THUMB, CS_MODE_ARM, ...
null
15,305
import argparse from binaryninja.update import ( UpdateChannel, are_auto_updates_enabled, set_auto_updates_enabled, is_update_installation_pending, install_pending_update, ) from binaryninja import core_version def get_version(version_string: str): channel = list(UpdateChannel)[0] for versi...
null
15,306
from dataclasses import dataclass from enum import Enum from typing import List, Optional import argparse import os import subprocess import sys import pkg_resources import yaml class InstallTarget(Enum): INSTALL = "install" DEVELOP = "develop" class OfrakImageConfig: registry: str base_image_name: str ...
null
15,307
from dataclasses import dataclass from enum import Enum from typing import List, Optional import argparse import os import subprocess import sys import pkg_resources import yaml def check_package_contents(package_path: str): required_contents = [ package_path, os.path.join(package_path, "Dockerstub...
null
15,308
from dataclasses import dataclass from enum import Enum from typing import List, Optional import argparse import os import subprocess import sys import pkg_resources import yaml class InstallTarget(Enum): class OfrakImageConfig: def validate_serial_txt_existence(self): def create_dockerfile_base(config: OfrakImag...
null
15,309
from dataclasses import dataclass from enum import Enum from typing import List, Optional import argparse import os import subprocess import sys import pkg_resources import yaml GIT_COMMIT_HASH = ( subprocess.check_output(["git", "rev-parse", "--short=8", "HEAD"]).decode("ascii").strip() ) class OfrakImageConfig: ...
null
15,311
import asyncio import dataclasses import hashlib import logging from inspect import isawaitable from typing import ( BinaryIO, Iterable, List, Optional, Tuple, Type, TypeVar, cast, Union, Awaitable, Sequence, Callable, Set, Pattern, overload, ) from ofrak.comp...
null
15,312
import asyncio import dataclasses import hashlib import logging from inspect import isawaitable from typing import ( BinaryIO, Iterable, List, Optional, Tuple, Type, TypeVar, cast, Union, Awaitable, Sequence, Callable, Set, Pattern, overload, ) from ofrak.comp...
null
15,313
import logging from dataclasses import dataclass from enum import Enum from hashlib import md5 from typing import Any, Callable, Dict, Generator, Iterable, Optional from ofrak.component.packer import Packer, PackerError from ofrak.component.unpacker import Unpacker, UnpackerError from ofrak.core.binary import GenericBi...
null
15,314
import logging from dataclasses import dataclass from enum import Enum from hashlib import md5 from typing import Any, Callable, Dict, Generator, Iterable, Optional from ofrak.component.packer import Packer, PackerError from ofrak.component.unpacker import Unpacker, UnpackerError from ofrak.core.binary import GenericBi...
null
15,315
import logging from dataclasses import dataclass from enum import Enum from hashlib import md5 from typing import Any, Callable, Dict, Generator, Iterable, Optional from ofrak.component.packer import Packer, PackerError from ofrak.component.unpacker import Unpacker, UnpackerError from ofrak.core.binary import GenericBi...
null
15,316
import asyncio import ctypes import logging import math from concurrent.futures import ProcessPoolExecutor from concurrent.futures.process import BrokenProcessPool from dataclasses import dataclass from ofrak.component.analyzer import Analyzer from ofrak.model.resource_model import ResourceAttributes from ofrak.resourc...
Return a list of entropy values where each value represents the Shannon entropy of the byte value distribution over a fixed-size, sliding window. If the entropy data is larger than a maximum size, summarize it by periodically sampling it. Shannon entropy represents how uniform a probability distribution is. Since more ...
15,317
import asyncio import ctypes import logging import math from concurrent.futures import ProcessPoolExecutor from concurrent.futures.process import BrokenProcessPool from dataclasses import dataclass from ofrak.component.analyzer import Analyzer from ofrak.model.resource_model import ResourceAttributes from ofrak.resourc...
null
15,318
import logging import math from typing import Callable, List, Optional def _shannon_entropy(distribution: List[int], window_size: int) -> float: """ Return the Shannon entropy of the input probability distribution (represented as a histogram counting byte occurrences over a window of known size). Shanno...
Return a list of entropy values where each value represents the Shannon entropy of the byte value distribution over a fixed-size, sliding window.
15,319
import io import struct import zlib from dataclasses import dataclass from enum import Enum from typing import Optional, List from ofrak.component.identifier import Identifier from ofrak.component.analyzer import Analyzer from ofrak.component.modifier import Modifier from ofrak.component.packer import Packer from ofrak...
Calculate CRC32 a-la OpenWrt. Original implementation: <https://git.archive.openwrt.org/?p=14.07/openwrt.git;a=blob;f=tools/firmware-utils/src/trx.c> Implements CRC-32 Ethernet which requires XOR'ing the zlib.crc32 result with 0xFFFFFFFF
15,320
import inspect import logging def _warn_user_no_xattr(function_name: str) -> None: LOGGER.warning( f"Function {function_name} not found. Library xattr is not available on Windows platforms. \ Extended attributes will not be properly handled while using OFRAK on this platform. \ If you requir...
null
15,321
import inspect import logging def _warn_user_no_xattr(function_name: str) -> None: LOGGER.warning( f"Function {function_name} not found. Library xattr is not available on Windows platforms. \ Extended attributes will not be properly handled while using OFRAK on this platform. \ If you requir...
null
15,322
import inspect import logging def _warn_user_no_xattr(function_name: str) -> None: def setxattr(f, attr, value, options=0, symlink=False): frame = inspect.currentframe() _warn_user_no_xattr(inspect.getframeinfo(frame).function) return None
null
15,323
import inspect import logging def _warn_user_no_xattr(function_name: str) -> None: def removexattr(f, attr, symlink=False): frame = inspect.currentframe() _warn_user_no_xattr(inspect.getframeinfo(frame).function) return None
null
15,324
from collections import defaultdict from dataclasses import dataclass from itertools import chain from typing import List, Tuple, Dict, Optional, Iterable, Mapping from immutabledict import immutabledict from ofrak.core.binary import BinaryPatchModifier, BinaryPatchConfig from ofrak.component.analyzer import Analyzer f...
null
15,325
from collections import defaultdict from dataclasses import dataclass from itertools import chain from typing import List, Tuple, Dict, Optional, Iterable, Mapping from immutabledict import immutabledict from ofrak.core.binary import BinaryPatchModifier, BinaryPatchConfig from ofrak.component.analyzer import Analyzer f...
null
15,326
import os import struct from dataclasses import dataclass from enum import Enum from typing import Union, List, Tuple import fdt from ofrak.component.analyzer import Analyzer from ofrak.component.identifier import Identifier from ofrak.component.packer import Packer from ofrak.component.unpacker import Unpacker from of...
Generates an fdt.items.property corresponding to a DtbProperty. :param p: :return:
15,327
import os import struct from dataclasses import dataclass from enum import Enum from typing import Union, List, Tuple import fdt from ofrak.component.analyzer import Analyzer from ofrak.component.identifier import Identifier from ofrak.component.packer import Packer from ofrak.component.unpacker import Unpacker from of...
Converts an fdt.items.property to its p_type and p_data values. :param p: :return:
15,328
import asyncio import tempfile from concurrent.futures.process import ProcessPoolExecutor from dataclasses import dataclass from typing import Dict from ofrak.resource import ResourceFactory, Resource from ofrak.model.resource_model import ResourceAttributes from ofrak.component.abstract import ComponentMissingDependen...
null
15,329
import logging import re import sys from dataclasses import dataclass from typing import List, Union, Tuple, Any from ofrak.component.abstract import ComponentMissingDependencyError from ofrak.component.analyzer import Analyzer from ofrak.component.identifier import Identifier from ofrak.component.packer import Packer ...
null
15,330
import io import logging from typing import Optional, TypeVar from ofrak.component.analyzer import Analyzer from ofrak.core import NamedProgramSection from ofrak.core.architecture import ProgramAttributes from ofrak.core.elf.model import ( ElfSectionHeader, Elf, ElfHeader, ElfBasicHeader, ElfProgram...
null
15,331
import asyncio from typing import Optional, Dict, Type, Tuple from ofrak.model.tag_model import ResourceTag from ofrak.component.unpacker import Unpacker from ofrak.core.code_region import CodeRegion from ofrak.model.resource_model import ResourceAttributes from ofrak.model.viewable_tag_model import AttributesType from...
null
15,332
import logging from itertools import tee from typing import List from ofrak import Modifier, Resource, OFRAKContext from ofrak.core import ( Elf, FreeSpace, ElfProgramHeaderModifier, ElfProgramHeaderModifierConfig, Allocatable, ElfProgramHeader, ElfProgramHeaderType, ElfUnpacker, ) from ...
null
15,333
import logging from itertools import tee from typing import List from ofrak import Modifier, Resource, OFRAKContext from ofrak.core import ( Elf, FreeSpace, ElfProgramHeaderModifier, ElfProgramHeaderModifierConfig, Allocatable, ElfProgramHeader, ElfProgramHeaderType, ElfUnpacker, ) from ...
Split range_1 around range_2 and return the split range whose start is the same as range_1.
15,334
import logging from itertools import tee from typing import List from ofrak import Modifier, Resource, OFRAKContext from ofrak.core import ( Elf, FreeSpace, ElfProgramHeaderModifier, ElfProgramHeaderModifierConfig, Allocatable, ElfProgramHeader, ElfProgramHeaderType, ElfUnpacker, ) from ...
A helper function waiting for itertools.pairwise from Python 3.10: https://docs.python.org/3/library/itertools.html#itertools.pairwise. Usage: `_pairwise('ABCDEFG') --> AB BC CD DE EF FG`
15,335
from dataclasses import dataclass from typing import List, Tuple from ofrak_type import LinkableSymbolType, MemoryPermissions, InstructionSetMode from ofrak.core.label import LabeledAddress from ofrak_patch_maker.toolchain.model import Segment from ofrak_type.memory_permissions import MemoryPermissions class LinkableSy...
null
15,336
from dataclasses import dataclass from typing import List, Tuple from ofrak_type import LinkableSymbolType, MemoryPermissions, InstructionSetMode from ofrak.core.label import LabeledAddress from ofrak_patch_maker.toolchain.model import Segment from ofrak_type.memory_permissions import MemoryPermissions class LinkableSy...
null
15,337
from dataclasses import dataclass from typing import List, Tuple from ofrak_type import LinkableSymbolType, MemoryPermissions, InstructionSetMode from ofrak.core.label import LabeledAddress from ofrak_patch_maker.toolchain.model import Segment from ofrak_type.memory_permissions import MemoryPermissions class LinkableSy...
null
15,338
import os.path from typing import Optional from ofrak import OFRAKContext, Resource import argparse from pathlib import Path import time import sys from ofrak.cli.ofrak_cli import OfrakCommandRunsScript from ofrak.core import FilesystemEntry from ofrak.gui.server import open_gui class UnpackCommand(OfrakCommandRunsScri...
null
15,339
from argparse import Namespace from typing import Iterable, Set from ofrak.cli.ofrak_cli import OfrakCommand, OFRAKEnvironment def _print_lines_without_duplicates(output_lines: Iterable[str]): # strip duplicates, resetting the memory of duplicates when indentation changes prev_indent = 0 seen: Set[str] = s...
null
15,340
from collections import defaultdict from typing import Any, List, Set, Tuple, cast, Callable from typing import Dict, Optional from sortedcontainers import SortedList from typing_inspect import get_origin from ofrak import ResourceTag from ofrak.model.resource_model import ResourceIndexedAttribute from ofrak.service.re...
null
15,341
import dataclasses from dataclasses import is_dataclass, fields from typing import Any, Dict, Type, cast, Tuple import inspect from ofrak.service.serialization.pjson_types import PJSONType from ofrak.service.serialization.serializers.enum_serializer import is_enum from ofrak.service.serialization.serializers.serializer...
null
15,342
from typing import Any, Type, Dict from typing_inspect import get_origin from ofrak.model.resource_model import ResourceIndexedAttribute, ResourceAttributes from ofrak.service.serialization.pjson_types import PJSONType from ofrak.service.serialization.serializers.serializer_i import SerializerInterface class ResourceI...
null
15,343
from collections import defaultdict from typing import Any, Dict, cast from itertools import product from ofrak.service.serialization.pjson import PJSONSerializationService from ofrak.service.serialization.pjson_types import PJSONType from ofrak.service.serialization.service_i import SerializationServiceInterface The ...
Generator of short JSON-compatible strings of increasing size.
15,344
import asyncio import logging from collections import defaultdict from dataclasses import dataclass from functools import lru_cache from typing import ( Awaitable, Dict, Iterable, List, Optional, Set, Tuple, TypeVar, Union, cast, Any, ) from ofrak.component.unpacker import Un...
null
15,345
import asyncio import logging from collections import defaultdict from dataclasses import dataclass from functools import lru_cache from typing import ( Awaitable, Dict, Iterable, List, Optional, Set, Tuple, TypeVar, Union, cast, Any, ) from ofrak.component.unpacker import Un...
When auto-running components, most of the time only the *most specific* components should be run for a resource. For example, an APK resource is also a ZIP resource; we want to always run the APK Unpacker on resources that are tagged as both ZIP and APK, because APK is a more specific tag. However, Identifiers are a sp...
15,346
import asyncio import logging from collections import defaultdict from dataclasses import dataclass from functools import lru_cache from typing import ( Awaitable, Dict, Iterable, List, Optional, Set, Tuple, TypeVar, Union, cast, Any, ) from ofrak.component.unpacker import Un...
null
15,347
import asyncio import binascii import dataclasses import re from enum import Enum import functools import itertools import logging from ofrak.project.project import OfrakProject import typing_inspect from typing_inspect import get_args import json import orjson import inspect import os import sys import webbrowser from...
Decorator for a server function that attempts to do some work, and forwards the exception, if any, to the client over HTTP. Usage: @exceptions_to_http(MyErrorClass) async def handle_some_request(self, request...): ...
15,348
import asyncio import binascii import dataclasses import re from enum import Enum import functools import itertools import logging from ofrak.project.project import OfrakProject import typing_inspect from typing_inspect import get_args import json import orjson import inspect import os import sys import webbrowser from...
null
15,349
import asyncio import binascii import dataclasses import re from enum import Enum import functools import itertools import logging from ofrak.project.project import OfrakProject import typing_inspect from typing_inspect import get_args import json import orjson import inspect import os import sys import webbrowser from...
URL-encoded GET parameters are all strings. For example, None is encoded as 'None', or 1 as '1', which isn't valid PJSON. We fix this by applying `json.loads` on each parameter.
15,350
import asyncio import binascii import dataclasses import re from enum import Enum import functools import itertools import logging from ofrak.project.project import OfrakProject import typing_inspect from typing_inspect import get_args import json import orjson import inspect import os import sys import webbrowser from...
null
15,351
import asyncio import binascii import dataclasses import re from enum import Enum import functools import itertools import logging from ofrak.project.project import OfrakProject import typing_inspect from typing_inspect import get_args import json import orjson import inspect import os import sys import webbrowser from...
null
15,352
import asyncio import binascii import dataclasses import re from enum import Enum import functools import itertools import logging from ofrak.project.project import OfrakProject import typing_inspect from typing_inspect import get_args import json import orjson import inspect import os import sys import webbrowser from...
null
15,353
import dataclasses import functools import logging from dataclasses import dataclass from typing import Optional, Type, TypeVar, Dict, Iterable, Any, cast, Set from ofrak.resource import Resource from ofrak.model.resource_model import ResourceAttributes, ResourceModel from ofrak.model.tag_model import ResourceTag from ...
null
15,354
import dataclasses from abc import ABC, abstractmethod from collections import defaultdict from typing import ( TypeVar, Set, Type, Dict, Optional, Iterable, MutableMapping, Union, Tuple, List, Callable, Generic, Any, cast, overload, ) from weakref import Weak...
When called as: @index(uses_indexes=(...)) def MyIndex(self): ...
15,355
import dataclasses from abc import ABC, abstractmethod from collections import defaultdict from typing import ( TypeVar, Set, Type, Dict, Optional, Iterable, MutableMapping, Union, Tuple, List, Callable, Generic, Any, cast, overload, ) from weakref import Weak...
When called as: @index def MyIndex(self): ...
15,356
import dataclasses from abc import ABC, abstractmethod from collections import defaultdict from typing import ( TypeVar, Set, Type, Dict, Optional, Iterable, MutableMapping, Union, Tuple, List, Callable, Generic, Any, cast, overload, ) from weakref import Weak...
Create a new indexable attribute for a [ResourceAttributes][ofrak.model.resource_model.ResourceAttributes]. :param index_value_getter: Method of [ResourceAttributes][ofrak.model.resource_model.ResourceAttributes] which returns the value of the index for that instance. :param uses_indexes: Additional index types that ar...
15,357
import dataclasses from abc import ABC, abstractmethod from collections import defaultdict from typing import ( TypeVar, Set, Type, Dict, Optional, Iterable, MutableMapping, Union, Tuple, List, Callable, Generic, Any, cast, overload, ) from weakref import Weak...
Verify the getter function returns a valid indexable type - a primitive type which can be compared. :param getter_func: :raises TypeError: if the getter function does not have a return type annotation :raises TypeError: if the getter does not return an indexable type :return:
15,358
import dataclasses from _warnings import warn from collections import defaultdict from dataclasses import dataclass from typing import Tuple, Type, Dict, Any, List, Set, TypeVar, Iterable, MutableMapping, Generic import ofrak.model._auto_attributes from ofrak.model.resource_model import ( ResourceAttributes, Re...
null
15,359
import dataclasses from _warnings import warn from collections import defaultdict from dataclasses import dataclass from typing import Tuple, Type, Dict, Any, List, Set, TypeVar, Iterable, MutableMapping, Generic import ofrak.model._auto_attributes from ofrak.model.resource_model import ( ResourceAttributes, Re...
null
15,360
import dataclasses from _warnings import warn from collections import defaultdict from dataclasses import dataclass from typing import Tuple, Type, Dict, Any, List, Set, TypeVar, Iterable, MutableMapping, Generic import ofrak.model._auto_attributes from ofrak.model.resource_model import ( ResourceAttributes, Re...
Check for any methods in a new class which override a parent's method. The behavior of `view_as` means that overriding methods might not work as users think it does. Calling something like `a = resource.view_as(A)` will always and only return instances of `A`. These resources may have tags `B` and/or `C` which inherit ...
15,361
import dataclasses from _warnings import warn from collections import defaultdict from dataclasses import dataclass from typing import Tuple, Type, Dict, Any, List, Set, TypeVar, Iterable, MutableMapping, Generic import ofrak.model._auto_attributes from ofrak.model.resource_model import ( ResourceAttributes, Re...
Extract the index descriptors from a namespaces.
15,362
import itertools from typing import FrozenSet, Set, Tuple, Type from dataclasses import dataclass from ofrak.model.resource_model import ResourceAttributes from ofrak.model.tag_model import ResourceTag from ofrak.component.interface import ComponentInterface from ofrak.component.analyzer import Analyzer from ofrak.serv...
null
15,364
import configparser import os from multiprocessing import Pool, cpu_count from typing import Optional, Dict, Mapping, Tuple import math from ofrak_patch_maker.toolchain.model import BinFileType, Segment from ofrak_type.error import NotFoundError from ofrak_type.memory_permissions import MemoryPermissions def get_file_...
null
15,365
import configparser import os from multiprocessing import Pool, cpu_count from typing import Optional, Dict, Mapping, Tuple import math from ofrak_patch_maker.toolchain.model import BinFileType, Segment from ofrak_type.error import NotFoundError from ofrak_type.memory_permissions import MemoryPermissions The provided ...
Get config values from toolchain.conf. :param section: section name in config file :param key: key in `config[section]` :raises SystemExit: If `config[section]` or `config[section][key]` not found. :return Union[str, List[Tuple[str, str]]]: the result of ``config.get(section, key)`` or ``config.items(section)``
15,366
import configparser import os from multiprocessing import Pool, cpu_count from typing import Optional, Dict, Mapping, Tuple import math from ofrak_patch_maker.toolchain.model import BinFileType, Segment from ofrak_type.error import NotFoundError from ofrak_type.memory_permissions import MemoryPermissions def _gen_file(...
Utility function to generate assembly stubs. This is necessary when function calls need to switch between ARM and thumb mode (when code generated by the PatchMaker is ARM and needs to jump to thumb code, or the opposite). With those stubs, the linker has explicit information about the destination mode, so it jumps corr...
15,367
import argparse from parsy import forward_declaration, generate, regex, seq, string def create_parser(): bb_parser = forward_declaration() @generate def tag(): start_tag = ( string("[") >> ( seq(regex(r"\w+") << string("="), regex(r"[^]]+")).map(tuple) ...
null
15,368
import argparse from parsy import forward_declaration, generate, regex, seq, string def pad_line(l, pad_char=" "): length = sum(map(len, l.split("%c"))) return l + (80 - length) * pad_char def build_log_string(parsed_original): def build_log_lists(parsed): str_list, format_list = [], [] for...
null
15,369
import asyncio from abc import ABC, abstractmethod from typing import TypeVar, Generic, Callable, Dict, Awaitable, Iterable, Tuple, ClassVar Request = TypeVar("Request") Result = TypeVar("Result") _RequestKeyT = str _BatchHandlerFunctionT = Callable[ [Tuple[Request, ...]], Awaitable[Iterable[Tuple[Request, Result]]...
Construct an object which will automatically batch every call to `get_result` into periodic calls to `handler_function`. This function is the preferred way to make a one-off batch manager with minimal lines of code. If you find yourself calling this function with the same arguments multiple times, consider instead defi...
15,370
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def check_and_warn_input_range(tensor, min_value, max_value, name): actual_min = tensor.min() actual_max = ...
null
15,371
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def sum_dict_with_prefix(target, cur_dict, prefix, default=0): for k, v in cur_dict.items(): target_key ...
null
15,372
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def add_prefix_to_keys(dct, prefix): return {prefix + k: v for k, v in dct.items()}
null
15,373
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def set_requires_grad(module, value): for param in module.parameters(): param.requires_grad = value
null
15,374
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def flatten_dict(dct): result = {} for k, v in dct.items(): if isinstance(k, tuple): k ...
null
15,375
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform class LinearRamp: def __init__(self, start_value=0, end_value=1, start_iter=-1, end_iter=0): self.start_...
null
15,376
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything LOGGER = logging.getLogger(__name__) import platform def print_traceback_handler(sig, frame): LOGGER.warning(f'Received signal {...
null
15,377
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def handle_deterministic_config(config): seed = dict(config).get('seed', None) if seed is None: ret...
null
15,378
import bisect import functools import logging import numbers import os import signal import sys import traceback import warnings import torch from pytorch_lightning import seed_everything import platform def get_shape(t): if torch.is_tensor(t): return tuple(t.shape) elif isinstance(t, dict): re...
null