repo_name
stringlengths
7
71
file_path
stringlengths
5
118
context
list
import_statement
stringlengths
45
12.5k
token_num
int64
641
99.4k
cropped_code
stringlengths
44
17k
all_code
stringlengths
43
754k
next_line
stringlengths
2
330
gold_snippet_index
int64
0
68
created_at
stringlengths
25
25
level
stringclasses
9 values
YaoFANGUK/video-subtitle-remover
backend/inpaint/video/raft/corr.py
[ { "identifier": "bilinear_sampler", "path": "backend/inpaint/video/raft/utils/utils.py", "snippet": "def bilinear_sampler(img, coords, mode='bilinear', mask=False):\n \"\"\" Wrapper for grid_sample, uses pixel coordinates \"\"\"\n H, W = img.shape[-2:]\n xgrid, ygrid = coords.split([1,1], dim=-...
import torch import torch.nn.functional as F import alt_cuda_corr from .utils.utils import bilinear_sampler, coords_grid
673
try: except: # alt_cuda_corr is not compiled pass class CorrBlock: def __init__(self, fmap1, fmap2, num_levels=4, radius=4): self.num_levels = num_levels self.radius = radius self.corr_pyramid = [] # all pairs correlation corr = CorrBlock.corr(fmap1, fmap2) ...
try: except: # alt_cuda_corr is not compiled pass class CorrBlock: def __init__(self, fmap1, fmap2, num_levels=4, radius=4): self.num_levels = num_levels self.radius = radius self.corr_pyramid = [] # all pairs correlation corr = CorrBlock.corr(fmap1, fmap2) ...
corr = bilinear_sampler(corr, coords_lvl)
0
2023-10-25 02:50:01+00:00
2k
Genesis-Embodied-AI/RoboGen
objaverse_utils/find_uid_utils.py
[ { "identifier": "text_to_uid_dict", "path": "objaverse_utils/utils.py", "snippet": "" }, { "identifier": "check_text_similarity", "path": "gpt_4/verification.py", "snippet": "def check_text_similarity(text, check_list=None, check_embeddings=None):\n global sentence_bert_model\n if ...
import pandas as pd import torch import numpy as np import json from objaverse_utils.utils import text_to_uid_dict from gpt_4.verification import check_text_similarity from gpt_4.bard_verify import verify_objaverse_object
1,182
objaverse_csv = pd.read_csv('objaverse_utils/Cap3D_automated_Objaverse.csv') objaverse_csv = objaverse_csv.dropna() objaverse_csv_uids = list(objaverse_csv.iloc[:, 0].values) objaverse_csv_annotations = list(objaverse_csv.iloc[:, 1].values) objaverse_csv_annotations_embeddings = torch.load("objaverse_utils/data/cap3d_...
objaverse_csv = pd.read_csv('objaverse_utils/Cap3D_automated_Objaverse.csv') objaverse_csv = objaverse_csv.dropna() objaverse_csv_uids = list(objaverse_csv.iloc[:, 0].values) objaverse_csv_annotations = list(objaverse_csv.iloc[:, 1].values) objaverse_csv_annotations_embeddings = torch.load("objaverse_utils/data/cap3d_...
uids = text_to_uid_dict.get(obj_descrption, None)
0
2023-10-31 19:44:09+00:00
2k
junhoyeo/BetterOCR
betterocr/detect.py
[ { "identifier": "extract_json", "path": "betterocr/parsers.py", "snippet": "def extract_json(input_string):\n # Find the JSON in the string\n matches = re.findall(r'{\\s*\"data\"\\s*:\\s*\"(.*?)\"\\s*}', input_string, re.DOTALL)\n if matches:\n # Correctly escape special characters\n ...
from threading import Thread from queue import Queue from openai import OpenAI from .parsers import extract_json, extract_list, rectangle_corners from .wrappers import ( job_easy_ocr, job_easy_ocr_boxes, job_tesseract, job_tesseract_boxes, ) from .wrappers.easy_pororo_ocr import job_easy...
1,298
def wrapper(func, args, queue): queue.put(func(args)) # custom error class NoTextDetectedError(Exception): pass def detect(): """Unimplemented""" raise NotImplementedError def detect_async(): """Unimplemented""" raise NotImplementedError def get_jobs(languages: list[str], boxes=False...
def wrapper(func, args, queue): queue.put(func(args)) # custom error class NoTextDetectedError(Exception): pass def detect(): """Unimplemented""" raise NotImplementedError def detect_async(): """Unimplemented""" raise NotImplementedError def get_jobs(languages: list[str], boxes=False...
job_easy_ocr if not boxes else job_easy_ocr_boxes,
3
2023-10-26 11:26:25+00:00
2k
KoeAI/LLVC
infer.py
[ { "identifier": "Net", "path": "model.py", "snippet": "class Net(nn.Module):\n def __init__(self, label_len, L=8,\n enc_dim=512, num_enc_layers=10,\n dec_dim=256, dec_buf_len=100, num_dec_layers=2,\n dec_chunk_size=72, out_buf_len=2,\n u...
from model import Net from utils import glob_audio_files from tqdm import tqdm import torch import torchaudio import time import numpy as np import argparse import json import os
1,507
def load_model(checkpoint_path, config_path): with open(config_path) as f: config = json.load(f)
def load_model(checkpoint_path, config_path): with open(config_path) as f: config = json.load(f)
model = Net(**config['model_params'])
0
2023-10-28 01:58:49+00:00
2k
aurelio-labs/semantic-router
semantic_router/llms/llamacpp.py
[ { "identifier": "BaseLLM", "path": "semantic_router/llms/base.py", "snippet": "class BaseLLM(BaseModel):\n name: str\n\n class Config:\n arbitrary_types_allowed = True\n\n def __init__(self, name: str, **kwargs):\n super().__init__(name=name, **kwargs)\n\n def __call__(self, me...
from contextlib import contextmanager from pathlib import Path from typing import Any, Optional from llama_cpp import Llama, LlamaGrammar from semantic_router.llms.base import BaseLLM from semantic_router.schema import Message from semantic_router.utils.logger import logger
1,212
class LlamaCppLLM(BaseLLM): llm: Llama temperature: float max_tokens: Optional[int] = 200 grammar: Optional[LlamaGrammar] = None def __init__( self, llm: Llama, name: str = "llama.cpp", temperature: float = 0.2, max_tokens: Optional[int] = 200, gr...
class LlamaCppLLM(BaseLLM): llm: Llama temperature: float max_tokens: Optional[int] = 200 grammar: Optional[LlamaGrammar] = None def __init__( self, llm: Llama, name: str = "llama.cpp", temperature: float = 0.2, max_tokens: Optional[int] = 200, gr...
logger.error(f"LLM error: {e}")
2
2023-10-30 12:12:45+00:00
2k
baaivision/JudgeLM
judgelm/llm_judge/gen_model_judgement_mmvet.py
[ { "identifier": "load_questions", "path": "judgelm/llm_judge/common.py", "snippet": "def parse_score(review):\ndef translate_score_to_win_list(score_list, T=0.0):\ndef generate_question_template(domain, question1, question2):\ndef reorg_answer_file(answer_file):\n def __init__(self, keywords, tokeniz...
import argparse import json import os import time import shortuuid import torch import sys import random import ray from tqdm import tqdm from pathlib import Path # if you haven't already done so from judgelm.llm_judge.common import load_questions, reorg_answer_file, conv_judge_vqa_single_answer, Ke...
937
"""Generate answers with local models. """ file = Path(__file__).resolve() root = file.parents[2] sys.path.append(str(root)) print(sys.path) def run_eval( model_path, model_id, question_file, question_begin, question_end, answer_file, max_new_token, num_gpus_per_model, num_gpus...
"""Generate answers with local models. """ file = Path(__file__).resolve() root = file.parents[2] sys.path.append(str(root)) print(sys.path) def run_eval( model_path, model_id, question_file, question_begin, question_end, answer_file, max_new_token, num_gpus_per_model, num_gpus...
model, tokenizer = load_model(
1
2023-10-26 19:41:07+00:00
2k
EulerSearch/embedding_studio
embedding_studio/api/api_v1/endpoints/fine_tuning.py
[ { "identifier": "FineTuningTaskCreate", "path": "embedding_studio/api/api_v1/schemas/fine_tuning.py", "snippet": "class FineTuningTaskCreate(BaseModel):\n fine_tuning_method: str\n batch_id: Optional[str] = None\n metadata: Optional[Dict] = None\n idempotency_key: Optional[uuid.UUID] = None"...
import logging from typing import Any, List from dramatiq_abort import abort as dramatiq_abort from fastapi import APIRouter, HTTPException, status from embedding_studio.api.api_v1.schemas.fine_tuning import ( FineTuningTaskCreate, FineTuningTaskResponse, ) from embedding_studio.context.app_context import conte...
1,238
logger = logging.getLogger(__name__) router = APIRouter() @router.post( "/task", response_model=FineTuningTaskResponse, response_model_by_alias=False, response_model_exclude_none=True, ) def create_fine_tuning_task(
logger = logging.getLogger(__name__) router = APIRouter() @router.post( "/task", response_model=FineTuningTaskResponse, response_model_by_alias=False, response_model_exclude_none=True, ) def create_fine_tuning_task(
body: FineTuningTaskCreate,
0
2023-10-31 00:33:13+00:00
2k
reworkd/bananalyzer
tests/test_examples.py
[ { "identifier": "download_examples", "path": "bananalyzer/data/examples.py", "snippet": "def are_examples_available(path: Path) -> bool:\ndef get_examples_path() -> Path:\ndef convert_to_crlf(file_path: Path) -> None:\ndef download_examples() -> None:\ndef load_examples_at_path(path: Path, examples_json...
import json import os import shutil import pytest from pathlib import Path from typing import List from unittest.mock import mock_open from pytest_mock import MockFixture from bananalyzer.data.examples import ( download_examples, downloaded_examples_path, get_all_examples, get_example_by_url, get_ex...
932
def test_load_examples_at_path_success(mocker: MockFixture) -> None: data: List[Example] = [] mocker.patch("builtins.open", mock_open(read_data=json.dumps(data))) loaded_examples = load_examples_at_path(Path("/fake/path"), "fake.json") assert len(loaded_examples) == len(data) assert all(isinstan...
def test_load_examples_at_path_success(mocker: MockFixture) -> None: data: List[Example] = [] mocker.patch("builtins.open", mock_open(read_data=json.dumps(data))) loaded_examples = load_examples_at_path(Path("/fake/path"), "fake.json") assert len(loaded_examples) == len(data) assert all(isinstan...
assert get_examples_path() == local_examples_path
0
2023-10-30 16:40:57+00:00
2k
OpenMask3D/openmask3d
openmask3d/mask_features_computation/features_extractor.py
[ { "identifier": "Camera", "path": "openmask3d/data/load.py", "snippet": "class Camera:\n def __init__(self, \n intrinsic_path, \n intrinsic_resolution, \n poses_path, \n depths_path, \n extension_depth, \n ...
import clip import numpy as np import imageio import torch import os from tqdm import tqdm from openmask3d.data.load import Camera, InstanceMasks3D, Images, PointCloud, get_number_of_images from openmask3d.mask_features_computation.utils import initialize_sam_model, mask2box_multi_level, run_sam
1,519
class PointProjector: def __init__(self, camera: Camera, point_cloud: PointCloud,
class PointProjector: def __init__(self, camera: Camera, point_cloud: PointCloud,
masks: InstanceMasks3D,
1
2023-10-31 14:58:50+00:00
2k
nv-tlabs/vid2player3d
embodied_pose/models/im_network_builder.py
[ { "identifier": "RunningNorm", "path": "embodied_pose/models/running_norm.py", "snippet": "class RunningNorm(nn.Module):\n \"\"\"\n y = (x-mean)/std\n using running estimates of mean,std\n \"\"\"\n\n def __init__(self, dim, demean=True, destd=True, clip=5.0):\n super().__init__()\n...
from rl_games.algos_torch import network_builder from rl_games.algos_torch.running_mean_std import RunningMeanStd from isaacgym.torch_utils import * from .running_norm import RunningNorm from utils import torch_utils from utils.torch_transform import heading_to_vec, rotation_matrix_to_angle_axis, rotation_matrix_to_qua...
1,231
DISC_LOGIT_INIT_SCALE = 1.0 mujoco_joint_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] s...
DISC_LOGIT_INIT_SCALE = 1.0 mujoco_joint_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] s...
self.running_obs = RunningNorm(self.humanoid_obs_dim)
0
2023-10-30 20:43:43+00:00
2k
vLAR-group/RayDF
net_multiview/network.py
[ { "identifier": "DualVisClassifier", "path": "net_classifier/network.py", "snippet": "class DualVisClassifier(nn.Module):\n def __init__(self, D=8, W=512, ext_layer=1, input_ch=11, w0_init=30.):\n super(DualVisClassifier, self).__init__()\n\n self.layer_ray = nn.ModuleList(\n ...
import os import torch import torch.nn as nn import sys from net_classifier.network import DualVisClassifier from utils.layer import Siren from utils.ray import get_rayparam_func
1,173
sys.path.append('../') EPS = 1e-8 class RaySurfDNet(nn.Module): def __init__(self, D=8, W=256, input_ch=4, rgb_layer=0, w0_init=30.): super(RaySurfDNet, self).__init__() self.predict_rgb = True if rgb_layer > 0 else False n_ext = max(rgb_layer, 1) self.lf_encoder = nn.ModuleList...
sys.path.append('../') EPS = 1e-8 class RaySurfDNet(nn.Module): def __init__(self, D=8, W=256, input_ch=4, rgb_layer=0, w0_init=30.): super(RaySurfDNet, self).__init__() self.predict_rgb = True if rgb_layer > 0 else False n_ext = max(rgb_layer, 1) self.lf_encoder = nn.ModuleList...
ray_fn, input_ch = get_rayparam_func(scene_info)
2
2023-10-30 14:05:51+00:00
2k
francescofugazzi/3dgsconverter
gsconverter/utils/utility.py
[ { "identifier": "debug_print", "path": "gsconverter/utils/utility_functions.py", "snippet": "def debug_print(message):\n if config.DEBUG:\n print(message)" }, { "identifier": "init_worker", "path": "gsconverter/utils/utility_functions.py", "snippet": "def init_worker():\n si...
import numpy as np import multiprocessing from multiprocessing import Pool, cpu_count from .utility_functions import debug_print, init_worker
913
""" 3D Gaussian Splatting Converter Copyright (c) 2023 Francesco Fugazzi This software is released under the MIT License. For more information about the license, please see the LICENSE file. """ class Utility: @staticmethod def text_based_detect_format(file_path): debug_print("[DEBUG] Executing 'text...
""" 3D Gaussian Splatting Converter Copyright (c) 2023 Francesco Fugazzi This software is released under the MIT License. For more information about the license, please see the LICENSE file. """ class Utility: @staticmethod def text_based_detect_format(file_path): debug_print("[DEBUG] Executing 'text...
with Pool(processes=num_cores, initializer=init_worker) as pool:
1
2023-10-28 15:09:50+00:00
2k
solangii/MICS
models/network/resnet20.py
[ { "identifier": "to_one_hot", "path": "utils/mixup_utils.py", "snippet": "def to_one_hot(inp, num_classes):\n y_onehot = torch.FloatTensor(inp.size(0), num_classes)\n y_onehot.zero_()\n\n y_onehot.scatter_(1, inp.unsqueeze(1).data.cpu(), 1)\n\n return Variable(y_onehot.cuda(), requires_grad=...
import torch import torch.nn as nn import numpy as np import random from utils.mixup_utils import to_one_hot, middle_mixup_process, get_lambda from torch.autograd import Variable
1,436
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=Non...
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=Non...
out, target_reweighted, mix_label_mask = middle_mixup_process(out, target_reweighted, num_base_classes,
1
2023-10-25 16:50:51+00:00
2k
megvii-research/WACV2024-SAFA
model/flownet.py
[ { "identifier": "warp", "path": "model/warplayer.py", "snippet": "def warp(tenInput, tenFlow, mode='bilinear'):\n k = (str(tenFlow.device), str(tenFlow.size()))\n if k not in backwarp_tenGrid:\n tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3]).view(1, 1, 1, tenFlow.shape[3]).expa...
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models from model.warplayer import warp from model.head import Head
1,255
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, groups=1): return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilati...
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, groups=1): return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilati...
i0 = warp(i0, flow_down[:, :2] * 0.5)
0
2023-10-26 09:24:29+00:00
2k
Z4kSec/IoctlHunter
ioctl_hunter/ui/keys_reader.py
[ { "identifier": "State", "path": "ioctl_hunter/lib/state.py", "snippet": "class State:\n results = Results()\n\n script = None\n cur_proc = None\n\n quiet = False\n running = True\n hook_enabled = False\n debug_enabled = False\n hex_out_enabled = False\n\n included_drivers = [...
import sys import threading import time import logging import msvcrt from colorama import init, Fore, Style from ..lib.state import State from ..ui.display import ( print_enable_debugger, print_disable_debugger, print_dynamic_helper, )
1,022
logger = logging.getLogger("ioctl-hunter") class KeysListenner(threading.Thread): is_debugger_enabled = False def __init__(self): super(KeysListenner, self).__init__(daemon=True) init(convert=True) self.start() def run(self): while not msvcrt.kbhit(): time.sl...
logger = logging.getLogger("ioctl-hunter") class KeysListenner(threading.Thread): is_debugger_enabled = False def __init__(self): super(KeysListenner, self).__init__(daemon=True) init(convert=True) self.start() def run(self): while not msvcrt.kbhit(): time.sl...
print_enable_debugger()
1
2023-10-31 22:38:36+00:00
2k
masked-spacetime-hashing/msth
nerfstudio/process_data/process_data_utils.py
[ { "identifier": "status", "path": "nerfstudio/utils/rich_utils.py", "snippet": "def status(msg: str, spinner: str = \"bouncingBall\", verbose: bool = False):\n \"\"\"A context manager that does nothing is verbose is True. Otherwise it hides logs under a message.\n\n Args:\n msg: The message...
import os import shutil import sys import cv2 import numpy as np from enum import Enum from pathlib import Path from typing import List, Optional, Tuple from rich.console import Console from typing_extensions import Literal, OrderedDict from nerfstudio.utils.rich_utils import status from nerfstudio.utils.scripts import...
1,336
# Copyright 2022 The Nerfstudio Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
# Copyright 2022 The Nerfstudio Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
with status(msg="Converting video to images...", spinner="bouncingBall", verbose=verbose):
0
2023-10-26 04:39:15+00:00
2k
sehyunkwon/ICTC
step2b.py
[ { "identifier": "args", "path": "utils/argument.py", "snippet": "def str2bool(v):" }, { "identifier": "get_gpt_response", "path": "utils/llm_utils.py", "snippet": "def get_gpt_response(system_prompt, user_prompt, api_key, user, model):\n\n headers = {\n \"Content-Type\"...
import os from dotenv import load_dotenv from utils.argument import args from utils.llm_utils import get_gpt_response, get_llama_response
1,139
### Requires the file to be in the following format: "Image-file ... ; Answer: {label}" def post_process(): answer_list = {} # read line by line with open(args.step2a_result_path, 'r') as answers: answers = answers.readlines() for answer in answers: if "Image file-" in answ...
### Requires the file to be in the following format: "Image-file ... ; Answer: {label}" def post_process(): answer_list = {} # read line by line with open(args.step2a_result_path, 'r') as answers: answers = answers.readlines() for answer in answers: if "Image file-" in answ...
response = get_gpt_response(system_prompt, user_prompt, api_key, user, model)
1
2023-10-27 05:00:14+00:00
2k
phineas-pta/comfy-trt-test
comfy_trt/model_manager.py
[ { "identifier": "ModelConfig", "path": "comfy_trt/datastructures.py", "snippet": "class ModelConfig:\n\tprofile: dict\n\tstatic_shapes: bool = False\n\tfp32: bool = False\n\tbaseline_model: str = \"SD15\" # save model info, for values see `comfy/supported_models.py`, breaking change incompatible A1111\...
import hashlib import json import os import logging import copy import torch from .datastructures import ModelConfig, ModelConfigEncoder
1,538
# -*- coding: utf-8 -*- # modified from https://github.com/NVIDIA/Stable-Diffusion-WebUI-TensorRT/blob/main/model_manager.py # CHANGE: retrieve checkpoint info from comfy # STATUS: ok i guess BASE_PATH = os.path.dirname(os.path.realpath(__file__)) ONNX_MODEL_DIR = os.path.join(BASE_PATH, "Unet-onnx") if not os.pat...
# -*- coding: utf-8 -*- # modified from https://github.com/NVIDIA/Stable-Diffusion-WebUI-TensorRT/blob/main/model_manager.py # CHANGE: retrieve checkpoint info from comfy # STATUS: ok i guess BASE_PATH = os.path.dirname(os.path.realpath(__file__)) ONNX_MODEL_DIR = os.path.join(BASE_PATH, "Unet-onnx") if not os.pat...
config = ModelConfig(profile, static_shapes, fp32, baseline_model, prediction_type, inpaint, refit, lora, unet_hidden_dim)
0
2023-10-25 23:58:12+00:00
2k
hydrogram/hydrogram
hydrogram/raw/core/gzip_packed.py
[ { "identifier": "Bytes", "path": "hydrogram/raw/core/primitives/bytes.py", "snippet": "class Bytes(bytes, TLObject):\n @classmethod\n def read(cls, data: BytesIO, *args: Any) -> bytes:\n length = int.from_bytes(data.read(1), \"little\")\n\n if length <= 253:\n x = data.rea...
from gzip import compress, decompress from io import BytesIO from typing import Any, cast from .primitives.bytes import Bytes from .primitives.int import Int from .tl_object import TLObject
1,159
# Hydrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2023 Dan <https://github.com/delivrance> # Copyright (C) 2023-present Hydrogram <https://hydrogram.org> # # This file is part of Hydrogram. # # Hydrogram is free software: you can redistribute it and/or modify # it under the terms o...
# Hydrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2023 Dan <https://github.com/delivrance> # Copyright (C) 2023-present Hydrogram <https://hydrogram.org> # # This file is part of Hydrogram. # # Hydrogram is free software: you can redistribute it and/or modify # it under the terms o...
return cast(GzipPacked, TLObject.read(BytesIO(decompress(Bytes.read(data)))))
0
2023-10-29 16:16:37+00:00
2k
chenruduan/OAReactDiff
oa_reactdiff/tests/utils/test_graph_tools.py
[ { "identifier": "get_edges_index", "path": "oa_reactdiff/utils/_graph_tools.py", "snippet": "def get_edges_index(\n combined_mask: Tensor,\n pos: Optional[Tensor] = None,\n edge_cutoff: Optional[float] = None,\n remove_self_edge: bool = False,\n) -> Tensor:\n r\"\"\"\n\n Args:\n ...
import unittest import torch from torch import Tensor, tensor from oa_reactdiff.utils import ( get_edges_index, get_subgraph_mask, get_n_frag_switch, get_mask_for_frag, )
1,138
class TestBasics(unittest.TestCase): def test_get_mask_for_frag(self): natms = Tensor([2, 0, 3]).long() res = get_mask_for_frag(natms) self.assertTrue(torch.allclose(res, Tensor([0, 0, 2, 2, 2]).long())) def test_get_n_frag_switch(self): natm_list = [tensor([2, 0]), tensor([...
class TestBasics(unittest.TestCase): def test_get_mask_for_frag(self): natms = Tensor([2, 0, 3]).long() res = get_mask_for_frag(natms) self.assertTrue(torch.allclose(res, Tensor([0, 0, 2, 2, 2]).long())) def test_get_n_frag_switch(self): natm_list = [tensor([2, 0]), tensor([...
res = get_n_frag_switch(natm_list)
2
2023-10-30 02:53:38+00:00
2k
lewandofskee/DiAD
ldm/models/diffusion/ddim.py
[ { "identifier": "make_ddim_sampling_parameters", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ...
import torch import numpy as np from tqdm import tqdm from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
1,171
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
0
2023-10-30 14:21:09+00:00
2k
nv-tlabs/trace
tbsim/models/temporal.py
[ { "identifier": "SinusoidalPosEmb", "path": "tbsim/models/trace_helpers.py", "snippet": "class SinusoidalPosEmb(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.dim = dim\n\n def forward(self, x):\n device = x.device\n half_dim = self.dim // 2\n ...
import torch import torch.nn as nn import einops from einops.layers.torch import Rearrange from .trace_helpers import ( SinusoidalPosEmb, Downsample1d, Upsample1d, Conv1dBlock, )
935
# # Based on Diffuser: https://github.com/jannerm/diffuser/blob/main/diffuser/models/temporal.py # class ResidualTemporalMapBlockConcat(nn.Module): def __init__(self, inp_channels, out_channels, time_embed_dim, horizon, kernel_size=5): super().__init__() self.time_mlp = nn.Sequential( ...
# # Based on Diffuser: https://github.com/jannerm/diffuser/blob/main/diffuser/models/temporal.py # class ResidualTemporalMapBlockConcat(nn.Module): def __init__(self, inp_channels, out_channels, time_embed_dim, horizon, kernel_size=5): super().__init__() self.time_mlp = nn.Sequential( ...
SinusoidalPosEmb(time_dim),
0
2023-10-31 18:43:07+00:00
2k
gydpku/PPTC
src/evaluate.py
[ { "identifier": "api_doc", "path": "src/api_doc.py", "snippet": "class API(object):\n def __init__(self, name, parameters, description,\n parameter_description=\"\", composition_instruction=\"\", example=\"\", api_desc=\"\",\n type=\"\",\n implementatio...
from src import api_doc from src import prompt_factor from src import ppt_reader, utils from pptx import Presentation from src import pptx_check from sacremoses import MosesTokenizer from tqdm import tqdm import mosestokenizer import os
1,181
def calc_token_cost(path): text = open(path,'r').read() tokenizer = MosesTokenizer() tokens = tokenizer.tokenize(text) return len(tokens) def calc_acc(label_path, pred_path, instruction, additional_restrictions=[]): pos_total, pos_correct, str_correct = 0,0,0 # position splitted = inst...
def calc_token_cost(path): text = open(path,'r').read() tokenizer = MosesTokenizer() tokens = tokenizer.tokenize(text) return len(tokens) def calc_acc(label_path, pred_path, instruction, additional_restrictions=[]): pos_total, pos_correct, str_correct = 0,0,0 # position splitted = inst...
label_string = ppt_reader.eval_get_contents(need_text=True, need_style=True, need_position=False,need_shape_list=None,ppt=Presentation(label_path))
2
2023-10-25 13:14:46+00:00
2k
secarri/MipFlooding
mipflooding/image_processing.py
[ { "identifier": "setup_logger", "path": "mipflooding/logger.py", "snippet": "def setup_logger(logger_name: str, abs_log_path: str) -> logging.Logger:\n \"\"\"Set up a logger with the specified name and log to the given absolute path, returning the logger instance.\"\"\"\n logger = logging.getLogge...
import logging import math import os import time from pathlib import Path from typing import List, Optional from PIL import Image from .logger import setup_logger, terminate_loggers from .file_utils import clear_log_file, get_output_directory, get_output_filename
1,599
# Default packages # Third party packages # From self package def _open_image_inputs(color: str, alpha: str, logger: logging.Logger) -> List: """Open and return the color and alpha images as a list of Image objects.""" logger.info("--- Opening images in memory...") if not color: color = str(None...
# Default packages # Third party packages # From self package def _open_image_inputs(color: str, alpha: str, logger: logging.Logger) -> List: """Open and return the color and alpha images as a list of Image objects.""" logger.info("--- Opening images in memory...") if not color: color = str(None...
return setup_logger("mipmap_flooding", out_log_file.__str__())
0
2023-10-25 11:05:59+00:00
2k
Lin-jun-xiang/chatgpt-line-bot
chatgpt_linebot/modules/horoscope.py
[ { "identifier": "chat_completion", "path": "chatgpt_linebot/modules/gpt.py", "snippet": "def chat_completion(message: List[Dict]) -> str:\n \"\"\"Use OpenAI API via gpt4free providers\"\"\"\n try:\n response = g4f.ChatCompletion.create(\n model=g4f.models.default,\n me...
import json import re import requests from bs4 import BeautifulSoup from chatgpt_linebot.modules.gpt import chat_completion from chatgpt_linebot.prompts import horoscope_template
668
class Horoscope: HOST = "https://www.cosmopolitan.com/tw/horoscopes/" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } error_msg = ( "Cannot get the horoscope, please try again.🥶\n" ...
class Horoscope: HOST = "https://www.cosmopolitan.com/tw/horoscopes/" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } error_msg = ( "Cannot get the horoscope, please try again.🥶\n" ...
response = chat_completion(
0
2023-10-24 09:01:13+00:00
2k
nv-tlabs/pacer
pacer/env/tasks/vec_task_wrappers.py
[ { "identifier": "VecTaskCPU", "path": "pacer/env/tasks/vec_task.py", "snippet": "class VecTaskCPU(VecTask):\n\n def __init__(self, task, rl_device, sync_frame_time=False, clip_observations=5.0):\n super().__init__(task, rl_device, clip_observations=clip_observations)\n self.sync_frame_t...
from gym import spaces from pacer.env.tasks.vec_task import VecTaskCPU, VecTaskGPU, VecTaskPython import numpy as np import torch
983
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and relat...
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and relat...
class VecTaskGPUWrapper(VecTaskGPU):
1
2023-10-31 20:47:12+00:00
2k
Improbable-AI/dexenv
dexenv/models/state_model.py
[ { "identifier": "DiagGaussianPolicy", "path": "dexenv/models/diag_gaussian_pol/diag_gaussian_policy.py", "snippet": "class DiagGaussianPolicy(nn.Module):\n def __init__(self,\n body_net,\n action_dim,\n init_log_std=-0.2,\n std_cond_in=F...
import gym import torch.nn as nn from collections.abc import Sequence from loguru import logger from dexenv.models.diag_gaussian_pol.diag_gaussian_policy import \ DiagGaussianPolicy from dexenv.models.utils import get_activation from dexenv.models.value_nets.value_net import ValueNet
1,138
class SimpleMLP(nn.Module): def __init__(self, in_dim, out_dim, act): super().__init__() act = get_activation(act) self.body = nn.Sequential( nn.Linear(in_dim, 512), act(), nn.Linear(512, 256), act(), nn.Linear(256, out_dim), ...
class SimpleMLP(nn.Module): def __init__(self, in_dim, out_dim, act): super().__init__() act = get_activation(act) self.body = nn.Sequential( nn.Linear(in_dim, 512), act(), nn.Linear(512, 256), act(), nn.Linear(256, out_dim), ...
critic = ValueNet(critic_body,
2
2023-10-25 17:22:41+00:00
2k
ai-safety-foundation/sparse_autoencoder
sparse_autoencoder/autoencoder/components/tests/test_tied_bias.py
[ { "identifier": "TiedBias", "path": "sparse_autoencoder/autoencoder/components/tied_bias.py", "snippet": "class TiedBias(Module):\n \"\"\"Tied Bias Layer.\n\n The tied pre-encoder bias is a learned bias term that is subtracted from the input before\n encoding, and added back after decoding.\n\n...
from jaxtyping import Float from torch import Tensor from torch.nn import Parameter from sparse_autoencoder.autoencoder.components.tied_bias import TiedBias, TiedBiasPosition from sparse_autoencoder.tensor_types import Axis import torch
1,467
"""Tied Bias Tests.""" def test_pre_encoder_subtracts_bias() -> None: """Check that the pre-encoder bias subtracts the bias.""" encoder_input: Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)] = torch.tensor( [[5.0, 3.0, 1.0]] ) bias = Parameter(torch.tensor([2.0, 4.0, 6.0])) ...
"""Tied Bias Tests.""" def test_pre_encoder_subtracts_bias() -> None: """Check that the pre-encoder bias subtracts the bias.""" encoder_input: Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)] = torch.tensor( [[5.0, 3.0, 1.0]] ) bias = Parameter(torch.tensor([2.0, 4.0, 6.0])) ...
pre_encoder = TiedBias(bias, TiedBiasPosition.PRE_ENCODER)
0
2023-10-27 07:37:15+00:00
2k
vb000/SemanticHearing
src/training/train.py
[ { "identifier": "utils", "path": "src/helpers/utils.py", "snippet": "class Params():\n def __init__(self, json_path):\n def save(self, json_path):\n def update(self, json_path):\n def dict(self):\ndef save_graph(train_metrics, test_metrics, save_dir):\ndef import_attr(import_path):\ndef set_...
import argparse import multiprocessing import os import logging import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import traceback # pylint: disable=import-outside-toplevel import wandb from pathlib import Path from torch.uti...
1,165
""" The main training script for training on synthetic data """ def train_epoch(model: nn.Module, device: torch.device, optimizer: optim.Optimizer,
""" The main training script for training on synthetic data """ def train_epoch(model: nn.Module, device: torch.device, optimizer: optim.Optimizer,
train_loader: torch.utils.data.dataloader.DataLoader,
0
2023-10-30 05:36:07+00:00
2k
openai/bugbounty-gpt
tests/test_openai_classification.py
[ { "identifier": "OpenAIHandler", "path": "bugbounty_gpt/handlers/openai_handler.py", "snippet": "class OpenAIHandler:\n @staticmethod\n def _classifications_sanitization(input_string):\n \"\"\"\n Sanitizes the input string by removing spaces, converting to upper case, and replacing s...
from bugbounty_gpt.handlers.openai_handler import OpenAIHandler from unittest.mock import patch, AsyncMock from bugbounty_gpt.env import OPENAI_PROMPT, OPENAI_MODEL, DEFAULT_CATEGORY import pytest, asyncio
915
def test_classifications_sanitization(): assert OpenAIHandler._classifications_sanitization(" Test Category ") == "TEST_CATEGORY" def test_build_request_data(): submission_content = "Sample content" expected_data = { "model": OPENAI_MODEL, "temperature": 0, "max_tokens": 512, ...
def test_classifications_sanitization(): assert OpenAIHandler._classifications_sanitization(" Test Category ") == "TEST_CATEGORY" def test_build_request_data(): submission_content = "Sample content" expected_data = { "model": OPENAI_MODEL, "temperature": 0, "max_tokens": 512, ...
{"role": "system", "content": OPENAI_PROMPT},
1
2023-10-27 22:41:24+00:00
2k
LeapLabTHU/FamO2O
jax_cql/JaxCQL/sac.py
[ { "identifier": "next_rng", "path": "jax_cql/JaxCQL/jax_utils.py", "snippet": "def next_rng(*args, **kwargs):\n global jax_utils_rng\n return jax_utils_rng(*args, **kwargs)" }, { "identifier": "value_and_multi_grad", "path": "jax_cql/JaxCQL/jax_utils.py", "snippet": "def value_and_...
from collections import OrderedDict from copy import deepcopy from functools import partial from ml_collections import ConfigDict from flax.training.train_state import TrainState from .jax_utils import ( next_rng, value_and_multi_grad, mse_loss, JaxRNG, wrap_function_with_rng, collect_jax_metrics ) from .model ...
1,576
class SAC(object): @staticmethod def get_default_config(updates=None): config = ConfigDict() config.discount = 0.99 config.alpha_multiplier = 1.0 config.use_automatic_entropy_tuning = True config.backup_entropy = False config.target_entropy = 0.0 con...
class SAC(object): @staticmethod def get_default_config(updates=None): config = ConfigDict() config.discount = 0.99 config.alpha_multiplier = 1.0 config.use_automatic_entropy_tuning = True config.backup_entropy = False config.target_entropy = 0.0 con...
self.log_alpha = Scalar(0.0)
6
2023-10-25 11:53:25+00:00
2k
RenShuhuai-Andy/TESTA
data/pretrain_dataset.py
[ { "identifier": "pre_caption", "path": "data/utils.py", "snippet": "def pre_caption(caption, max_words=50):\n caption = re.sub(\n r\"([!\\\"()*#~])\", #r\"([!\\\"()*#:;~])\" #r\"([.!\\\"()*#:;~])\",\n ' ',\n caption.lower(),\n )\n caption = re.sub(\n r\"\\s{2,}\",\n...
import json import os import random import torch import torch import numpy as np import decord import os,glob from pandas import Categorical from torch.utils.data import Dataset from PIL import Image from PIL import ImageFile from decord import VideoReader from data.utils import pre_caption from .randaugment import Tem...
1,012
ImageFile.LOAD_TRUNCATED_IMAGES = True Image.MAX_IMAGE_PIXELS = None decord.bridge.set_bridge('torch') class pretrain_dataset(Dataset): def __init__(self, ann_file, laion_path, transform): self.ann_pretrain = [] for f in ann_file: print('loading '+f) ann = json.load(op...
ImageFile.LOAD_TRUNCATED_IMAGES = True Image.MAX_IMAGE_PIXELS = None decord.bridge.set_bridge('torch') class pretrain_dataset(Dataset): def __init__(self, ann_file, laion_path, transform): self.ann_pretrain = [] for f in ann_file: print('loading '+f) ann = json.load(op...
caption = pre_caption(ann['caption'],30)
0
2023-10-29 12:09:38+00:00
2k
flbraun/poe-palette
data/beasts.py
[ { "identifier": "League", "path": "data/leagues.py", "snippet": "class League:\n type_: LeagueType\n title: str # e.g. \"Ancestor\"\n slug: str # e.g. \"ancestor\"\n is_hardcore: bool" }, { "identifier": "get_ninja_index", "path": "data/ninja.py", "snippet": "@functools.cac...
from collections.abc import Generator from .leagues import League from .ninja import get_ninja_index, make_ninja_url from .trade import make_trade_url from .types import NinjaCategory from .utils import Entry, make_wiki_url
1,262
def get_beasts(league: League) -> Generator[Entry, None, None]: index = get_ninja_index(league) for beast in index.raw[NinjaCategory.BEASTS]: yield Entry( display_text=beast, wiki_url=make_wiki_url(beast), ninja_url=make_ninja_url(league, beast, None, NinjaCategor...
def get_beasts(league: League) -> Generator[Entry, None, None]: index = get_ninja_index(league) for beast in index.raw[NinjaCategory.BEASTS]: yield Entry( display_text=beast, wiki_url=make_wiki_url(beast), ninja_url=make_ninja_url(league, beast, None, NinjaCategor...
trade_url=make_trade_url(league, beast),
3
2023-10-27 11:33:43+00:00
2k
ATR-DBI/CityRefer
models/cityrefer.py
[ { "identifier": "SparseConvEncoder", "path": "models/basic_blocks.py", "snippet": "class SparseConvEncoder(nn.Module):\n def __init__(self, input_dim):\n super().__init__()\n\n self.stem = nn.Sequential(\n BasicConvolutionBlock(input_dim, 32, 3)\n )\n\n self.sta...
import sys import os import importlib import models import torch import torch.nn as nn import torchsparse.nn as spnn from torch.nn.utils.rnn import pad_sequence from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torchsparse.utils.collate import sparse_collate from transformers import BertConf...
1,357
importlib.reload(models) sys.path.append(os.path.join(os.getcwd(), "lib")) # HACK add the lib folder sys.path.append(os.path.join(os.getcwd(), "models")) # HACK add the lib folder class CityRefer(nn.Module): def __init__(self, args, input_feature_dim=0, num_object_class=None, vocab_size=None, pad_token_id=...
importlib.reload(models) sys.path.append(os.path.join(os.getcwd(), "lib")) # HACK add the lib folder sys.path.append(os.path.join(os.getcwd(), "models")) # HACK add the lib folder class CityRefer(nn.Module): def __init__(self, args, input_feature_dim=0, num_object_class=None, vocab_size=None, pad_token_id=...
self.sparse_conv = SparseConvEncoder(self.input_feature_dim) # self.input_feature_dim = 3 -> 128
0
2023-10-25 10:02:28+00:00
2k
OATML-Markslab/ProteinNPT
baselines/data_processing.py
[ { "identifier": "slice_sequences", "path": "utils/data_utils.py", "snippet": "def slice_sequences(list_mutant_mutated_seq_pairs, max_positions=1024, method=\"rolling\", rolling_overlap=100, eval_mode=True, batch_target_labels=None, batch_masked_targets=None, target_names=None, start_idx=1, num_extra_tok...
import sys import numpy as np import h5py import torch from collections import defaultdict from utils.data_utils import slice_sequences, get_indices_retrieved_embeddings from utils.msa_utils import weighted_sample_MSA
1,219
def process_batch(batch, model, alphabet, args, device, MSA_sequences=None, MSA_weights=None, MSA_start_position=None, MSA_end_position=None, eval_mode = True, indel_mode=False, start_idx=1): """ start_idx is the one-indexed postion of the first residue in the sequence. If full sequence is passed (as always as...
def process_batch(batch, model, alphabet, args, device, MSA_sequences=None, MSA_weights=None, MSA_start_position=None, MSA_end_position=None, eval_mode = True, indel_mode=False, start_idx=1): """ start_idx is the one-indexed postion of the first residue in the sequence. If full sequence is passed (as always as...
indices_retrieved_embeddings = get_indices_retrieved_embeddings(batch,args.sequence_embeddings_location)
1
2023-10-28 11:41:05+00:00
2k
dyhBUPT/iKUN
test.py
[ { "identifier": "opt", "path": "opts.py", "snippet": "class opts:\n def __init__(self):\n def parse(self, args=''):" }, { "identifier": "get_model", "path": "model.py", "snippet": "def get_model(opt, name='Model'):\n model = eval(name)(opt)\n model.cuda()\n model = nn.Data...
import os import json import shutil import numpy as np import torch import torch.nn.functional as F import warnings from tqdm import tqdm from os.path import join, exists from collections import defaultdict from torch import nn from torchvision.utils import save_image from opts import opt from utils import * from model...
916
warnings.filterwarnings('ignore') # import `opts` first to set gpus def test_accuracy_v1(model, dataloader, save_img=False): model.eval() TP, FP, FN = 0, 0, 0 assert dataloader.batch_size == 1 if save_img: save_dir = join(opt.save_dir, 'images') os.makedirs(save_dir, exist_ok=True)...
warnings.filterwarnings('ignore') # import `opts` first to set gpus def test_accuracy_v1(model, dataloader, save_img=False): model.eval() TP, FP, FN = 0, 0, 0 assert dataloader.batch_size == 1 if save_img: save_dir = join(opt.save_dir, 'images') os.makedirs(save_dir, exist_ok=True)...
un_norm = get_transform('unnorm', opt, -1)
3
2023-10-31 07:08:37+00:00
2k
CVHub520/yolov5_obb
utils/augmentations.py
[ { "identifier": "LOGGER", "path": "utils/general.py", "snippet": "LOGGER = set_logging(__name__) # define globally (used in train.py, val.py, detect.py, etc.)" }, { "identifier": "check_version", "path": "utils/general.py", "snippet": "def check_version(current='0.0.0', minimum='0.0.0',...
import math import random import cv2 import numpy as np import albumentations as A from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box from utils.metrics import bbox_ioa from utils.rboxs_utils import poly_filter
1,519
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Image augmentation functions """ class Albumentations: # YOLOv5 Albumentations class (optional, only used if package is installed) def __init__(self): self.transform = None try:
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Image augmentation functions """ class Albumentations: # YOLOv5 Albumentations class (optional, only used if package is installed) def __init__(self): self.transform = None try:
check_version(A.__version__, '1.0.3', hard=True) # version requirement
1
2023-10-31 06:06:41+00:00
2k
hyw-dev/AFI-ForwardDeduplicate
models/gmflow/matching.py
[ { "identifier": "coords_grid", "path": "models/gmflow/geometry.py", "snippet": "def coords_grid(b, h, w, homogeneous=False, device=None, dtype: torch.dtype=torch.float32):\r\n k = (str(device), str((b, h, w)))\r\n if k in coords_grid_cache:\r\n return coords_grid_cache[k]\r\n y, x = torc...
import torch import torch.nn.functional as F from models.gmflow.geometry import coords_grid, generate_window_grid, normalize_coords
767
def global_correlation_softmax(feature0, feature1, pred_bidir_flow=False, ): # global correlation b, c, h, w = feature0.shape feature0 = feature0.view(b, c, -1).permute(0, 2, 1) # [B, H*W, C] feature1 = feature1.view(b, c, -1) #...
def global_correlation_softmax(feature0, feature1, pred_bidir_flow=False, ): # global correlation b, c, h, w = feature0.shape feature0 = feature0.view(b, c, -1).permute(0, 2, 1) # [B, H*W, C] feature1 = feature1.view(b, c, -1) #...
init_grid = coords_grid(b, h, w, device=correlation.device, dtype=feature0.dtype) # [B, 2, H, W]
0
2023-10-29 18:25:36+00:00
2k
bmrussell/LGBattery
device.py
[ { "identifier": "Shared", "path": "globals.py", "snippet": "class Shared:\n \"\"\"_Configuration_\n\n Args:\n Singleton class for application configuration\n \"\"\"\n\n appname = 'lgbattery'\n quit_selected = False\n datadir = f'{os.getenv(\"APPDATA\")}\\\\{app...
import asyncio import json import logging import websockets from globals import Shared from icons import get_icon
1,575
def get_device_by_id(id): for dev in Shared.devices: if dev.id == id: return dev return None class Device: def __init__(self, id, unitId, name, batteryLevel, charging): self.id = id self.unitId = unitId self.name = name self.batteryLevel = batteryLeve...
def get_device_by_id(id): for dev in Shared.devices: if dev.id == id: return dev return None class Device: def __init__(self, id, unitId, name, batteryLevel, charging): self.id = id self.unitId = unitId self.name = name self.batteryLevel = batteryLeve...
icon = get_icon(self.batteryLevel)
1
2023-10-25 20:37:43+00:00
2k
Kiteretsu77/VCISR-official
degradation/ESR/usm_sharp.py
[ { "identifier": "filter2D", "path": "degradation/ESR/utils.py", "snippet": "def filter2D(img, kernel):\n \"\"\"PyTorch version of cv2.filter2D\n\n Args:\n img (Tensor): (b, c, h, w)\n kernel (Tensor): (b, k, k)\n \"\"\"\n k = kernel.size(-1)\n b, c, h, w = img.size()\n if...
import cv2 import numpy as np import torch import os, sys from torch.nn import functional as F from degradation.ESR.utils import filter2D, np2tensor, tensor2np
948
# -*- coding: utf-8 -*- root_path = os.path.abspath('.') sys.path.append(root_path) def usm_sharp_func(img, weight=0.5, radius=50, threshold=10): """USM sharpening. Input image: I; Blurry image: B. 1. sharp = I + weight * (I - B) 2. Mask = 1 if abs(I - B) > threshold, else: 0 3. Blur mask: ...
# -*- coding: utf-8 -*- root_path = os.path.abspath('.') sys.path.append(root_path) def usm_sharp_func(img, weight=0.5, radius=50, threshold=10): """USM sharpening. Input image: I; Blurry image: B. 1. sharp = I + weight * (I - B) 2. Mask = 1 if abs(I - B) > threshold, else: 0 3. Blur mask: ...
img = np2tensor(img)
1
2023-10-29 04:33:38+00:00
2k
serengil/LightPHE
lightphe/models/Tensor.py
[ { "identifier": "Homomorphic", "path": "lightphe/models/Homomorphic.py", "snippet": "class Homomorphic(ABC):\n keys: dict\n plaintext_modulo: int\n ciphertext_modulo: int\n\n @abstractmethod\n def generate_keys(self, key_size: int, s: Optional[int] = None) -> dict:\n pass\n\n @a...
from typing import Union, List from lightphe.models.Homomorphic import Homomorphic from lightphe.commons import phe_utils
674
# pylint: disable=too-few-public-methods, no-else-return class Fraction: """ Class to store fractional values """ def __init__( self, dividend: Union[int, tuple, list], abs_dividend: Union[int, tuple, list], divisor: Union[int, tuple, list], sign: int = 1, ...
# pylint: disable=too-few-public-methods, no-else-return class Fraction: """ Class to store fractional values """ def __init__( self, dividend: Union[int, tuple, list], abs_dividend: Union[int, tuple, list], divisor: Union[int, tuple, list], sign: int = 1, ...
def __init__(self, fractions: List[Fraction], cs: Homomorphic):
0
2023-10-28 14:57:59+00:00
2k
DataCanvasIO/LMS
lms/runtime/prune/llm_pruner/LLMPruner/peft/utils/save_and_load.py
[ { "identifier": "PeftType", "path": "lms/runtime/prune/llm_pruner/LLMPruner/peft/utils/config.py", "snippet": "class PeftType(str, enum.Enum):\n PROMPT_TUNING = \"PROMPT_TUNING\"\n P_TUNING = \"P_TUNING\"\n PREFIX_TUNING = \"PREFIX_TUNING\"\n LORA = \"LORA\"\n ADALORA = \"ADALORA\"" }, ...
from .config import PeftType, PromptLearningConfig
732
# coding=utf-8 # Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
# coding=utf-8 # Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
if config.peft_type in (PeftType.LORA, PeftType.ADALORA):
0
2023-10-30 10:50:32+00:00
2k
imhotep/hass-unifi-access
custom_components/unifi_access/hub.py
[ { "identifier": "DEVICE_NOTIFICATIONS_URL", "path": "custom_components/unifi_access/const.py", "snippet": "DEVICE_NOTIFICATIONS_URL = \"/api/v1/developer/devices/notifications\"" }, { "identifier": "DOOR_UNLOCK_URL", "path": "custom_components/unifi_access/const.py", "snippet": "DOOR_UNL...
import asyncio import json import logging import ssl import urllib3 import websocket from datetime import timedelta from threading import Thread from urllib.parse import urlparse from requests import request from requests.exceptions import ConnectionError as ConnError, SSLError from homeassistant.core import HomeAssist...
1,326
"""Unifi Access Hub. This module interacts with the Unifi Access API server. """ _LOGGER = logging.getLogger(__name__) class ApiAuthError(Exception): """Raised when we can't authenticate with the API Token.""" class ApiError(Exception): """Raised when we have some trouble using the API.""" class Unif...
"""Unifi Access Hub. This module interacts with the Unifi Access API server. """ _LOGGER = logging.getLogger(__name__) class ApiAuthError(Exception): """Raised when we can't authenticate with the API Token.""" class ApiError(Exception): """Raised when we have some trouble using the API.""" class Unif...
data = self._make_http_request(f"{self.host}{DOORS_URL}")
2
2023-10-27 20:34:27+00:00
2k
aws-samples/amazon-bedrock-serverless-prompt-chaining
stacks/trip_planner_stack.py
[ { "identifier": "get_lambda_bundling_options", "path": "stacks/util.py", "snippet": "def get_lambda_bundling_options():\n return lambda_python.BundlingOptions(\n asset_excludes=[\".venv\", \".mypy_cache\", \"__pycache__\"],\n command_hooks=CommandHooks(),\n )" }, { "identifie...
from aws_cdk import ( Duration, Stack, RemovalPolicy, aws_lambda as lambda_, aws_lambda_python_alpha as lambda_python, aws_s3 as s3, aws_ssm as ssm, aws_stepfunctions as sfn, aws_stepfunctions_tasks as tasks, ) from constructs import Construct from .util import ( get_lambda_bundl...
692
class TripPlannerStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Agent #1: suggest places to stay
class TripPlannerStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Agent #1: suggest places to stay
hotels_job = get_claude_instant_invoke_chain(
1
2023-10-26 22:17:30+00:00
2k
pengsongyou/lseg_feature_extraction
modules/models/lseg_blocks.py
[ { "identifier": "_make_pretrained_clip_vitl16_384", "path": "modules/models/lseg_vit.py", "snippet": "def _make_pretrained_clip_vitl16_384(\n pretrained, use_readout=\"ignore\", hooks=None, enable_attention_hooks=False\n):\n clip_pretrained, _ = clip.load(\"ViT-B/32\", device='cuda', jit=False)\n ...
import torch import torch.nn as nn from .lseg_vit import ( _make_pretrained_clip_vitl16_384, _make_pretrained_clip_vitb32_384, _make_pretrained_clipRN50x16_vitl16_384, forward_vit, )
1,199
def _make_encoder( backbone, features, use_pretrained=True, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore", enable_attention_hooks=False, ): if backbone == "clip_vitl16_384":
def _make_encoder( backbone, features, use_pretrained=True, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore", enable_attention_hooks=False, ): if backbone == "clip_vitl16_384":
clip_pretrained, pretrained = _make_pretrained_clip_vitl16_384(
0
2023-10-27 15:40:36+00:00
2k
chenran-li/RQL-release
rl_zoo3/plots/plot_train.py
[ { "identifier": "LoadMonitorResultsError", "path": "stable_baselines3/common/monitor.py", "snippet": "class LoadMonitorResultsError(Exception):\n \"\"\"\n Raised when loading the monitor log fails.\n \"\"\"\n\n pass" }, { "identifier": "load_results", "path": "stable_baselines3/c...
import argparse import os import numpy as np import seaborn from matplotlib import pyplot as plt from stable_baselines3.common.monitor import LoadMonitorResultsError, load_results from stable_baselines3.common.results_plotter import X_EPISODES, X_TIMESTEPS, X_WALLTIME, ts2xy, window_func
1,247
""" Plot training reward/success rate """ # Activate seaborn seaborn.set() def plot_train(): parser = argparse.ArgumentParser("Gather results, plot training reward/success") parser.add_argument("-a", "--algo", help="Algorithm to include", type=str, required=True) parser.add_argument("-e", "--env", help=...
""" Plot training reward/success rate """ # Activate seaborn seaborn.set() def plot_train(): parser = argparse.ArgumentParser("Gather results, plot training reward/success") parser.add_argument("-a", "--algo", help="Algorithm to include", type=str, required=True) parser.add_argument("-e", "--env", help=...
"steps": X_TIMESTEPS,
3
2023-10-28 01:09:21+00:00
2k
AmgdGocha/DriveFS-Sleuth
drivefs_sleuth/tasks.py
[ { "identifier": "copy_file", "path": "drivefs_sleuth/utils.py", "snippet": "def copy_file(file_path, dest_filename, recovery_path=''):\n if not recovery_path:\n recovery_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'recovered_items')\n\n if not os.path.exists(recovery_pat...
import os import csv from jinja2 import Environment from jinja2 import FileSystemLoader from drivefs_sleuth.utils import copy_file from drivefs_sleuth.utils import lookup_account_id from drivefs_sleuth.utils import get_properties_list from drivefs_sleuth.utils import get_account_properties from drivefs_sleuth.utils imp...
1,505
def get_accounts(drivefs_path): accounts = {} experiments_ids = get_experiment_account_ids(drivefs_path) profiles = get_available_profiles(drivefs_path) available_accounts = set(experiments_ids + profiles) for account_id in available_accounts: accounts[account_id] = { 'email...
def get_accounts(drivefs_path): accounts = {} experiments_ids = get_experiment_account_ids(drivefs_path) profiles = get_available_profiles(drivefs_path) available_accounts = set(experiments_ids + profiles) for account_id in available_accounts: accounts[account_id] = { 'email...
for prop in get_properties_list(os.path.join(setup.get_drivefs_path(), account.get_account_id())):
2
2023-10-29 11:05:04+00:00
2k
zyang1580/CoLLM
minigpt4/datasets/builders/rec_base_dataset_builder.py
[ { "identifier": "is_dist_avail_and_initialized", "path": "minigpt4/common/dist_utils.py", "snippet": "def is_dist_avail_and_initialized():\n if not dist.is_available():\n return False\n if not dist.is_initialized():\n return False\n return True" }, { "identifier": "is_main...
import logging import os import shutil import warnings import torch.distributed as dist import minigpt4.common.utils as utils from omegaconf import OmegaConf from torchvision.datasets.utils import download_url from minigpt4.common.dist_utils import is_dist_avail_and_initialized, is_main_process from minigpt4.common.reg...
799
""" This file is from Copyright (c) 2022, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ class RecBaseDatasetBuilder: train_dataset_cls, eval_dataset_cls...
""" This file is from Copyright (c) 2022, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ class RecBaseDatasetBuilder: train_dataset_cls, eval_dataset_cls...
if is_main_process():
1
2023-10-29 12:47:25+00:00
2k
naver/bq-nco
learning/op/traj_learner.py
[ { "identifier": "decode", "path": "learning/op/decoding.py", "snippet": "def decode(node_coords: Tensor, node_values: Tensor, upper_bounds: Tensor, dist_matrices: Tensor, net: Module,\n beam_size: int, knns: int) -> Tensor:\n if beam_size == 1:\n tours, collected_rewards = greedy_dec...
import time import torch from torch import nn from learning.op.decoding import decode from utils.misc import do_lr_decay, EpochMetrics
791
""" BQ-NCO Copyright (c) 2023-present NAVER Corp. Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license """ DEBUG_NUM_BATCHES = 3 class TrajectoryLearner: def __init__(self, args, net, module, device, data_iterator, optimizer=None, checkpointer=None): # same supervisor is used for training a...
""" BQ-NCO Copyright (c) 2023-present NAVER Corp. Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license """ DEBUG_NUM_BATCHES = 3 class TrajectoryLearner: def __init__(self, args, net, module, device, data_iterator, optimizer=None, checkpointer=None): # same supervisor is used for training a...
epoch_metrics_train = EpochMetrics()
2
2023-10-27 09:08:45+00:00
2k
coder-pig/YuQueBackups
app.py
[ { "identifier": "init_token", "path": "yuque_doc_backups.py", "snippet": "def is_dir_existed(file_path, mkdir=True):\ndef write_text_to_file(content, file_path, mode=\"w+\"):\ndef scan_file_list_by_suffix(file_dir=os.getcwd(), suffix=\"\"):\n def __init__(self, repo_id, repo_type, repo_slug, repo_nam...
from yuque_doc_backups import init_token, fetch_user_id, fetch_repo_list, fetch_toc_list, doc_count from yeque_md_to_local import search_all_file, md_to_local, pic_url_path_record_list, download_pic import asyncio import time
685
# -*- coding: utf-8 -*- # !/usr/bin/env python """ ------------------------------------------------- File : app.py Author : CoderPig date : 2023-10-26 14:57 Desc : 语雀备份脚本-入口 ------------------------------------------------- """ if __name__ == '__main__': yq_token = input("请输入你的语雀Token:") ...
# -*- coding: utf-8 -*- # !/usr/bin/env python """ ------------------------------------------------- File : app.py Author : CoderPig date : 2023-10-26 14:57 Desc : 语雀备份脚本-入口 ------------------------------------------------- """ if __name__ == '__main__': yq_token = input("请输入你的语雀Token:") ...
md_to_local(yq_doc_file_list)
1
2023-10-26 08:35:04+00:00
2k
tobagin/whakarere
whakarere/pages/whatsapp.py
[ { "identifier": "ChatItem", "path": "whakarere/types/chat.py", "snippet": "class ChatItem(GObject.Object):\n chat_id = GObject.Property(type=str)\n chat_name = GObject.Property(type=str)\n chat_picture = GObject.Property(type=Gdk.Texture)\n last_message_body = GObject.Property(type=str)\n ...
import gi import base64, requests, threading from whakarere.types.chat import ChatItem from whakarere.widgets.titlebar import WindowTitlebarWidget from whakarere.widgets.main_menu import MainMenuButtonWidget from gi.repository import Gtk, Adw, GLib, Gio, GdkPixbuf, Pango, Gdk, GObject from datetime import datetime
1,319
gi.require_version("Gtk", "4.0") gi.require_version("Adw", "1") gi.require_version("GdkPixbuf", "2.0") class WhatsappMessengerPage(Adw.NavigationPage): def __init__(self, app_manager, session_id): super().__init__() self.set_title("Whakarere") self.app_manager = app_manager self.se...
gi.require_version("Gtk", "4.0") gi.require_version("Adw", "1") gi.require_version("GdkPixbuf", "2.0") class WhatsappMessengerPage(Adw.NavigationPage): def __init__(self, app_manager, session_id): super().__init__() self.set_title("Whakarere") self.app_manager = app_manager self.se...
self.window_titlebar_widget = WindowTitlebarWidget()
1
2023-10-29 15:46:50+00:00
2k
Agricultural-Robotics-Bonn/pagnerf
loss/lin_assignment_things.py
[ { "identifier": "centers_from_3d_points_with_ids", "path": "utils/outlier_rejection.py", "snippet": "def centers_from_3d_points_with_ids(points):\n # points: [N,[x,y,z,ID]]\n # return: [I,[x,y,z,ID]]\n # K: number of unique IDs\n # [K,[x,y,z,ID]]: centers of the points with t...
import numpy as np import torch import scipy import torch.nn.functional as F from torch import nn from utils.outlier_rejection import centers_from_3d_points_with_ids, add_position_id_range_cost
1,485
# from panoptic lifting implementation # #https://github.com/nihalsid/panoptic-lifting/blob/7af7a3e8477ead8e57f699a240d993e3bc21ee42/trainer/train_panopli_tensorf.py#L195-L206 class LinAssignmentThingsLoss(nn.Module): def __init__(self, outlier_rejection=False, min_distance=0.2, max_distance=0.5, *args, **kwargs...
# from panoptic lifting implementation # #https://github.com/nihalsid/panoptic-lifting/blob/7af7a3e8477ead8e57f699a240d993e3bc21ee42/trainer/train_panopli_tensorf.py#L195-L206 class LinAssignmentThingsLoss(nn.Module): def __init__(self, outlier_rejection=False, min_distance=0.2, max_distance=0.5, *args, **kwargs...
cost_matrix = add_position_id_range_cost(cost_matrix, current_inst_centers)
1
2023-10-30 16:14:39+00:00
2k
John-WL/sd-webui-inpaint-difference
lib_inpaint_difference/webui_hijacks.py
[ { "identifier": "DifferenceGlobals", "path": "lib_inpaint_difference/globals.py", "snippet": "class DifferenceGlobals:\n tab_index = None\n\n base_image = None\n altered_image = None\n generated_mask = None\n\n is_extension_enabled = opts.data.get('inpaint_difference_enabled', True)\n ...
import gradio as gr from modules import img2img, ui_loadsave from lib_inpaint_difference.globals import DifferenceGlobals from lib_inpaint_difference.one_time_callable import one_time_callable from lib_inpaint_difference.img2img_tab_extender import Img2imgTabExtender
1,429
@one_time_callable def hijack_img2img_processing(): original_img2img_processing = img2img.img2img def hijack_func(id_task: str, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint, ...
@one_time_callable def hijack_img2img_processing(): original_img2img_processing = img2img.img2img def hijack_func(id_task: str, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint, ...
if mode == DifferenceGlobals.tab_index:
0
2023-10-30 16:17:34+00:00
2k
BIT-DA/Annotator
tools/utils/train_utils.py
[ { "identifier": "common_utils", "path": "tools/utils/common/common_utils.py", "snippet": "def check_numpy_to_torch(x):\ndef limit_period(val, offset=0.5, period=np.pi):\ndef drop_info_with_name(info, name):\ndef rotate_points_along_z(points, angle):\ndef mask_points_by_range(points, limit_range):\ndef g...
import glob import os import torch import tqdm import time import pcdet from torch.nn.utils import clip_grad_norm_ from tools.utils.common import common_utils, commu_utils
756
def train_one_epoch(model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg, rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False): if total_it_each_epoch == len(train_loader): dataloader_iter = iter(train_loader) if rank =...
def train_one_epoch(model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg, rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False): if total_it_each_epoch == len(train_loader): dataloader_iter = iter(train_loader) if rank =...
avg_data_time = commu_utils.average_reduce_value(cur_data_time)
1
2023-10-31 08:11:57+00:00
2k
hl123-123/yiyan-ppt
gradio_test.py
[ { "identifier": "yiyan_api", "path": "yiyan.py", "snippet": "def yiyan_api(message,access_token,use4=False):\n if use4:\n url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=\" + access_token\n else:\n url = \"https://aip.baidubce.co...
import gradio as gr import gradio as gr import os import time import random import structure_article import shutil from yiyan import yiyan_api, get_access_token from mdtree import tree2ppt from PIL import Image
953
# def image_mod(): # return Image.open("pptx_static/static/img.png") def save_knowledge_func(task_name,knowledge_content,mode,sub_num): time1= time.time() sub_num = int(sub_num) rand_seed = str(random.randint(0,10000000000000000000000000000000000000000000000000000)) character_a = "你是一个精通各方面知识的人" ...
# def image_mod(): # return Image.open("pptx_static/static/img.png") def save_knowledge_func(task_name,knowledge_content,mode,sub_num): time1= time.time() sub_num = int(sub_num) rand_seed = str(random.randint(0,10000000000000000000000000000000000000000000000000000)) character_a = "你是一个精通各方面知识的人" ...
tree2ppt.Tree2PPT(content,"./my_ppt_mode/"+str(int(mode)),save_path=save_path)
2
2023-10-29 15:10:06+00:00
2k
thoddnn/open-datagen
opendatagen/anonymizer.py
[ { "identifier": "OpenAIChatModel", "path": "opendatagen/model.py", "snippet": "class OpenAIChatModel(BaseModel):\n\n name:str = \"gpt-3.5-turbo-1106\"\n system_prompt:Optional[str] = \"No verbose.\"\n max_tokens:Optional[int] = 256\n temperature:Optional[List[float]] = [1]\n json_mode:Opt...
import re import spacy from opendatagen.model import OpenAIChatModel, ModelName from opendatagen.utils import load_file
1,575
class Anonymizer: NER_PLACEHOLDER = { "PERSON": "{person}", "ORG": "{organization}", "GPE": "{location}", "DATE": "{date}", "TIME": "{time}", "NORP": "{group}", "FAC": "{facility}", "LOC": "{location}", "PRODUCT": "{product}", "EVENT"...
class Anonymizer: NER_PLACEHOLDER = { "PERSON": "{person}", "ORG": "{organization}", "GPE": "{location}", "DATE": "{date}", "TIME": "{time}", "NORP": "{group}", "FAC": "{facility}", "LOC": "{location}", "PRODUCT": "{product}", "EVENT"...
def __init__(self, completion_model:OpenAIChatModel):
0
2023-10-27 17:38:37+00:00
2k
HAMNET-AI/PDFTriage
src/routers.py
[ { "identifier": "fetch_figure", "path": "src/triage.py", "snippet": "def fetch_figure(query):\n query_prompt = f\"What contents mentioned in the figure of this pdf\"\n path = query_engine.query(query_prompt).metadata['json_path_response_str'].replace(\"&&\", \"&\")\n jsonpath_expression = parse...
from llama_index.tools import ToolMetadata from llama_index.selectors.llm_selectors import LLMSingleSelector from .triage import fetch_figure, fetch_pages, fetch_sections, fetch_table, retrieve
884
def router(query): choices = [ ToolMetadata(description="Get the text contained in the pages listed", name="fetch_pages"), ToolMetadata(description="Get the text contained in the section listed", name="fetch_sections"), ToolMetadata(description="Get the text contained in the figure caption...
def router(query): choices = [ ToolMetadata(description="Get the text contained in the pages listed", name="fetch_pages"), ToolMetadata(description="Get the text contained in the section listed", name="fetch_sections"), ToolMetadata(description="Get the text contained in the figure caption...
content = fetch_pages(query=query)
1
2023-10-30 14:36:23+00:00
2k
zhanggang001/HEDNet
pcdet/models/backbones_3d/vfe/dynamic_voxel_vfe.py
[ { "identifier": "VFETemplate", "path": "pcdet/models/backbones_3d/vfe/vfe_template.py", "snippet": "class VFETemplate(nn.Module):\n def __init__(self, model_cfg, **kwargs):\n super().__init__()\n self.model_cfg = model_cfg\n\n def get_output_feature_dim(self):\n raise NotImple...
import torch import torch.nn as nn import torch.nn.functional as F import torch_scatter from .vfe_template import VFETemplate from .dynamic_pillar_vfe import PFNLayerV2
746
try: except Exception as e: # Incase someone doesn't want to use dynamic pillar vfe and hasn't installed torch_scatter pass class DynamicVoxelVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, voxel_size, grid_size, point_cloud_range, **kwargs): super().__init__(model_cfg=model_...
try: except Exception as e: # Incase someone doesn't want to use dynamic pillar vfe and hasn't installed torch_scatter pass class DynamicVoxelVFE(VFETemplate): def __init__(self, model_cfg, num_point_features, voxel_size, grid_size, point_cloud_range, **kwargs): super().__init__(model_cfg=model_...
PFNLayerV2(in_filters, out_filters, self.use_norm, last_layer=(i >= len(num_filters) - 2))
1
2023-10-25 02:57:35+00:00
2k
deepsearch-ai/deepsearch
deepsearchai/tests/sources/test_local.py
[ { "identifier": "MEDIA_TYPE", "path": "deepsearchai/enums.py", "snippet": "class MEDIA_TYPE(Enum):\n UNKNOWN = -1\n IMAGE = 1\n TEXT = 2\n AUDIO = 3\n VIDEO = 4" }, { "identifier": "DataSource", "path": "deepsearchai/sources/data_source.py", "snippet": "class DataSource(En...
import unittest import mock.mock from unittest import mock from unittest.mock import patch from deepsearchai.enums import MEDIA_TYPE from deepsearchai.sources.data_source import DataSource from deepsearchai.sources.local import LocalDataSource
862
class LocalDataSourceTest(unittest.TestCase): def setUp(self): self.local_data_source = LocalDataSource() @patch("os.walk") @patch("PIL.Image.open") def test_add_data_image_directory_with_no_existing_files( self, mock_image_file, mock_listdir ): embedding_models_config =...
class LocalDataSourceTest(unittest.TestCase): def setUp(self): self.local_data_source = LocalDataSource() @patch("os.walk") @patch("PIL.Image.open") def test_add_data_image_directory_with_no_existing_files( self, mock_image_file, mock_listdir ): embedding_models_config =...
DataSource.LOCAL,
1
2023-10-27 06:46:22+00:00
2k
jerpint/RAGTheDocs
app.py
[ { "identifier": "embed_documents", "path": "embed_docs.py", "snippet": "def embed_documents(homepage_url, save_directory, target_version=None):\n # adds https:// and trailing slash\n homepage_url = sanitize_url(homepage_url)\n\n # Crawl the website using scrapy\n run_spider(\n homepag...
import os import gradio as gr import pandas as pd import cfg from typing import Optional, Tuple from buster.completers import Completion from embed_docs import embed_documents from cfg import setup_buster
922
# from embed_docs import embed_rtd_website # from rtd_scraper.scrape_rtd import scrape_rtd # Typehint for chatbot history ChatHistory = list[list[Optional[str], Optional[str]]] # Because this is a one-click deploy app, we will be relying on env. variables being set openai_api_key = os.getenv("OPENAI_API_KEY") # M...
# from embed_docs import embed_rtd_website # from rtd_scraper.scrape_rtd import scrape_rtd # Typehint for chatbot history ChatHistory = list[list[Optional[str], Optional[str]]] # Because this is a one-click deploy app, we will be relying on env. variables being set openai_api_key = os.getenv("OPENAI_API_KEY") # M...
embed_documents(
0
2023-10-31 03:36:43+00:00
2k
Paulo-Lopes-Estevao/ci-generator
cigen/core/github/nodejs_action.py
[ { "identifier": "Steps", "path": "cigen/core/github/github_action.py", "snippet": "class Steps:\n def __init__(self, steps: list[dict]) -> None:\n self.steps = steps\n\n def to_dict(self) -> list[dict]:\n return self.steps\n\n def add(self, step: dict) -> None:\n self.steps...
from abc import ABC, abstractmethod from cigen.core.github.github_action import Steps, Action
792
from __future__ import annotations class NodejsActionBuilder(ABC): @property @abstractmethod def build(self) -> Action: pass @property @abstractmethod def build_steps(self) -> NodejsActionSteps: pass @abstractmethod def base(self) -> None: pass @abstra...
from __future__ import annotations class NodejsActionBuilder(ABC): @property @abstractmethod def build(self) -> Action: pass @property @abstractmethod def build_steps(self) -> NodejsActionSteps: pass @abstractmethod def base(self) -> None: pass @abstra...
self.step = Steps([])
0
2023-10-31 03:36:36+00:00
2k
TheCompAce/ShellSpeak
modules/llm.py
[ { "identifier": "get_token_count", "path": "modules/utils.py", "snippet": "def get_token_count(text, token_adjust=1):\n # Define the maximum length for a text chunk\n max_length = 1000000\n\n # Initialize the total token count\n total_token_count = 0\n\n # Split the text into chunks of up...
from enum import Enum from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline from concurrent.futures import ThreadPoolExecutor from modules.utils import get_token_count from modules.responseCache import ResponseCache import json import sqlite3 import os import torch import transformers import requests i...
1,430
transformers.logging.set_verbosity_error() executor = ThreadPoolExecutor() class ModelTypes(Enum): OpenAI = "OpenAI" OpenAI4 = "OpenAI4" Mistral = "Mistral" StableBeluga7B = "StableBeluga7B" Zephyr7bAlpha = "Zephyr7bAlpha" Zephyr7bBeta = "Zephyr7bBeta" Falcon7BInst = "Falcon7BInst" c...
transformers.logging.set_verbosity_error() executor = ThreadPoolExecutor() class ModelTypes(Enum): OpenAI = "OpenAI" OpenAI4 = "OpenAI4" Mistral = "Mistral" StableBeluga7B = "StableBeluga7B" Zephyr7bAlpha = "Zephyr7bAlpha" Zephyr7bBeta = "Zephyr7bBeta" Falcon7BInst = "Falcon7BInst" c...
token_ct = max_tokens - int(get_token_count(system_prompt + "\n" + user_prompt) + 20)
0
2023-10-31 23:35:19+00:00
2k
qym7/SparseDiff
sparse_diffusion/models/transconv_layer.py
[ { "identifier": "SparseXtoy", "path": "sparse_diffusion/models/layers.py", "snippet": "class SparseXtoy(nn.Module):\n def __init__(self, dx, dy):\n \"\"\"Map node features to global features\"\"\"\n super().__init__()\n self.lin = nn.Linear(4 * dx, dy)\n\n def forward(self, X,...
import math import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Union from torch import Tensor from torch_geometric.nn.conv import MessagePassing from torch_geometric.nn.dense.linear import Linear from torch_geometric.typing import Adj, OptTensor, Size from torch_geome...
1,359
class TransformerConv(MessagePassing): r"""The graph transformer operator from the `"Masked Label Prediction: Unified Message Passing Model for Semi-Supervised Classification" <https://arxiv.org/abs/2009.03509>`_ paper .. math:: \mathbf{x}^{\prime}_i = \mathbf{W}_1 \mathbf{x}_i + \s...
class TransformerConv(MessagePassing): r"""The graph transformer operator from the `"Masked Label Prediction: Unified Message Passing Model for Semi-Supervised Classification" <https://arxiv.org/abs/2009.03509>`_ paper .. math:: \mathbf{x}^{\prime}_i = \mathbf{W}_1 \mathbf{x}_i + \s...
self.e_y = SparseEtoy(de, dy)
1
2023-10-30 12:12:16+00:00
2k
ZhangLin-PKU/FedFTG
train.py
[ { "identifier": "util_dataset", "path": "utils/util_dataset.py", "snippet": "COLOR_MAP = ['red', 'green', 'blue', 'black', 'brown', 'purple', 'yellow', 'pink', 'cyan', 'gray']\r\nclass DatasetObject:\r\nclass Dataset(torch.utils.data.Dataset):\r\nclass DatasetFromDir(data.Dataset):\r\n def __init__(s...
from utils import util_dataset, util_parser from models import model_choose_fn from methods import FedAvg, FedProx, SCAFFOLD, MOON, FedDyn from methods import FedFTG, FedProxGAN, SCAFFOLDGAN, MOONGAN, FedDynGAN import torch import os import random import numpy as np import matplotlib.pyplot as plt
1,537
def run(conf): print('Init-------------------------') root_path = os.getcwd() # print(root_path) if root_path.endswith('scripts'): root_path = os.path.dirname(root_path) conf['savepath'] = os.path.join(root_path, conf['savepath'].strip()) print('Data and results save path is...
def run(conf): print('Init-------------------------') root_path = os.getcwd() # print(root_path) if root_path.endswith('scripts'): root_path = os.path.dirname(root_path) conf['savepath'] = os.path.join(root_path, conf['savepath'].strip()) print('Data and results save path is...
data_obj = util_dataset.DatasetObject(dataset=conf['dataset'],
0
2023-10-26 03:35:17+00:00
2k
Shou-Hsu/Report.ai
summarize.py
[ { "identifier": "convert_json", "path": "utils.py", "snippet": "def convert_json(txt:str, item_list:list) -> str:\n txt = txt.replace('\\n', '').replace('#', '')\n\n output = dict()\n for i in range(len(item_list)):\n start = txt.lower().find(item_list[i].lower() + ':')\n\n if i !...
from langchain.chains.combine_documents.stuff import StuffDocumentsChain from utils import convert_json, get_items from langchain.docstore.document import Document from langchain.prompts import PromptTemplate from langchain.chains.llm import LLMChain from tqdm import tqdm from utils import llm from lang...
669
class generate_summary(): def __init__(self, file_name:str, original_language:str, translated_language:str, chunk_size:int, output_dir:str) -> None: self.file_name = file_name self.chunk_size = chunk_size self.original_language = original_language self.translated_language = transla...
class generate_summary(): def __init__(self, file_name:str, original_language:str, translated_language:str, chunk_size:int, output_dir:str) -> None: self.file_name = file_name self.chunk_size = chunk_size self.original_language = original_language self.translated_language = transla...
item_list, items, item_format = get_items('general')
1
2023-10-30 12:29:20+00:00
2k
Thinksy-app/thinksy
app/review_ops.py
[ { "identifier": "SYSTEM_TEXT", "path": "app/env.py", "snippet": "SYSTEM_TEXT = os.environ.get(\"OPENAI_SYSTEM_TEXT\", DEFAULT_SYSTEM_TEXT)" }, { "identifier": "fetch_channel_messages", "path": "app/slack_ops.py", "snippet": "def fetch_channel_messages(\n client: WebClient,\n user: ...
from datetime import datetime from slack_sdk import WebClient from app.env import ( SYSTEM_TEXT, ) from app.slack_ops import fetch_channel_messages, filter_non_membership_and_join from app.openai_ops import make_synchronous_openai_call import json import re
1,105
""" Business logic writing the reviews """ def generate_review(context, user: str, web_client: WebClient, selected_conversations, start_date, end_date, logger): """ Generates the review based on the user's criteria Parameters: user (str): The user ID from Slack slack_enc_team_id (str): ...
""" Business logic writing the reviews """ def generate_review(context, user: str, web_client: WebClient, selected_conversations, start_date, end_date, logger): """ Generates the review based on the user's criteria Parameters: user (str): The user ID from Slack slack_enc_team_id (str): ...
"content": SYSTEM_TEXT
0
2023-10-26 23:47:28+00:00
2k
CrystalWindSnake/nicegui-toolkit
__tests/test_componentStore.py
[ { "identifier": "ComponentStore", "path": "niceguiToolkit/layout/componentStore.py", "snippet": "class ComponentStore:\n def __init__(self) -> None:\n self.cpMapper: Dict[_TNiceguiComponentId, ComponentInfo] = {}\n self._styles_records: Set[_TNiceguiComponentId] = set()\n self._c...
from niceguiToolkit.layout.componentStore import ComponentStore from niceguiToolkit.utils import astCore from .utils import get_data_file
1,464
def test_create_new_style_call(): mock_code_file = get_data_file("code1.py") exp_file = get_data_file("code1_exp.txt") store = ComponentStore()
def test_create_new_style_call(): mock_code_file = get_data_file("code1.py") exp_file = get_data_file("code1_exp.txt") store = ComponentStore()
entry_info = astCore._T_entry_point_info(
1
2023-10-27 13:50:03+00:00
2k
EnVision-Research/Defect_Spectrum
models/stylegan/mapper.py
[ { "identifier": "EqualLinear", "path": "models/stylegan/modules.py", "snippet": "class EqualLinear(nn.Module):\r\n def __init__(\r\n self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None\r\n ):\r\n super().__init__()\r\n\r\n self.weight = nn.Parameter(torch....
from abc import abstractmethod from torch import nn from models.stylegan.modules import EqualLinear, PixelNorm import torch
1,149
STYLESPACE_DIMENSIONS = [512 for _ in range(15)] + [256, 256, 256] + [128, 128, 128] + [64, 64, 64] + [32, 32] class ConcatSquashLinear(nn.Module): def __init__(self, dim_in, dim_out, dim_ctx): super(ConcatSquashLinear, self).__init__() self._layer = EqualLinear(dim_in, dim_out, lr_mul=0.01, acti...
STYLESPACE_DIMENSIONS = [512 for _ in range(15)] + [256, 256, 256] + [128, 128, 128] + [64, 64, 64] + [32, 32] class ConcatSquashLinear(nn.Module): def __init__(self, dim_in, dim_out, dim_ctx): super(ConcatSquashLinear, self).__init__() self._layer = EqualLinear(dim_in, dim_out, lr_mul=0.01, acti...
layers = [PixelNorm()]
1
2023-10-26 10:28:26+00:00
2k
ORI-Muchim/BEGANSing
main.py
[ { "identifier": "update_text_file_in_yaml", "path": "main_util.py", "snippet": "def update_text_file_in_yaml(yaml_path):\n yaml = YAML()\n yaml.preserve_quotes = True\n try:\n with open(yaml_path, 'r', encoding='utf-8') as file:\n data = yaml.load(file)\n\n current_text...
import os import sys import shutil import argparse from main_util import update_text_file_in_yaml, find_index_files from get_models import get_model
1,003
if len(sys.argv) < 4: print("Usage: python main.py <model_name> <song_name> <f0_up_key> [--audiosr]") sys.exit(1) # Init model_name = sys.argv[1] song_name = sys.argv[2] f0_up_key = int(sys.argv[3]) # transpose value input_path = f"../samples/latest_G_{song_name}.wav" output_path = f"../samples/latest_G_{son...
if len(sys.argv) < 4: print("Usage: python main.py <model_name> <song_name> <f0_up_key> [--audiosr]") sys.exit(1) # Init model_name = sys.argv[1] song_name = sys.argv[2] f0_up_key = int(sys.argv[3]) # transpose value input_path = f"../samples/latest_G_{song_name}.wav" output_path = f"../samples/latest_G_{son...
get_model()
2
2023-10-29 09:32:19+00:00
2k
Charl-AI/stochastic-caching
run_benchmark.py
[ { "identifier": "DummyDataset", "path": "benchmark/dataset.py", "snippet": "class DummyDataset(Dataset):\n def __init__(self, data_dir: str, cache_limit_gib: int):\n \"\"\"PyTorch dataset for dummy data.\n No cache is used if cache_limit_gib is 0.\"\"\"\n self.data_dir = data_dir...
import argparse import os import pandas as pd import torch from torch.utils.data import DataLoader from benchmark.dataset import DummyDataset from benchmark.trainer import train
889
parser = argparse.ArgumentParser() parser.add_argument("--seed", type=int, default=42) parser.add_argument("--data-dir", type=str, default="/data2/dummy_data") parser.add_argument("--cache-limit-gib", type=int, default=0) parser.add_argument("--batch-size", type=int, default=256) parser.add_argument("--num-workers",...
parser = argparse.ArgumentParser() parser.add_argument("--seed", type=int, default=42) parser.add_argument("--data-dir", type=str, default="/data2/dummy_data") parser.add_argument("--cache-limit-gib", type=int, default=0) parser.add_argument("--batch-size", type=int, default=256) parser.add_argument("--num-workers",...
dataset = DummyDataset(args.data_dir, args.cache_limit_gib)
0
2023-10-27 09:33:43+00:00
2k
hugoycj/light-hloc
lighthloc/pipeline.py
[ { "identifier": "extract_features", "path": "lighthloc/extract_features.py", "snippet": "def resize_image(image, size, interp):\n def __init__(self, root, conf, paths=None):\n def __getitem__(self, idx):\n def __len__(self):\ndef main(conf: Dict,\n image_dir: Path,\n export_dir:...
from lighthloc import extract_features, match_features, reconstruction from lighthloc.associators import pairs_from_retrieval, pairs_from_exhaustive, pairs_from_sequance from pathlib import Path import click
1,377
# To install hloc, see: https://github.com/cvg/Hierarchical-retrivalization mapper_confs = { 'default' : {}, 'fast' : {'ba_global_max_num_iterations': 20, "ba_global_max_refinements":1, "ba_global_points_freq":200000} } @click.command() @click.option('--data', type=str, help='Path to data direc...
# To install hloc, see: https://github.com/cvg/Hierarchical-retrivalization mapper_confs = { 'default' : {}, 'fast' : {'ba_global_max_num_iterations': 20, "ba_global_max_refinements":1, "ba_global_points_freq":200000} } @click.command() @click.option('--data', type=str, help='Path to data direc...
matcher_conf = match_features.confs[matcher_type]
1
2023-10-27 01:20:50+00:00
2k
KUNLP/XAI_EvidenceExtraction
src/functions/utils.py
[ { "identifier": "SquadV1Processor", "path": "src/functions/processor_sent.py", "snippet": "class SquadV1Processor(SquadProcessor):\r\n train_file = \"train-v1.1.json\"\r\n dev_file = \"dev-v1.1.json\"\r" }, { "identifier": "squad_convert_examples_to_features", "path": "src/functions/pr...
import logging import random import torch import numpy as np import os from src.functions.processor_sent import ( SquadV1Processor, squad_convert_examples_to_features )
1,277
def init_logger(): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(arg...
def init_logger(): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(arg...
processor = SquadV1Processor()
0
2023-10-25 07:03:47+00:00
2k
joenghl/HYPO
hypo/algo/hypo_bc.py
[ { "identifier": "PPOPolicy", "path": "hypo/network/policy.py", "snippet": "class PPOPolicy(nn.Module):\n\n def __init__(self, state_shape, action_shape, hidden_units=(64, 64),\n hidden_activation=nn.Tanh()):\n super().__init__()\n\n self.net = build_mlp(\n inp...
from torch import nn from torch.optim import Adam from hypo.network import PPOPolicy from .base import Algorithm import torch
768
class HBC(Algorithm): def __init__(self, buffer_exp, state_shape, action_shape, device, seed, logger, gamma=0.995, log_interval=1e3, lr_actor=3e-4, batch_size=64, units_actor=(64, 64), **kwargs): super().__init__(state_shape, action_shape, device, seed, logger, gamma) self.buffer...
class HBC(Algorithm): def __init__(self, buffer_exp, state_shape, action_shape, device, seed, logger, gamma=0.995, log_interval=1e3, lr_actor=3e-4, batch_size=64, units_actor=(64, 64), **kwargs): super().__init__(state_shape, action_shape, device, seed, logger, gamma) self.buffer...
self.actor = PPOPolicy(
0
2023-10-27 10:37:44+00:00
2k
jmcruvellier/little_monkey
custom_components/little_monkey/sensor.py
[ { "identifier": "EcojokoEntity", "path": "custom_components/little_monkey/entity.py", "snippet": "class EcojokoEntity(CoordinatorEntity):\n \"\"\"EcojokoEntity class.\"\"\"\n\n _attr_attribution = ATTRIBUTION\n\n def __init__(self, coordinator, device_name, firmware_version):\n \"\"\"Ini...
from homeassistant.components.sensor import ( SensorStateClass, SensorDeviceClass, ) from homeassistant.const import UnitOfPower, UnitOfEnergy, UnitOfTemperature, PERCENTAGE, CONF_NAME from custom_components.little_monkey.entity import EcojokoEntity, EcojokoSensor from .const import ( DOMAIN, CONF_USE_H...
1,325
"""Sensor platform for mon_ecojoko.""" from __future__ import annotations async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the custom component sensors.""" # Fetch data or configure your sensors here coordinator = hass.data[DOMAIN][config_entry.entry_id] # Create the ma...
"""Sensor platform for mon_ecojoko.""" from __future__ import annotations async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the custom component sensors.""" # Fetch data or configure your sensors here coordinator = hass.data[DOMAIN][config_entry.entry_id] # Create the ma...
main_device.add_child_entity(EcojokoSensor(
1
2023-10-29 21:03:13+00:00
2k
stanleylsx/text_embedding
engines/predict.py
[ { "identifier": "configure", "path": "config.py", "snippet": "" }, { "identifier": "Model", "path": "engines/model.py", "snippet": "class Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.model_type = configure['model_type']\n se...
from config import configure from engines.model import Model from engines.utils.metrics import MyModel from torch.utils.data import DataLoader from mteb import MTEB import pandas as pd import torch import os
837
# -*- coding: utf-8 -*- # @Time : 2023/10/27 22:05 # @Author : lishouxian # @Email : gzlishouxian@gmail.com # @File : predict.py # @Software: VSCode class Predictor: def __init__(self, data_manage, device, logger): self.logger = logger self.data_manage = data_manage self.device = device ...
# -*- coding: utf-8 -*- # @Time : 2023/10/27 22:05 # @Author : lishouxian # @Email : gzlishouxian@gmail.com # @File : predict.py # @Software: VSCode class Predictor: def __init__(self, data_manage, device, logger): self.logger = logger self.data_manage = data_manage self.device = device ...
self.model = Model().to(device)
1
2023-10-27 07:47:02+00:00
2k
akekic/causal-component-analysis
data_generator/mixing_function.py
[ { "identifier": "leaky_tanh", "path": "data_generator/utils.py", "snippet": "def leaky_tanh(x: Tensor, alpha: float = 1.0, beta: float = 0.1) -> Tensor:\n return torch.tanh(alpha * x) + beta * x" }, { "identifier": "sample_invertible_matrix", "path": "data_generator/utils.py", "snippe...
from abc import ABC from pathlib import Path from torch import Tensor from .utils import leaky_tanh, sample_invertible_matrix import pandas as pd import torch
1,048
""" def __init__(self, latent_dim: int, observation_dim: int) -> None: self.latent_dim = latent_dim self.observation_dim = observation_dim def __call__(self, v: Tensor) -> Tensor: """ Apply the mixing function to the latent variables. Parameters ---------- ...
class MixingFunction(ABC): """ Base class for mixing functions. The mixing function is the function that maps from the latent space to the observation space. Parameters ---------- latent_dim: int Dimension of the latent space. observation_dim: int Dimension of the obser...
nonlinearities.append(leaky_tanh)
0
2023-10-25 09:25:26+00:00
2k
facebookresearch/verde
src/generate/export.py
[ { "identifier": "to_cuda", "path": "src/utils.py", "snippet": "def to_cuda(*args):\n \"\"\"\n Move tensors to CUDA.\n \"\"\"\n if not CUDA:\n return args\n return [None if x is None else x.cuda() for x in args]" }, { "identifier": "timeout", "path": "src/utils.py", ...
import os import io import sys import ast import time import numpy as np import torch from logging import getLogger from collections import OrderedDict from torch import nn from ..utils import to_cuda, timeout, TimeoutError
1,067
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. logger = getLogger() class Generator(object): def __init__(self, params, gen): """ Initialize t...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. logger = getLogger() class Generator(object): def __init__(self, params, gen): """ Initialize t...
except TimeoutError:
2
2023-10-30 17:53:57+00:00
2k
Paiman-Rasoli/flatway
src/tests/test_flatten.py
[ { "identifier": "mock_list_with_deep_one", "path": "src/tests/fixtures.py", "snippet": "@pytest.fixture\ndef mock_list_with_deep_one():\n return [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12]" }, { "identifier": "mock_list_with_deep_five", "path": "src/tests/fixtures.py", "snippet": "@pyte...
from flatway.flatten import flatten, flattenDict from .fixtures import (mock_list_with_deep_one, mock_list_with_deep_five, mock_tuple_with_deep_one, mock_tuple_with_deep_five, mock_dictionary_deep_one, mock_dictionary_deep_three)
646
def test_flatten_of_list_with_deep_one(mock_list_with_deep_one): result = flatten(mock_list_with_deep_one) expect = [x for x in range(1, 13)] assert result == expect assert isinstance(result, list)
def test_flatten_of_list_with_deep_one(mock_list_with_deep_one): result = flatten(mock_list_with_deep_one) expect = [x for x in range(1, 13)] assert result == expect assert isinstance(result, list)
def test_flatten_of_list_with_deep_five(mock_list_with_deep_five):
1
2023-10-25 20:47:36+00:00
2k
Muhammadali-Akbarov/aiogram-bot-template
aiogram_bot_template/db/db_api/storages/postgres/storage.py
[ { "identifier": "MultipleQueryResults", "path": "aiogram_bot_template/db/db_api/storages/basestorage/storage.py", "snippet": "class MultipleQueryResults:\n def __init__(self, results: list[typing.Mapping[str, Any]]):\n self._data: list[dict[str, Any]] = [{**i} for i in results]\n\n @propert...
import time import asyncpg import structlog from typing import Any, Optional, TypeVar from ..basestorage.storage import MultipleQueryResults, RawConnection, SingleQueryResult
901
T = TypeVar("T") class PostgresConnection(RawConnection): def __init__( self, connection_poll: asyncpg.Pool, logger: structlog.typing.FilteringBoundLogger, ): self._pool = connection_poll self._logger = logger async def _fetch( self, sql: str, ...
T = TypeVar("T") class PostgresConnection(RawConnection): def __init__( self, connection_poll: asyncpg.Pool, logger: structlog.typing.FilteringBoundLogger, ): self._pool = connection_poll self._logger = logger async def _fetch( self, sql: str, ...
) -> SingleQueryResult:
2
2023-10-28 19:44:58+00:00
2k
Doubling-Open-Source/git_calculator
src/calculators/throughput_calculator.py
[ { "identifier": "git_log", "path": "src/git_ir.py", "snippet": "def git_log():\n def to_obj(line):\n parts = line.split('|', 5)\n parts[3] = parts[3].split() # Multiple parents\n return git_obj.commit(*parts)\n res = [\n to_obj(line)\n for line in git_run('log',...
from datetime import datetime from src.git_ir import git_log, format_git_logs_as_string from collections import defaultdict from io import StringIO from subprocess import run as sp_run import logging
880
# Logging configuration logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ) def extract_commits_and_authors(logs): """ Extract commits and their authors from git logs. Args: logs (list): List of commit logs. Returns: dict...
# Logging configuration logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ) def extract_commits_and_authors(logs): """ Extract commits and their authors from git logs. Args: logs (list): List of commit logs. Returns: dict...
logging.debug('Logs: %s', format_git_logs_as_string(logs))
1
2023-10-28 13:43:03+00:00
2k
sisl/SceneInformer
sceneinformer/model/encoder.py
[ { "identifier": "MLPPointEncoder", "path": "sceneinformer/model/utils.py", "snippet": "class MLPPointEncoder(nn.Module):\n def __init__(self, config):\n super(MLPPointEncoder, self).__init__()\n self.config = config\n in_dim = config['in_dim'] * 11\n out_dim = config['out_...
import torch import torch.nn as nn import torch.nn.functional as F import lightning.pytorch as pl from sceneinformer.model.utils import MLPPointEncoder, PointEncoder, count_parameters
861
class Encoder(pl.LightningModule): def __init__(self, config: dict) -> None: super(Encoder, self).__init__() self.config = config self.hidden_dim = config['d_model'] if 'point_enc' in config.keys(): if config['point_enc'] == 'mlp': self.veh_encoder = ...
class Encoder(pl.LightningModule): def __init__(self, config: dict) -> None: super(Encoder, self).__init__() self.config = config self.hidden_dim = config['d_model'] if 'point_enc' in config.keys(): if config['point_enc'] == 'mlp': self.veh_encoder = ...
self.veh_encoder = PointEncoder(config['vehicle_encoder'])
1
2023-10-31 08:08:26+00:00
2k
LFhase/GALA
drugood/models/algorithms/groupdro.py
[ { "identifier": "BaseAlgorithm", "path": "drugood/models/algorithms/base.py", "snippet": "class BaseAlgorithm(BaseModule, metaclass=ABCMeta):\n def __init__(self, init_cfg=None):\n super(BaseAlgorithm, self).__init__(init_cfg)\n\n @abstractmethod\n def forward_train(self, input, group, *...
import torch import torch_scatter from drugood.models.algorithms.base import BaseAlgorithm from ..builder import MODELS, build_tasker
970
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. @MODELS.register_module() class GroupDRO(BaseAlgorithm): """ Group distributionally robust optimization. Original paper: @inproceedings{sagawa2019distributionally, title={Distributionally robust neural networ...
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. @MODELS.register_module() class GroupDRO(BaseAlgorithm): """ Group distributionally robust optimization. Original paper: @inproceedings{sagawa2019distributionally, title={Distributionally robust neural networ...
self.tasker = build_tasker(tasker)
2
2023-10-30 16:57:56+00:00
2k
Graph-and-Geometric-Learning/D4Explainer
main.py
[ { "identifier": "feature_dict", "path": "constants.py", "snippet": "" }, { "identifier": "get_datasets", "path": "utils/dataset.py", "snippet": "def get_datasets(name, root=\"data/\"):\n \"\"\"\n Get preloaded datasets by name\n :param name: name of the dataset\n :param root:...
import argparse import torch from torch_geometric.loader import DataLoader from constants import feature_dict, task_type, dataset_choices from explainers import * from gnns import * from utils.dataset import get_datasets
1,234
def parse_args(): parser = argparse.ArgumentParser(description="Train explainers") parser.add_argument("--cuda", type=int, default=0, help="GPU device.") parser.add_argument("--root", type=str, default="results/", help="Result directory.") parser.add_argument("--dataset", type=str, default="Tree_Cycl...
def parse_args(): parser = argparse.ArgumentParser(description="Train explainers") parser.add_argument("--cuda", type=int, default=0, help="GPU device.") parser.add_argument("--root", type=str, default="results/", help="Result directory.") parser.add_argument("--dataset", type=str, default="Tree_Cycl...
args.task = task_type[args.dataset]
0
2023-10-28 19:58:40+00:00
2k
p4p1/havoc-reporter
reporter.py
[ { "identifier": "html_panel_mitre", "path": "html_source/mitre.py", "snippet": "" }, { "identifier": "html_panel_vulns", "path": "html_source/vulnerabilities.py", "snippet": "" }, { "identifier": "network_vulns", "path": "vulns/network_vulnerabilities.py", "snippet": "" ...
import havocui import webbrowser import os, sys, html, json from html_source.mitre import html_panel_mitre from html_source.vulnerabilities import html_panel_vulns from mitre.tactics import * from vulns.network_vulnerabilities import network_vulns from vulns.active_directory import active_directory_vulns from...
1,298
#!/usr/bin/env python # -*- coding: utf-8 -*- # Made by papi # Created on: Wen 25 Oct 2023 # reporter.py # Description: # A havoc extention to provide examples for different vulnerabilities that can # be tested on the infected networks and on the infected machines. # Usage: # To use this script save it on y...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Made by papi # Created on: Wen 25 Oct 2023 # reporter.py # Description: # A havoc extention to provide examples for different vulnerabilities that can # be tested on the infected networks and on the infected machines. # Usage: # To use this script save it on y...
tree_display_vulns.setPanel(html_panel_vulns % (title, image, mitre, desc, html.escape(command), external_data))
1
2023-10-25 10:39:20+00:00
2k
amazon-science/adaptive-in-context-learning
MetaICL/utils/download.py
[ { "identifier": "all_settings", "path": "MetaICL/utils/utils.py", "snippet": "def get_checkpoint_id(key):\ndef download_file(_id, dest):" }, { "identifier": "download_file", "path": "MetaICL/utils/utils.py", "snippet": "def download_file(_id, dest):\n if os.path.exists(dest):\n ...
import os import json import argparse import subprocess from .utils import all_settings, all_methods from .utils import download_file, get_checkpoint_id
970
''' script for downloading preprocessed data and trained checkpoints ''' def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--checkpoints", default=False, action="store_true") parser.add_argument("--demo_data", default=False, action="store_true") parser.add_argument("--target_...
''' script for downloading preprocessed data and trained checkpoints ''' def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--checkpoints", default=False, action="store_true") parser.add_argument("--demo_data", default=False, action="store_true") parser.add_argument("--target_...
_, _, _id = get_checkpoint_id(method + "/" + setting)
2
2023-10-30 16:34:21+00:00
2k
endo-yuki-t/MAG
ldm/models/diffusion/ddim.py
[ { "identifier": "make_ddim_sampling_parameters", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ...
import torch import cv2 import matplotlib.pyplot as plt import numpy as np import math from tqdm import tqdm from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor from ldm.diffusion_utils import denoising_step from einops import rearrange, repe...
1,445
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) =...
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
1
2023-10-27 06:56:37+00:00
2k
LibreTranslate/LexiLang
lexilang/utils.py
[ { "identifier": "get_supported_languages", "path": "lexilang/languages.py", "snippet": "def get_supported_languages():\n return {\n 'afrikaans': 'af', \n 'albanian': 'sq', \n 'arabic': 'ar', \n 'bengali': 'bn', \n 'bulgarian': 'bg', \n 'catalan': 'ca', \n ...
import os import pickle from .languages import get_supported_languages, tokenize
647
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) def compile_data(): print("Compiling database...") words = {} langs = get_supported_languages() for name in langs: code = langs[name] with open(os.path.join(root_dir, "dictionaries", f"{name}.txt"), "r", encodin...
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) def compile_data(): print("Compiling database...") words = {} langs = get_supported_languages() for name in langs: code = langs[name] with open(os.path.join(root_dir, "dictionaries", f"{name}.txt"), "r", encodin...
tokens = tokenize(code, l.strip())
1
2023-10-30 13:43:19+00:00
2k
alexeichhorn/typegpt
typegpt/parser.py
[ { "identifier": "LLMOutputFieldMissing", "path": "typegpt/exceptions.py", "snippet": "class LLMOutputFieldMissing(LLMParseException):\n ..." }, { "identifier": "LLMOutputFieldWrongType", "path": "typegpt/exceptions.py", "snippet": "class LLMOutputFieldWrongType(LLMParseException):\n ...
import re from typing import TYPE_CHECKING, Generic, TypeVar from .exceptions import LLMOutputFieldMissing, LLMOutputFieldWrongType from .fields import LLMArrayOutputInfo, LLMFieldInfo, LLMOutputInfo, LLMArrayElementOutputInfo from .utils.utils import symmetric_strip from .utils.type_checker import if_response_...
781
from __future__ import annotations _Output = TypeVar("_Output", bound="BaseLLMResponse | BaseLLMArrayElement") class Parser(Generic[_Output]): def __init__(self, output_type: type[_Output]): self.output_type = output_type self.fields = self.output_type.__fields__.values() def _regex_for_fi...
from __future__ import annotations _Output = TypeVar("_Output", bound="BaseLLMResponse | BaseLLMArrayElement") class Parser(Generic[_Output]): def __init__(self, output_type: type[_Output]): self.output_type = output_type self.fields = self.output_type.__fields__.values() def _regex_for_fi...
if isinstance(field.info, LLMOutputInfo) or isinstance(field.info, LLMArrayElementOutputInfo):
4
2023-10-25 22:17:27+00:00
2k
andriioreshk1118/python-storage-main
tests/system/test_transfer_manager.py
[ { "identifier": "transfer_manager", "path": "google/cloud/storage/transfer_manager.py", "snippet": "TM_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024\nDEFAULT_MAX_WORKERS = 8\nMAX_CRC32C_ZERO_ARRAY_SIZE = 4 * 1024 * 1024\nMETADATA_HEADER_TRANSLATION = {\n \"cacheControl\": \"Cache-Control\",\n \"contentDis...
import tempfile import os import pytest import datetime import gzip from google.cloud.storage import transfer_manager from google.cloud.storage._helpers import _base64_md5hash from google.api_core import exceptions from google.cloud._helpers import UTC
1,412
# coding=utf-8 # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
# coding=utf-8 # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
results = transfer_manager.upload_many(
0
2023-10-31 10:36:21+00:00
2k
TopGuru777/badsecrets
badsecrets/modules/aspnet_viewstate.py
[ { "identifier": "unpad", "path": "badsecrets/helpers.py", "snippet": "def unpad(s):\n return s[: -ord(s[len(s) - 1 :])]" }, { "identifier": "sp800_108_derivekey", "path": "badsecrets/helpers.py", "snippet": "def sp800_108_derivekey(key, label, context, keyLengthInBits):\n lblcnt = ...
import re import hmac import struct import base64 import hashlib import binascii from Crypto.Cipher import AES from Crypto.Cipher import DES from Crypto.Cipher import DES3 from viewstate import ViewState from contextlib import suppress from urllib.parse import urlsplit, urlparse from badsecrets.helpers import unpad, sp...
1,372
class ASPNET_Viewstate(BadsecretsBase): check_secret_args = 3 identify_regex = generic_base64_regex description = {"product": "ASP.NET Viewstate", "secret": "ASP.NET MachineKey", "severity": "CRITICAL"} def carve_regex(self): return re.compile( r"<input.+__VIEWSTATE\"\svalue=\"(.+...
class ASPNET_Viewstate(BadsecretsBase): check_secret_args = 3 identify_regex = generic_base64_regex description = {"product": "ASP.NET Viewstate", "secret": "ASP.NET MachineKey", "severity": "CRITICAL"} def carve_regex(self): return re.compile( r"<input.+__VIEWSTATE\"\svalue=\"(.+...
decrypt = unpad(decrypted_raw)
0
2023-10-30 12:52:39+00:00
2k
asprenger/ray_vllm_inference
tests/prompt_format_test.py
[ { "identifier": "Message", "path": "ray_vllm_inference/prompt_format.py", "snippet": "class Message(BaseModel):\n role: Literal[\"system\", \"assistant\", \"user\"]\n content: str\n\n def __str__(self):\n return self.content" }, { "identifier": "Prompt", "path": "ray_vllm_inf...
import unittest import pytest from pydantic import ValidationError from ray_vllm_inference.prompt_format import Message, Prompt, PromptFormat
1,231
# Adapted from: # https://github.com/ray-project/ray-llm/blob/master/rayllm/common/models.py class PromptFormatCases(unittest.TestCase): def test_prompt_format_with_prompt_obj(self): prompt_format = PromptFormat( system="[system] {instruction} [/system] ", assistant="[assistant] {...
# Adapted from: # https://github.com/ray-project/ray-llm/blob/master/rayllm/common/models.py class PromptFormatCases(unittest.TestCase): def test_prompt_format_with_prompt_obj(self): prompt_format = PromptFormat( system="[system] {instruction} [/system] ", assistant="[assistant] {...
messages = [Message(role="user", content="hello1")]
0
2023-10-28 23:17:59+00:00
2k
fu-feng/GRL
algos/ppo.py
[ { "identifier": "Actor", "path": "algos/network.py", "snippet": "class Actor(Network):\n def __init__(self, layer_num, input_dim, output_dim, hidden_dim, activation_function = torch.tanh,last_activation_mu = None, last_activation_std = None, is_actor=True):\n super(Actor, self).__init__(layer_...
from algos.network import Actor, Critic from utils.utils import ReplayBuffer, make_mini_batch, convert_to_tensor import torch import torch.nn as nn import torch.optim as optim
976
class PPO(nn.Module): def __init__(self, device, state_dim, action_dim, args): super(PPO,self).__init__() self.args = args
class PPO(nn.Module): def __init__(self, device, state_dim, action_dim, args): super(PPO,self).__init__() self.args = args
self.data = ReplayBuffer(action_prob_exist = True, max_size = self.args.traj_length, state_dim = state_dim, num_action = action_dim)
2
2023-10-27 07:39:01+00:00
2k
CoderMungan/Otel
OtelIcerik/forms.py
[ { "identifier": "OtelOda", "path": "OtelIcerik/models.py", "snippet": "class OtelOda(models.Model):\n otel = models.ForeignKey(OtelYonetim, verbose_name=(\"Otel Adı\"), on_delete=models.CASCADE)\n odaNumarasi = models.CharField((\"Oda Numarası\"), max_length=5)\n odaTipi = models.CharField((\"O...
from django import forms from .models import OtelOda, KonukBilgileri, KonukCheckInveCheckOut
957
class UpdateOtelOdaForm(forms.ModelForm): class Meta: model = OtelOda fields = ["odaNumarasi","odaTipi","odaTemizMi","odaArizaliMi","odaBosMu","odaProblemi",] class UpdateMusteriDetay(forms.ModelForm): class Meta:
class UpdateOtelOdaForm(forms.ModelForm): class Meta: model = OtelOda fields = ["odaNumarasi","odaTipi","odaTemizMi","odaArizaliMi","odaBosMu","odaProblemi",] class UpdateMusteriDetay(forms.ModelForm): class Meta:
model = KonukBilgileri
1
2023-10-26 02:42:23+00:00
2k
lukas-clarke/pyEight
pyeight/eight.py
[ { "identifier": "Token", "path": "pyeight/structs.py", "snippet": "class Token:\n bearer_token: str\n expiration: float\n main_id: str" }, { "identifier": "User", "path": "pyeight/structs.py", "snippet": "class User:\n def __init__(self,\n user_name: str,\n ...
import asyncio import time import httpx import atexit import logging from aiohttp.client import ClientError, ClientSession, ClientTimeout from pyeight.constants import * from pyeight.structs import Token, User
793
_LOGGER = logging.getLogger(__name__) CLIENT_TIMEOUT = ClientTimeout(total=DEFAULT_TIMEOUT) class EightSleep(): def __init__( self, email: str, password: str, client_id: str, client_secret: str): self.email = email self.password = passwor...
_LOGGER = logging.getLogger(__name__) CLIENT_TIMEOUT = ClientTimeout(total=DEFAULT_TIMEOUT) class EightSleep(): def __init__( self, email: str, password: str, client_id: str, client_secret: str): self.email = email self.password = passwor...
async def _get_auth(self) -> Token:
0
2023-10-26 21:11:20+00:00
2k
loliverhennigh/PhantomGaze
phantomgaze/render/camera.py
[ { "identifier": "normalize", "path": "phantomgaze/utils/math.py", "snippet": "@cuda.jit(device=True)\ndef normalize(vector):\n \"\"\"Normalize a vector.\n\n Parameters\n ----------\n vector : tuple\n The vector to normalize.\n\n Returns\n -------\n tuple\n The normaliz...
import math import numba from numba import cuda from phantomgaze.utils.math import normalize, dot, cross
773
# Render functions for volumes @cuda.jit(device=True) def calculate_ray_direction( x, y, img_shape, camera_position, camera_focal, camera_up): """ Calculate the direction of a ray from the camera to the image plane. Parameters ---------- x : int ...
# Render functions for volumes @cuda.jit(device=True) def calculate_ray_direction( x, y, img_shape, camera_position, camera_focal, camera_up): """ Calculate the direction of a ray from the camera to the image plane. Parameters ---------- x : int ...
forward = normalize(forward)
0
2023-10-26 23:53:16+00:00
2k
Khushiyant/dockerpulse
dockerpulse/lgbert/bert_pytorch/trainer/pretrain.py
[ { "identifier": "BERT", "path": "dockerpulse/lgbert/bert_pytorch/model/bert.py", "snippet": "class BERT(nn.Module):\r\n \"\"\"\r\n BERT model : Bidirectional Encoder Representations from Transformers.\r\n \"\"\"\r\n\r\n def __init__(self, vocab_size, max_len=512, hidden=768, n_layers=12,\r\n...
import torch import torch.nn as nn import time import tqdm import numpy as np import pandas as pd from torch.optim import Adam from torch.utils.data import DataLoader from ..model import BERTLog, BERT from .optim_schedule import ScheduledOptim
1,287
class BERTTrainer: """ BERTTrainer make the pretrained BERT model with two LM training method. 1. Masked Language Model : 3.3.1 Task #1: Masked LM 2. Next Sentence prediction : 3.3.2 Task #2: Next Sentence Prediction please check the details on README.md with simple example. ...
class BERTTrainer: """ BERTTrainer make the pretrained BERT model with two LM training method. 1. Masked Language Model : 3.3.1 Task #1: Masked LM 2. Next Sentence prediction : 3.3.2 Task #2: Next Sentence Prediction please check the details on README.md with simple example. ...
def __init__(self, bert: BERT, vocab_size: int,
0
2023-10-29 09:52:36+00:00
2k
audiodude/rainfall
rainfall/blueprint/site.py
[ { "identifier": "db", "path": "rainfall/db.py", "snippet": "class Base(DeclarativeBase):" }, { "identifier": "with_current_user", "path": "rainfall/decorators.py", "snippet": "def with_current_user(f):\n '''\n Retrieves the current user from the session, performs some checks, and then\...
from uuid import UUID from rainfall.db import db from rainfall.decorators import with_current_user, with_current_site from rainfall.models.site import Site import flask
944
site = flask.Blueprint('site', __name__) @site.route('/site', methods=['POST']) @with_current_user def create_site(user): if not user.is_welcomed: return flask.jsonify(status=400, error='User has not yet been welcomed'), 400 data = flask.request.get_json() if data is None: r...
site = flask.Blueprint('site', __name__) @site.route('/site', methods=['POST']) @with_current_user def create_site(user): if not user.is_welcomed: return flask.jsonify(status=400, error='User has not yet been welcomed'), 400 data = flask.request.get_json() if data is None: r...
@with_current_site
2
2023-10-30 04:43:03+00:00
2k
LasticXYZ/price-simulation
tests/test_poly.py
[ { "identifier": "Linear", "path": "poly.py", "snippet": "class Linear:\n @staticmethod\n def leadin_factor_at(when, factor = 1):\n \"\"\"\n Factor represents the slope of the linear function\n Factor is not a parameter that is originally used in the `broker pallet code`.\n\n ...
import unittest from poly import Linear, Exponential
653
class TestLinearNoPanic(unittest.TestCase): def test_linear_no_panic(self): for limit in range(10): for target in range(1, 10): for sold in range(limit + 1): price = Linear.adapt_price(sold, target, limit) if sold > target: ...
class TestLinearNoPanic(unittest.TestCase): def test_linear_no_panic(self): for limit in range(10): for target in range(1, 10): for sold in range(limit + 1): price = Linear.adapt_price(sold, target, limit) if sold > target: ...
price = Exponential.adapt_price(sold, target, limit)
1
2023-10-30 12:49:00+00:00
2k
dangeng/flowmag
test_time_adapt.py
[ { "identifier": "TestTimeAdaptDataset", "path": "dataset.py", "snippet": "class TestTimeAdaptDataset(Dataset):\n def __init__(self, root, mode='first', length=None):\n '''\n args:\n root: (string) path to directory of frames\n mode: ['first', 'random'] how to sampl...
from tqdm import tqdm from torch.optim import Adam from torch.utils.data import DataLoader from dataset import TestTimeAdaptDataset from myutils import AverageMeter import torch import matplotlib.pyplot as plt
1,430
def test_time_adapt(model, frames_dir, num_epochs=5, mode='first', device=0, inference_fn=None, inference_freq=1, alpha=None, save_dir=None, dataset_length=None): ''' params: model: (nn.Module) model with checkpoint already loaded frames_dir: (string) path to directory of frames for test tim...
def test_time_adapt(model, frames_dir, num_epochs=5, mode='first', device=0, inference_fn=None, inference_freq=1, alpha=None, save_dir=None, dataset_length=None): ''' params: model: (nn.Module) model with checkpoint already loaded frames_dir: (string) path to directory of frames for test tim...
meter_loss = AverageMeter('loss')
1
2023-10-27 05:23:08+00:00
2k
warner-benjamin/optimi
optimi/adam.py
[ { "identifier": "MIN_TORCH_2_1", "path": "optimi/utils.py", "snippet": "MIN_TORCH_2_1 = parse(torch.__version__) >= parse(\"2.1\")" }, { "identifier": "debias_beta", "path": "optimi/utils.py", "snippet": "def debias_beta(beta: float, step: int) -> float:\n \"\"\"Applies the Adam-style...
from typing import Any, Callable, Iterable from warnings import warn from torch import Tensor from torch.optim.optimizer import Optimizer, _default_to_fused_or_foreach from torch.utils._foreach_utils import _group_tensors_by_device_and_dtype from optimi.utils import MIN_TORCH_2_1, debias_beta import torch
1,021
# Copyright (c) 2023 Benjamin Warner # SPDX-License-Identifier: MIT # Based on PyTorch Optimizers # PyTorch - PyTorch BSD-style license - Copyright (c) 2013-present PyTorch contributors # Kahan summation inspired by Torch Distributed Experimental's `AnyPrecisionAdamW` # torchdistX - BSD 3-Clause License - Copyright (...
# Copyright (c) 2023 Benjamin Warner # SPDX-License-Identifier: MIT # Based on PyTorch Optimizers # PyTorch - PyTorch BSD-style license - Copyright (c) 2013-present PyTorch contributors # Kahan summation inspired by Torch Distributed Experimental's `AnyPrecisionAdamW` # torchdistX - BSD 3-Clause License - Copyright (...
if not MIN_TORCH_2_1:
0
2023-10-25 00:51:05+00:00
2k