id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
17,814
import argparse import time from functools import partial import kwt import mlx.core as mx import mlx.data as dx import mlx.nn as nn import mlx.optimizers as optim from mlx.data.datasets import load_speechcommands from mlx.data.features import mfsc def prepare_dataset(batch_size, split, root=None): def normalize(x...
null
17,815
import argparse import time from functools import partial import kwt import mlx.core as mx import mlx.data as dx import mlx.nn as nn import mlx.optimizers as optim from mlx.data.datasets import load_speechcommands from mlx.data.features import mfsc def train_epoch(model, train_iter, optimizer, epoch): def train_st...
null
17,816
import argparse import time from functools import partial import kwt import mlx.core as mx import mlx.data as dx import mlx.nn as nn import mlx.optimizers as optim from mlx.data.datasets import load_speechcommands from mlx.data.features import mfsc def eval_fn(model, x, y): return mx.mean(mx.argmax(model(x), axis=1...
null
17,817
from typing import Any import mlx.core as mx import mlx.nn as nn from mlx.utils import tree_flatten class KWT(nn.Module): """ Implements the Keyword Transformer (KWT) [1] model. KWT is essentially a vision transformer [2] with minor modifications: - Instead of square patches, KWT uses rectangular patche...
null
17,818
from typing import Any import mlx.core as mx import mlx.nn as nn from mlx.utils import tree_flatten class KWT(nn.Module): """ Implements the Keyword Transformer (KWT) [1] model. KWT is essentially a vision transformer [2] with minor modifications: - Instead of square patches, KWT uses rectangular patche...
null
17,819
from typing import Any import mlx.core as mx import mlx.nn as nn from mlx.utils import tree_flatten class KWT(nn.Module): """ Implements the Keyword Transformer (KWT) [1] model. KWT is essentially a vision transformer [2] with minor modifications: - Instead of square patches, KWT uses rectangular patche...
null
17,820
from functools import partial import matplotlib.pyplot as plt import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np from flows import RealNVP from sklearn import datasets, preprocessing from tqdm import trange The provided code snippet includes necessary dependencies for implement...
Get two moons dataset with given noise level.
17,821
import argparse import copy import hashlib import json import os import urllib import warnings from dataclasses import asdict from pathlib import Path from typing import List import mlx.core as mx import mlx.nn as nn import numpy as np import torch from mlx.utils import tree_flatten, tree_map, tree_unflatten from tqdm ...
Load a Whisper ASR model Parameters ---------- name_or_path : str one of the official model names listed by `whisper.available_models()` or a local Pytorch checkpoint which is in the original OpenAI format download_root: str path to download the model files; by default, it uses "~/.cache/whisper" Returns ------- model ...
17,822
import argparse import copy import hashlib import json import os import urllib import warnings from dataclasses import asdict from pathlib import Path from typing import List import mlx.core as mx import mlx.nn as nn import numpy as np import torch from mlx.utils import tree_flatten, tree_map, tree_unflatten from tqdm ...
null
17,823
import argparse import copy import hashlib import json import os import urllib import warnings from dataclasses import asdict from pathlib import Path from typing import List import mlx.core as mx import mlx.nn as nn import numpy as np import torch from mlx.utils import tree_flatten, tree_map, tree_unflatten from tqdm ...
null
17,824
import argparse import copy import hashlib import json import os import urllib import warnings from dataclasses import asdict from pathlib import Path from typing import List import mlx.core as mx import mlx.nn as nn import numpy as np import torch from mlx.utils import tree_flatten, tree_map, tree_unflatten from tqdm ...
null
17,825
import base64 import gzip from dataclasses import dataclass from typing import Dict, Iterable, Optional import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn The provided code snippet includes necessary dependencies for implementing the `sinusoids` function. Write a Python functi...
Returns sinusoids for positional embedding
17,826
import base64 import gzip import math from dataclasses import dataclass from typing import Union import mlx.core as mx import mlx.nn as nn import numpy as np from .decoding import decode as decode_function from .decoding import detect_language as detect_language_function The provided code snippet includes necessary de...
Returns sinusoids for positional embedding
17,827
import sys import warnings from typing import List, Optional, Tuple, Union import mlx.core as mx import numpy as np import tqdm from .audio import ( FRAMES_PER_SECOND, HOP_LENGTH, N_FRAMES, N_SAMPLES, SAMPLE_RATE, log_mel_spectrogram, pad_or_trim, ) from .decoding import DecodingOptions, Dec...
Transcribe an audio file using Whisper Parameters ---------- audio: Union[str, np.ndarray, mx.array] The path to the audio file to open, or the audio waveform path_or_hf_repo: str The localpath to the Whisper model or HF Hub repo with the MLX converted weights. verbose: bool Whether to display the text being decoded to...
17,828
import json from pathlib import Path import mlx.core as mx import mlx.nn as nn from huggingface_hub import snapshot_download from mlx.utils import tree_unflatten from . import whisper def load_model( path_or_hf_repo: str, dtype: mx.Dtype = mx.float32, ) -> whisper.Whisper: model_path = Path(path_or_hf_repo...
null
17,829
argparse import os import subprocess import sys import time import mlx.core as mx from whisper import audio, decoding, load_models, transcribe def parse_arguments(): parser = argparse.ArgumentParser(description="Benchmark script.") parser.add_argument( "--mlx-dir", type=str, default="ml...
null
17,830
import os import subprocess import sys import time import mlx.core as mx from whisper import audio, decoding, load_models, transcribe def timer(fn, *args): for _ in range(5): fn(*args) num_its = 10 tic = time.perf_counter() for _ in range(num_its): fn(*args) toc = time.perf_counte...
null
17,831
import os import subprocess import sys import time import mlx.core as mx from whisper import audio, decoding, load_models, transcribe audio_file = "whisper/assets/ls_test.flac" def feats(n_mels: int = 80): data = audio.load_audio(audio_file) data = audio.pad_or_trim(data) mels = audio.log_mel_spectrogram(d...
null
17,832
import os import subprocess import sys import time import mlx.core as mx from whisper import audio, decoding, load_models, transcribe def model_forward(model, mels, tokens): logits = model(mels, tokens) mx.eval(logits) return logits
null
17,833
import os import subprocess import sys import time import mlx.core as mx from whisper import audio, decoding, load_models, transcribe def decode(model, mels): return decoding.decode(model, mels)
null
17,834
import os import subprocess import sys import time import mlx.core as mx from whisper import audio, decoding, load_models, transcribe audio_file = "whisper/assets/ls_test.flac" def everything(model_path): return transcribe(audio_file, path_or_hf_repo=model_path)
null
17,835
import argparse import time from functools import partial from pathlib import Path import dataset import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import vae from mlx.utils import tree_flatten from PIL import Image def loss_fn(model, X): X_recon, mu, logvar = model(X) ...
null
17,836
import argparse import time from functools import partial from pathlib import Path import dataset import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import vae from mlx.utils import tree_flatten from PIL import Image def grid_image_from_batch(image_batch, num_rows): """ ...
null
17,837
import argparse import time from functools import partial from pathlib import Path import dataset import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import vae from mlx.utils import tree_flatten from PIL import Image def grid_image_from_batch(image_batch, num_rows): """ ...
null
17,838
import math import mlx.core as mx import mlx.nn as nn def upsample_nearest(x, scale: int = 2): B, H, W, C = x.shape x = mx.broadcast_to(x[:, :, None, :, None, :], (B, H, scale, W, scale, C)) x = x.reshape(B, H * scale, W * scale, C) return x
null
17,839
from mlx.data.datasets import load_mnist def mnist(batch_size, img_size, root=None): # load train and test sets using mlx-data load_fn = load_mnist tr = load_fn(root=root, train=True) test = load_fn(root=root, train=False) # number of image channels is 1 for MNIST num_img_channels = 1 # n...
null
17,840
import math import time from functools import partial import datasets import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np from mlx.utils import tree_flatten def to_samples(context_size, dataset): tokens = dataset.size window_size = context_size + 1 # include target s...
null
17,841
import io import itertools import os import zipfile from urllib import request import numpy as np def wikitext(dataset="2", save_dir="/tmp"): def ptb(save_dir="/tmp"): def load_dataset(dataname): if dataname == "ptb": return ptb() elif dataname == "wikitext2": return wikitext(dataset="2") e...
null
17,842
import argparse import time from functools import partial import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import mnist def loss_fn(model, X, y): return nn.losses.cross_entropy(model(X), y, reduction="mean")
null
17,843
import argparse import time from functools import partial import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import mnist def batch_iterate(batch_size, X, y): perm = mx.array(np.random.permutation(y.size)) for s in range(0, y.size, batch_size): ids = perm[s : s ...
null
17,844
import gzip import os import pickle from urllib import request import numpy as np def mnist( save_dir="/tmp", base_url="http://yann.lecun.com/exdb/mnist/", filename="mnist.pkl" ): def fashion_mnist(save_dir="/tmp"): return mnist( save_dir, base_url="http://fashion-mnist.s3-website.eu-central-1....
null
17,845
import argparse from time import perf_counter_ns from typing import List, Optional, Tuple import mlx.core as mx import mlx.nn as nn import numpy as np from mlx.utils import tree_map, tree_unflatten from transformers import AutoTokenizer, T5Config The provided code snippet includes necessary dependencies for implementi...
Adapted from HF Tensorflow: https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py Translate relative position to a bucket number for relative attention. The relative position is defined as memory_position - query_position, i.e. the distance in tokens from the attending position...
17,846
import argparse from time import perf_counter_ns from typing import List, Optional, Tuple import mlx.core as mx import mlx.nn as nn import numpy as np from mlx.utils import tree_map, tree_unflatten from transformers import AutoTokenizer, T5Config class T5(nn.Module): def __init__(self, config: T5Config): def ...
null
17,847
import argparse from time import perf_counter_ns from typing import List, Optional, Tuple import mlx.core as mx import mlx.nn as nn import numpy as np from mlx.utils import tree_map, tree_unflatten from transformers import AutoTokenizer, T5Config class T5(nn.Module): def __init__(self, config: T5Config): se...
null
17,848
import argparse from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, T5EncoderModel def embed(t5_model: str): batch = [ "translate English to German: That is good.", "This is an example of T5 working on MLX.", ] tokenizer = AutoTokenizer.from_pretrained(t5_model) torch_model ...
null
17,849
import argparse from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, T5EncoderModel def generate(t5_model: str): prompt = "translate English to German: As much as six inches of rain could fall in the New York City region through Monday morning, and officials warned of flooding along the coast." token...
null
17,851
import argparse import numpy from transformers import BertModel def replace_key(key: str) -> str: key = key.replace(".layer.", ".layers.") key = key.replace(".self.key.", ".key_proj.") key = key.replace(".self.query.", ".query_proj.") key = key.replace(".self.value.", ".value_proj.") key = key.repla...
null
17,852
import argparse from dataclasses import dataclass from pathlib import Path from typing import List, Optional, Tuple import mlx.core as mx import mlx.nn as nn import numpy import numpy as np from mlx.utils import tree_unflatten from transformers import BertTokenizer def load_model(bert_model: str, weights_path: str) -> ...
null
17,853
from typing import Tuple from image_processor import CLIPImageProcessor from model import CLIPModel from tokenizer import CLIPTokenizer class CLIPImageProcessor: """ A simple port of https://github.com/huggingface/transformers/blob/main/src/transformers/models/clip/image_processing_clip.py. """ de...
null
17,854
import argparse import json import shutil from pathlib import Path from typing import Any, Dict, Union import mlx.core as mx import torch from huggingface_hub import snapshot_download def make_shards(weights: dict, max_file_size_gb: int = 5) -> list: max_file_size_bytes = max_file_size_gb << 30 shards = [] ...
Save model weights into specified directory.
17,855
import argparse import json import shutil from pathlib import Path from typing import Any, Dict, Union import mlx.core as mx import torch from huggingface_hub import snapshot_download def get_model_path(path_or_hf_repo: str) -> Path: model_path = Path(path_or_hf_repo) if not model_path.exists(): model_...
null
17,856
import argparse import json import shutil from pathlib import Path from typing import Any, Dict, Union import mlx.core as mx import torch from huggingface_hub import snapshot_download def torch_to_mx(a: torch.Tensor, *, dtype: str) -> mx.array: # bfloat16 is not numpy convertible. Upcast to float32 to avoid precis...
null
17,857
import json from pathlib import Path from typing import List, Tuple import mlx.core as mx import numpy as np from PIL.Image import Image The provided code snippet includes necessary dependencies for implementing the `resize` function. Write a Python function `def resize(image: Image, short_size: int) -> Image` to solv...
Resize so small size to short_size
17,858
import json from pathlib import Path from typing import List, Tuple import mlx.core as mx import numpy as np from PIL.Image import Image def center_crop(image: Image, size: Tuple[int, int]) -> Image: if size[0] % 2 != 0 or size[1] % 2 != 0: raise ValueError("Only even crop sizes supported.") original_w...
null
17,859
import json from pathlib import Path from typing import List, Tuple import mlx.core as mx import numpy as np from PIL.Image import Image def rescale(image: mx.array) -> mx.array: return image.astype(mx.float32) * (1 / 255.0)
null
17,860
import json from pathlib import Path from typing import List, Tuple import mlx.core as mx import numpy as np from PIL.Image import Image def normalize(image: mx.array, mean: mx.array, std: mx.array) -> mx.array: return (image - mean) / std
null
17,861
import glob import json import logging import math from dataclasses import dataclass from pathlib import Path from typing import Optional, Union import mlx.core as mx import mlx.nn as nn from mlx.core import linalg as LA from mlx.nn.losses import cross_entropy from mlx.utils import tree_flatten The provided code snipp...
A fast GELU approximation https://github.com/hendrycks/GELUs
17,862
import glob import json import logging import math from dataclasses import dataclass from pathlib import Path from typing import Optional, Union import mlx.core as mx import mlx.nn as nn from mlx.core import linalg as LA from mlx.nn.losses import cross_entropy from mlx.utils import tree_flatten def clip_loss(logits: m...
null
17,863
import glob import json import logging from pathlib import Path from typing import Generator import mlx.core as mx import mlx.nn as nn import models.llama as llama import models.mixtral as mixtral import models.phi2 as phi2 import transformers from huggingface_hub import snapshot_download def load(path_or_hf_repo: str)...
null
17,864
import glob import json import logging from pathlib import Path from typing import Generator import mlx.core as mx import mlx.nn as nn import models.llama as llama import models.mixtral as mixtral import models.phi2 as phi2 import transformers from huggingface_hub import snapshot_download def load(path_or_hf_repo: str)...
null
17,865
import glob import json import logging from pathlib import Path from typing import Generator import mlx.core as mx import mlx.nn as nn import models.llama as llama import models.mixtral as mixtral import models.phi2 as phi2 import transformers from huggingface_hub import snapshot_download def make_shards(weights: dict,...
null
17,866
import glob import json import logging from pathlib import Path from typing import Generator import mlx.core as mx import mlx.nn as nn import models.llama as llama import models.mixtral as mixtral import models.phi2 as phi2 import transformers from huggingface_hub import snapshot_download The provided code snippet inc...
Generate text based on the given prompt and model. Args: prompt (mx.array): The input prompt. model (nn.Module): The model to use for generation. temp (float): The temperature for sampling. If temp is 0, use max sampling. Yields: mx.array: The generated text.
17,867
import argparse import copy import mlx.core as mx import mlx.nn as nn import utils from mlx.utils import tree_flatten def quantize(weights, config, args): quantized_config = copy.deepcopy(config) # Get model classes model_class, model_args_class = utils._get_classes(config=config) # Load the model: ...
null
17,868
import glob import inspect import json import math from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional, Tuple, Union import mlx.core as mx import mlx.nn as nn import numpy as np from huggingface_hub import snapshot_download from transformers import AutoTokenizer class Mode...
null
17,869
import glob import inspect import json import math from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional, Tuple, Union import mlx.core as mx import mlx.nn as nn import numpy as np from huggingface_hub import snapshot_download from transformers import AutoTokenizer class Mode...
null
17,870
import json import os class WikiSQL: def __init__(self, dataset, save_dir="/tmp"): valid_sets = ("train", "dev", "test") if dataset not in valid_sets: raise ValueError(f"Dataset must be in {valid_sets}, got {dataset}") data_dir = os.path.join(save_dir, "wikisql") self._ma...
Load all three splits of the WikiSQL dataset.
17,871
import argparse import json import math import time from pathlib import Path import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import utils as lora_utils from mlx.utils import tree_flatten, tree_unflatten from models.lora import LoRALinear def build_parser(): parser = argp...
null
17,872
import argparse import json import math import time from pathlib import Path import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import utils as lora_utils from mlx.utils import tree_flatten, tree_unflatten from models.lora import LoRALinear class Dataset: """ Light-weigh...
null
17,873
import argparse import json import math import time from pathlib import Path import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import utils as lora_utils from mlx.utils import tree_flatten, tree_unflatten from models.lora import LoRALinear def loss(model, inputs, targets, leng...
null
17,874
import argparse import json import math import time from pathlib import Path import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim import numpy as np import utils as lora_utils from mlx.utils import tree_flatten, tree_unflatten from models.lora import LoRALinear def generate(model, prompt, tokenizer...
null
17,875
import argparse import codecs from pathlib import Path import mlx.core as mx import requests from PIL import Image from transformers import AutoProcessor from llava import LlavaModel def parse_arguments(): parser = argparse.ArgumentParser( description="Generate text from an image using a model." ) ...
null
17,876
import argparse import codecs from pathlib import Path import mlx.core as mx import requests from PIL import Image from transformers import AutoProcessor from llava import LlavaModel def load_image(image_source): """ Helper function to load an image from either a URL or file. """ if image_source.startsw...
null
17,877
import argparse import codecs from pathlib import Path import mlx.core as mx import requests from PIL import Image from transformers import AutoProcessor from llava import LlavaModel def load_model(model_path): processor = AutoProcessor.from_pretrained(model_path) model = LlavaModel.from_pretrained(model_path)...
null
17,878
import argparse import codecs from pathlib import Path import mlx.core as mx import requests from PIL import Image from transformers import AutoProcessor from llava import LlavaModel def sample(logits, temperature=0.0): if temperature == 0: return mx.argmax(logits, axis=-1) else: return mx.rando...
null
17,879
import time from argparse import ArgumentParser from functools import partial import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim from datasets import download_cora, load_data, train_val_test_mask from mlx.nn.losses import cross_entropy from mlx.utils import tree_flatten from gcn import GCN def ev...
null
17,880
import time from argparse import ArgumentParser from functools import partial import mlx.core as mx import mlx.nn as nn import mlx.optimizers as optim from datasets import download_cora, load_data, train_val_test_mask from mlx.nn.losses import cross_entropy from mlx.utils import tree_flatten from gcn import GCN def los...
null
17,881
import os import tarfile import mlx.core as mx import numpy as np import requests import scipy.sparse as sparse The provided code snippet includes necessary dependencies for implementing the `train_val_test_mask` function. Write a Python function `def train_val_test_mask()` to solve the following problem: Splits the l...
Splits the loaded dataset into train/validation/test sets.
17,882
import os import tarfile import mlx.core as mx import numpy as np import requests import scipy.sparse as sparse def download_cora(): """Downloads the cora dataset into a local cora folder.""" url = "https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz" extract_to = "." if os.path.exists(os.path.join(extr...
Loads the Cora graph data into MLX array format.
17,883
import hashlib from django.conf import settings def is_request_from_worker(request): auth_header = request.META.get('HTTP_X_AUTH_TOKEN') if auth_header is None: return False if settings.DEBUG: return True hashed_token = hashlib.sha256(auth_header.encode()).hexdigest() return hashed_...
null
17,884
import json import os import secrets from pathlib import Path def show_toolbar(request): return True
null
17,885
import hashlib import itertools import uuid from collections import OrderedDict from datetime import timedelta from django.conf import settings from django.core.cache import cache from django.db import models from django.db.models.signals import post_save from django.db.models.constraints import UniqueConstraint, Check...
null
17,886
import hashlib import itertools import uuid from collections import OrderedDict from datetime import timedelta from django.conf import settings from django.core.cache import cache from django.db import models from django.db.models.signals import post_save from django.db.models.constraints import UniqueConstraint, Check...
null
17,887
import hashlib import itertools import uuid from collections import OrderedDict from datetime import timedelta from django.conf import settings from django.core.cache import cache from django.db import models from django.db.models.signals import post_save from django.db.models.constraints import UniqueConstraint, Check...
null
17,888
from django.db import migrations def populate_completed(apps, schema_editor): DecompilationRequest = apps.get_model('explorer', 'decompilationrequest') DecompilationRequest.objects.exclude(decompilation=None).update(completed=True)
null
17,889
import os import shutil import subprocess import sys import tempfile from pathlib import Path DEWOLF_INSTALL = Path(os.getenv("DEWOLF_INSTALL_PATH", "/home/decompiler_user/dewolf")) def version(): p = subprocess.check_output(['git', 'describe', '--tags', '--abbrev=0', 'HEAD'], cwd=str(DEWOLF_INSTALL)) ver = p....
null
17,890
import os import shutil import subprocess import sys import tempfile from pathlib import Path RETDEC_DECOMPILER = RETDEC_INSTALL / 'retdec-decompiler' def version(): proc = subprocess.run([RETDEC_DECOMPILER, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # RetDec version : v4.0-415-g05c9b113 ...
null
17,891
import argparse import gzip import shlex import signal from dataclasses import dataclass, asdict import logging import os import resource import subprocess import sys import threading import time import traceback import requests def set_limits(soft_mem, hard_mem): resource.setrlimit(resource.RLIMIT_AS, (soft_mem, ...
null
17,892
import os import shutil import subprocess import sys import tempfile from pathlib import Path SNOWMAN_NOCODE = SNOWMAN_INSTALL / 'nocode' def version(): proc = subprocess.run([SNOWMAN_NOCODE, '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Version: v0.1.3-13-g6fed71c output = proc.stdout.decod...
null
17,893
import os import shutil import subprocess import sys import tempfile from pathlib import Path REKO_DECOMPILE = REKO_INSTALL / 'reko' def version(): proc = subprocess.run([REKO_DECOMPILE, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Reko decompiler version 0.11.5.0 (git:36c3481) output = ...
null
17,894
import sys import tempfile from typing import List import angr from angr.analyses import CFGFast, Decompiler from angr.knowledge_plugins import Function import warnings def decompile(): conts = sys.stdin.buffer.read() t = tempfile.NamedTemporaryFile() t.write(conts) t.flush() p = angr.Project(t.na...
null
17,895
import re import os import subprocess import sys from pathlib import Path def relyze_cli_run(params): def version(): success, ver = relyze_cli_run(['/version']) if not success: return 1 match = re.findall(r'\s(\d+\.\d+\.\d+)\s', ver) if len(match) == 0: return 1 print(match[0]) ...
null
17,896
import os import shutil import subprocess import sys import tempfile from pathlib import Path BOOMERANG_CLI = BOOMERANG_INSTALL / 'boomerang-cli' def version(): proc = subprocess.run([BOOMERANG_CLI, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # boomerang-cli v0.5.2 output = proc.stdout.de...
null
17,897
import os import shutil import subprocess import sys import tempfile from pathlib import Path RECSTUDIO_CLI = RECSTUDIO_INSTALL / 'RecCLI' def version(): with open(RECSTUDIO_CLI, 'rb') as f: # <h3>Welcome to RecStudio 4.1</h3> conts = f.read() assert b'<h3>Welcome to RecStudio ' in conts ...
null
17,898
import os import shutil import subprocess import sys import tempfile from pathlib import Path IDA_IDAT = IDA_INSTALL / 'idat' IDA_VERSION_PY = IDA_INSTALL / 'version.py' def version(): logpath = Path(os.getcwd()) / 'ida.log' try: # TODO: Is there a way to do this without creating an idb? with ...
null
17,899
from __future__ import print_function import ida_ida import ida_auto import ida_loader import ida_hexrays import ida_idp import ida_entry import idautils import os.path def init_hexrays(): ALL_DECOMPILERS = { ida_idp.PLFM_386: "hexrays", ida_idp.PLFM_ARM: "hexarm", ida_idp.PLFM_PPC: "hexppc...
null
17,900
import os import sys import shutil import argparse import subprocess def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs)
null
17,901
import os import sys import shutil import argparse import subprocess def delete_files(path, exts): for ext in exts: tmpfile = path + ext if os.path.exists(tmpfile): os.unlink(tmpfile)
null
17,902
import os import sys import shutil import argparse import subprocess platforms_32 = [HEX_X86, HEX_ARM, HEX_PPC, HEX_MIPS ] platforms_64 = [HEX_X64, HEX_ARM64, HEX_PPC64, HEX_MIPS64] def get_bitness(efd, path): # check if the input file is decompilable, and its bitness p = subprocess.run([efd, '-z', path]) e...
null
17,903
import argparse import os import secrets import subprocess import sys from pathlib import Path DATA_DIR = BASE_DIR / 'db_data' MEDIA_DIR = BASE_DIR / 'media' STATICFILES_DIR = BASE_DIR / 'staticfiles' def _generate_secrets(force=False): if not SECRETS_DIR.exists(): SECRETS_DIR.mkdir() for secret_name in...
null
17,904
import argparse import os import secrets import subprocess import sys from pathlib import Path BASE_COMPOSE_FILE = BASE_DIR / 'docker-compose.yml' PROD_COMPOSE_FILE = BASE_DIR / 'docker-compose.prod.yml' DEV_COMPOSE_FILE = BASE_DIR / 'docker-compose.dev.yml' DECOMPILERS = [ ('angr', 'angr'), ('boomerang'...
null
17,905
import argparse import os import secrets import subprocess import sys from pathlib import Path BASE_COMPOSE_FILE = BASE_DIR / 'docker-compose.yml' PROD_COMPOSE_FILE = BASE_DIR / 'docker-compose.prod.yml' DEV_COMPOSE_FILE = BASE_DIR / 'docker-compose.dev.yml' S3_COMPOSE_FILE = BASE_DIR / 'docker-compose.s3.yml' def sta...
null
17,906
import argparse import os import secrets import subprocess import sys from pathlib import Path def stop_server(): cmd = f"docker stack rm dogbolt" subprocess.run(cmd.split(' '), check=True)
null
17,907
import datasets def simple_accuracy(preds, labels): return (preds == labels).mean()
null
17,908
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets def compute_exact(a_gold, a_pred): def compute_em(predictions, references): scores = [any(compute_exact(ref, pred) for ref in refs) for pred, refs in zip(predictions, references)...
null
17,909
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets def SARIsent(ssent, csent, rsents): numref = len(rsents) s1grams = ssent.split(" ") c1grams = csent.split(" ") s2grams = [] c2grams = [] s3grams = [] c3gra...
null
17,910
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets def compute_sacrebleu( predictions, references, smooth_method="exp", smooth_value=None, force=False, lowercase=False, use_effective_order=False, ): re...
null
17,911
import coval from coval.conll import reader, util from coval.eval import evaluator import datasets logger = datasets.logging.get_logger(__name__) def get_coref_infos( key_lines, sys_lines, NP_only=False, remove_nested=False, keep_singletons=True, min_span=False, doc="dummy_doc" ): key_doc_lines = {doc: key_lin...
null
17,912
import coval from coval.conll import reader, util from coval.eval import evaluator import datasets def check_gold_parse_annotation(key_lines): has_gold_parse = False for line in key_lines: if not line.startswith("#"): if len(line.split()) > 6: parse_col = line.split()[5] ...
null
17,913
from typing import List from packaging import version from sklearn.metrics import f1_score import datasets from datasets.config import PY_VERSION def simple_accuracy(preds, labels): return float((preds == labels).mean()) def f1_and_simple_accuracy(preds, labels): return { "f1": float(f1_score(y_true=la...
null
17,914
from typing import List from packaging import version from sklearn.metrics import f1_score import datasets from datasets.config import PY_VERSION def bleu( preds, labels, smooth_method="exp", smooth_value=None, force=False, lowercase=False, tokenize=None, use_effective_order=False, ): ...
null