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
generative-skill-chaining/gsc-code
generative_skill_chaining/envs/pybullet/table/objects.py
[ { "identifier": "body", "path": "generative_skill_chaining/envs/pybullet/sim/body.py", "snippet": "class Body:\nclass Link:\n def aabb(self) -> np.ndarray:\n def pose(self) -> math.Pose:\n def set_pose(self, pose: math.Pose) -> None:\n def twist(self) -> np.ndarray:\n def dof(self) -> int...
import dataclasses import itertools import random import numpy as np import pybullet as p import spatialdyn as dyn from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Type, Union from ctrlutils import eigen from generative_skill_chaining.envs.pybullet.sim import body, math, shapes from generative_s...
2,762
self.body_id, link_id, 0, 0, physicsClientId=self.physics_id ) def enable_collisions(self) -> None: for link_id in range(self.dof): p.setCollisionFilterGroupMask( self.body_id, link_id, 1, 0xFF, physicsClientId=self.physics_id ) @prop...
OBJECT_HIERARCHY = ["rack", "table", "hook", "box"] def compute_bbox_vertices( bbox: np.ndarray, pose: Optional[math.Pose] = None, project_2d: bool = False ) -> np.ndarray: """Computes the vertices of the given 3D bounding box. Args: bbox: Array of shape [2, 3] (min/max, x/y/z). pose:...
def shapes(self) -> Sequence[shapes.Shape]:
2
2023-10-16 00:22:40+00:00
4k
ChiyuSONG/dynamics-of-instruction-tuning
evaluate/pred.py
[ { "identifier": "Assistant", "path": "inference.py", "snippet": "class Assistant:\n def __init__(self, model_name_or_path):\n tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path)\n tokenizer.padding_side = \"left\"\n tokenizer.user_token_id, tokenizer.assistant_token_id...
import os import sys import torch import json import jsonlines import copy from pathlib import Path from argparse import ArgumentParser from tqdm import tqdm from inference import Assistant from train_sft import IGNORE_INDEX, DataCollatorForSupervisedDataset
1,683
sys.path.append(".") def process(example, tokenizer): processed = [] user = tokenizer.user_token_id assistant = tokenizer.assistant_token_id eot = tokenizer.eot_token_id def tokenize(s): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(s.strip())) for choice in example["cho...
sys.path.append(".") def process(example, tokenizer): processed = [] user = tokenizer.user_token_id assistant = tokenizer.assistant_token_id eot = tokenizer.eot_token_id def tokenize(s): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(s.strip())) for choice in example["cho...
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer, pad_to_multiple_of=8)
2
2023-10-17 07:41:58+00:00
4k
akashgreninja/GreSec
backend/venv/lib/python3.10/site-packages/anyio/_core/_synchronization.py
[ { "identifier": "cancel_shielded_checkpoint", "path": "backend/venv/lib/python3.10/site-packages/anyio/lowlevel.py", "snippet": "async def cancel_shielded_checkpoint() -> None:\n \"\"\"\n Allow the scheduler to switch to another task but without checking for cancellation.\n\n Equivalent to (but...
from collections import deque from dataclasses import dataclass from types import TracebackType from warnings import warn from ..lowlevel import cancel_shielded_checkpoint, checkpoint, checkpoint_if_cancelled from ._compat import DeprecatedAwaitable from ._eventloop import get_asynclib from ._exceptions import BusyReso...
3,299
raise assert self._owner_task == task else: try: await cancel_shielded_checkpoint() except BaseException: self.release() raise def acquire_nowait(self) -> None: """ Acquire the lock, withou...
from __future__ import annotations @dataclass(frozen=True) class EventStatistics: """ :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` """ tasks_waiting: int @dataclass(frozen=True) class CapacityLimiterStatistics: """ :ivar int borrowed_tokens: number of tokens cu...
await checkpoint()
1
2023-10-23 18:09:28+00:00
4k
marmotlab/Context_Aware_Navigation
runner.py
[ { "identifier": "PolicyNet", "path": "model.py", "snippet": "class PolicyNet(nn.Module):\r\n def __init__(self, input_dim, embedding_dim):\r\n super(PolicyNet, self).__init__()\r\n self.initial_embedding = nn.Linear(input_dim, embedding_dim) # layer for non-end position\r\n self....
import torch import ray from model import PolicyNet, QNet from worker import Worker from parameter import *
3,250
class Runner(object): def __init__(self, meta_agent_id): self.meta_agent_id = meta_agent_id self.device = torch.device('cuda') if USE_GPU else torch.device('cpu')
class Runner(object): def __init__(self, meta_agent_id): self.meta_agent_id = meta_agent_id self.device = torch.device('cuda') if USE_GPU else torch.device('cpu')
self.local_network = PolicyNet(INPUT_DIM, EMBEDDING_DIM)
0
2023-10-17 04:32:42+00:00
4k
adarshxs/TokenTally
main.py
[ { "identifier": "sidebar", "path": "sidebar.py", "snippet": "def sidebar():\n with st.sidebar:\n st.image(\"cutie.png\", use_column_width=True)\n st.title(\"About Token Tally\")\n st.info(\"Select your desired base model, parameters, and configuration to get an estimate of the re...
from sidebar import sidebar from overview import display_overview from tools.llm_cost_calculator import display_llm_cost_tool from tools.transformer_memory_calculator import display_transformer_memory_tool from tools.llm_recomender import display_llm_recomender_tool
3,256
def main(): selected_product = sidebar() if selected_product == "Overview": display_overview() elif selected_product == "LLM Cost Tool": display_llm_cost_tool() elif selected_product == "Transformer Memory Tool": display_transformer_memory_tool() elif selected_prod...
def main(): selected_product = sidebar() if selected_product == "Overview": display_overview() elif selected_product == "LLM Cost Tool": display_llm_cost_tool() elif selected_product == "Transformer Memory Tool": display_transformer_memory_tool() elif selected_prod...
display_llm_recomender_tool()
4
2023-10-18 06:16:47+00:00
4k
WestlakeIntelligentRobotics/ConsensusLLM-code
modules/experiment/scalar_debate.py
[ { "identifier": "Template", "path": "modules/experiment/template.py", "snippet": "class Template(ABC):\n \"\"\"\n A template class for designing and running experiments with multiple agents\n and rounds.\n\n This abstract class defines a template for designing experiments where \n multipl...
import numpy as np from concurrent.futures import ThreadPoolExecutor, as_completed from .template import Template from ..llm.agent import Agent, GPT from ..llm.api_key import api_keys from ..llm.role import names from ..prompt.scenario import agent_role, game_description, round_description from ..prompt.form import age...
2,926
""" MIT License Copyright (c) [2023] [Intelligent Unmanned Systems Laboratory at Westlake University] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
""" MIT License Copyright (c) [2023] [Intelligent Unmanned Systems Laboratory at Westlake University] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
self._init_input = game_description + "\n\n" + agent_output_form
4
2023-10-20 07:58:07+00:00
4k
LzVv123456/Contrastive-Prototypical-Prompt
train.py
[ { "identifier": "ProtoDataset", "path": "datasets/proto.py", "snippet": "class ProtoDataset(Dataset):\n def __init__(self, args, prototypes, prototypes_var, classes):\n self.args = args\n self.prototypes = prototypes\n self.prototypes_var = prototypes_var\n self.classes = ...
import torch import utils import copy import losses import prototype as prot from torch import nn from torch.nn import functional as F from torch.utils.data import DataLoader, RandomSampler from tqdm import tqdm from datasets import ProtoDataset from prompt import ProTLearner, PromptHead
2,648
class Trainer(object): def __init__(self, args, vit_model, train_dataset, gen_proto_dataset): super().__init__() self.args = args self.vit_model = vit_model self.dataset = train_dataset self.gen_proto_dataset = gen_proto_dataset self.proto = [] self.proto_v...
class Trainer(object): def __init__(self, args, vit_model, train_dataset, gen_proto_dataset): super().__init__() self.args = args self.vit_model = vit_model self.dataset = train_dataset self.gen_proto_dataset = gen_proto_dataset self.proto = [] self.proto_v...
self.prompter = ProTLearner(self.args, self.vit_model)
1
2023-10-16 21:28:42+00:00
4k
inngest/inngest-py
inngest/_internal/middleware_lib/log.py
[ { "identifier": "client_lib", "path": "inngest/_internal/client_lib.py", "snippet": "_DEV_SERVER_EVENT_KEY = \"NO_EVENT_KEY_SET\"\nclass Inngest:\n def api_origin(self) -> str:\n def event_api_origin(self) -> str:\n def event_key(self) -> str | None:\n def signing_key(self) -> str | None:\n ...
from inngest._internal import client_lib, function, types from .middleware import MiddlewareSync
1,907
from __future__ import annotations class LoggerProxy: _proxied_methods = ( "critical", "debug", "error", "exception", "fatal", "info", "log", "warn", "warning", ) def __init__(self, logger: types.Logger) -> None: self._is_e...
from __future__ import annotations class LoggerProxy: _proxied_methods = ( "critical", "debug", "error", "exception", "fatal", "info", "log", "warn", "warning", ) def __init__(self, logger: types.Logger) -> None: self._is_e...
ctx: function.Context,
1
2023-10-19 01:02:30+00:00
4k
f0uriest/quadax
quadax/romberg.py
[ { "identifier": "QuadratureInfo", "path": "quadax/utils.py", "snippet": "class QuadratureInfo(NamedTuple):\n \"\"\"Information about quadrature.\n\n Parameters\n ----------\n err : float\n Estimate of the error in the quadrature result.\n neval : int\n Number of evaluations ...
import jax import jax.numpy as jnp from .utils import ( QuadratureInfo, bounded_while_loop, errorif, map_interval, tanhsinh_transform, wrap_func, )
2,501
"""Romberg integration aka adaptive trapezoid with Richardson extrapolation.""" def romberg( fun, interval, args=(), full_output=False, epsabs=1.4e-8, epsrel=1.4e-8, divmax=20, norm=jnp.inf, ): """Romberg integration of a callable function or method. Returns the integral of ...
"""Romberg integration aka adaptive trapezoid with Richardson extrapolation.""" def romberg( fun, interval, args=(), full_output=False, epsabs=1.4e-8, epsrel=1.4e-8, divmax=20, norm=jnp.inf, ): """Romberg integration of a callable function or method. Returns the integral of ...
vfunc = wrap_func(fun, args)
5
2023-10-24 04:44:34+00:00
4k
yixinliu233/SIGNET
main.py
[ { "identifier": "GIN", "path": "models.py", "snippet": "class GIN(torch.nn.Module):\n def __init__(self, num_features, dim, num_gc_layers, pooling, readout):\n super(GIN, self).__init__()\n\n self.num_gc_layers = num_gc_layers\n self.pooling = pooling\n self.readout = read...
import torch import numpy as np import torch.nn as nn import random import warnings from sklearn.metrics import roc_auc_score from models import GIN, Explainer_GIN, HyperGNN, Explainer_MLP from arguments import arg_parse from get_data_loaders import get_data_loaders from get_data_loaders_tuad import get_ad_split_TU, ge...
3,513
warnings.filterwarnings("ignore") explainable_datasets = ['mutag', 'mnist0', 'mnist1', 'bm_mn', 'bm_ms', 'bm_mt'] class SIGNET(nn.Module): def __init__(self, input_dim, input_dim_edge, args, device): super(SIGNET, self).__init__() self.device = device self.embedding_dim = args.hidden_...
warnings.filterwarnings("ignore") explainable_datasets = ['mutag', 'mnist0', 'mnist1', 'bm_mn', 'bm_ms', 'bm_mt'] class SIGNET(nn.Module): def __init__(self, input_dim, input_dim_edge, args, device): super(SIGNET, self).__init__() self.device = device self.embedding_dim = args.hidden_...
self.explainer = Explainer_MLP(input_dim, args.explainer_hidden_dim, args.explainer_layers)
3
2023-10-18 04:23:35+00:00
4k
smonsays/metax
metax/data/synthetic.py
[ { "identifier": "DatasetGenerator", "path": "metax/data/dataset/base.py", "snippet": "class DatasetGenerator(abc.ABC):\n \"\"\"\n Abstract base class for generated datasets.\n\n Attributes:\n input_shape (tuple): The shape of the input data.\n output_dim (int): The dimensionality ...
import logging import chex import jax from typing import List, Optional from metax.data.dataset.base import DatasetGenerator from .base import Dataloader, MetaDataset from .dataset import family, sinusoid from .utils import create_metadataset
1,901
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, m...
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, m...
data_generator = sinusoid.Sinusoid()
4
2023-10-19 16:36:20+00:00
4k
claws-lab/XLingEval
correctness/correctness_get_gpt_answer.py
[ { "identifier": "load_HealthQA", "path": "dataloader/load_data.py", "snippet": "def load_HealthQA(split: str, language: str = 'English', task: str = \"consistency\"):\n print(f\"Loading HealthQA with split {split} and Language {language} ...\")\n\n if osp.basename(os.getcwd()) == \"XLingHealth_Dat...
import os import time import traceback import sys import pandas as pd from os import path as osp from dataloader.load_data import load_HealthQA, load_MedicationQA, load_LiveQA from setup import project_setup, openai_setup from utils_chatgpt import get_response from const import set_constants from argparse import Argume...
2,794
llm_answer_list = [] for idx, row in data_df.iterrows(): retry = True if idx%100 == 0: print("Index: ", idx) while retry: try: message_list=[{'role': 'system', 'content': f'You are Health GPT and You answer to heal...
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) def get_eval(data_df, lang, open_ai_object_list, constants): print("Lang: ", lang) model_use_count = 0 model_list_index = 0 llm_answer_list = [] for idx, row in data_df.iterrows(): retry = True if idx%100...
df = load_LiveQA(language=lang, task="correctness")
2
2023-10-18 17:35:42+00:00
4k
RF-Tar-Railt/satori-python
src/satori/model.py
[ { "identifier": "Element", "path": "src/satori/element.py", "snippet": "class Element:\n @classmethod\n def from_raw(cls: Type[TE], raw: RawElement) -> TE:\n _fields = {f.name for f in fields(cls)}\n attrs = {k: v for k, v in raw.attrs.items() if k in _fields}\n result = cls(*...
from dataclasses import asdict, dataclass from datetime import datetime from enum import IntEnum from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar from .element import Element, transform from .parser import parse
2,337
data["user"] = User.parse(raw["user"]) if "joined_at" in raw: data["joined_at"] = datetime.fromtimestamp(int(raw["joined_at"]) / 1000) return cls(**data) def dump(self): res = {} if self.user: res["user"] = self.user.dump() if self.nick or...
class ChannelType(IntEnum): TEXT = 0 VOICE = 1 CATEGORY = 2 DIRECT = 3 @dataclass class Channel: id: str type: ChannelType name: Optional[str] = None parent_id: Optional[str] = None @classmethod def parse(cls, raw: dict): data = raw.copy() data["type"] = Cha...
"content": transform(parse(raw["content"])),
1
2023-10-18 11:09:34+00:00
4k
zju3dv/nr_in_a_room
tools/check_pose.py
[ { "identifier": "create_sphere_lookat_poses", "path": "data_gen/data_geo_utils.py", "snippet": "def create_sphere_lookat_poses(\n radius: float, n_poses: int, n_circles: float, up_dir=\"y\", phi_begin=20, phi_end=90\n):\n deg2rad = np.pi / 180\n # y up\n phi_list = np.linspace(phi_begin * de...
import numpy as np import argparse import sys import os import open3d as o3d import matplotlib.pyplot as plt from data_gen.data_geo_utils import create_sphere_lookat_poses from tools.O3dVisualizer import O3dVisualizer from utils.util import *
2,689
sys.path.append(os.getcwd()) # noqa # from datasets.geo_utils import observe_angle_distance # from render_tools.render_utils import * def spheric_pose(theta, phi, radius, height): trans_t = lambda t: np.array( [ [1, 0, 0, 0], [0, 1, 0, -0.9 * t], [0, 0, 1, t], ...
sys.path.append(os.getcwd()) # noqa # from datasets.geo_utils import observe_angle_distance # from render_tools.render_utils import * def spheric_pose(theta, phi, radius, height): trans_t = lambda t: np.array( [ [1, 0, 0, 0], [0, 1, 0, -0.9 * t], [0, 0, 1, t], ...
visualizer = O3dVisualizer()
1
2023-10-15 08:41:29+00:00
4k
ShramanPramanick/VoLTA
Multimodal_Fine_Grained/maskrcnn_benchmark/modeling/rpn/fcos.py
[ { "identifier": "make_fcos_loss_evaluator", "path": "Multimodal_Fine_Grained/maskrcnn_benchmark/modeling/rpn/loss.py", "snippet": "def make_fcos_loss_evaluator(cfg):\n loss_evaluator = FCOSLossComputation(cfg)\n return loss_evaluator" }, { "identifier": "make_center_anchor_generator", ...
import math import torch import torch.nn.functional as F from torch import nn from maskrcnn_benchmark.modeling import registry from maskrcnn_benchmark.layers import Scale, DFConv2d from .loss import make_fcos_loss_evaluator from .anchor_generator import make_center_anchor_generator from .inference import make_fcos_post...
1,809
@registry.RPN_HEADS.register("FCOSHead") class FCOSHead(torch.nn.Module): def __init__(self, cfg): super(FCOSHead, self).__init__() # TODO: Implement the sigmoid version first. num_classes = cfg.MODEL.FCOS.NUM_CLASSES - 1 in_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS use_...
@registry.RPN_HEADS.register("FCOSHead") class FCOSHead(torch.nn.Module): def __init__(self, cfg): super(FCOSHead, self).__init__() # TODO: Implement the sigmoid version first. num_classes = cfg.MODEL.FCOS.NUM_CLASSES - 1 in_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS use_...
self.anchor_generator = make_center_anchor_generator(cfg)
1
2023-10-23 04:07:08+00:00
4k
earthcube-lab/textnoisr
scripts/generate_figures.py
[ { "identifier": "CharNoiseAugmenter", "path": "textnoisr/noise.py", "snippet": "class CharNoiseAugmenter:\n r\"\"\"Add noise into text according to a noise level measured between 0 and 1.\n\n It will add noise to a string by modifying each character\n according to a probability and a list o...
import argparse import logging import sys import time import matplotlib.pyplot as plt import matplotlib.ticker as mtick import numpy as np import pandas as pd from pathlib import Path from datasets import load_dataset from evaluate import load from nlpaug.augmenter.char import RandomCharAug from textnoisr.noise import ...
2,552
"""Generate figures for the documentation. ## Pre-requisites You'll need to install the following packages: ```sh pip install matplotlib nlpaug ``` If you don't have [Roboto](https://fonts.google.com/specimen/Roboto) installed, the default font will be used. ## Usage From the root of the project, run: ```sh pyth...
"""Generate figures for the documentation. ## Pre-requisites You'll need to install the following packages: ```sh pip install matplotlib nlpaug ``` If you don't have [Roboto](https://fonts.google.com/specimen/Roboto) installed, the default font will be used. ## Usage From the root of the project, run: ```sh pyth...
return MAX_SWAP_LEVEL / 1.052 - 0.005
1
2023-10-18 19:28:34+00:00
4k
WenzhengZhang/Seq2seqCoref
check_align.py
[ { "identifier": "CorefAllMetrics", "path": "metrics.py", "snippet": "class CorefAllMetrics(object):\n \"\"\"\n Wrapper for coreference resolution metrics.\n \"\"\"\n\n @staticmethod\n def _get_mention_to_x(clusters: List[list]) -> dict:\n mention_to_x = {}\n for cluster in c...
import os import json import re import argparse from collections import defaultdict from metrics import CorefAllMetrics from typing import Dict from data import get_document_predicts, SPECIAL_IDS, parse_short_target_tokens from transformers import T5Tokenizer from preprocess import SPEAKER_START, SPEAKER_END, MENTION_S...
2,416
def load_data(data_dir, tokenizer): def load_split(split): max_len = 4096 data_path = os.path.join( data_dir, f'{split}.t5-small.english.{max_len}.jsonlines') samples = [] doc_labels = {} with open(data_path, 'r') as f: for line in f: ...
def load_data(data_dir, tokenizer): def load_split(split): max_len = 4096 data_path = os.path.join( data_dir, f'{split}.t5-small.english.{max_len}.jsonlines') samples = [] doc_labels = {} with open(data_path, 'r') as f: for line in f: ...
metrics = CorefAllMetrics().get_all_metrics(labels_list,
0
2023-10-17 17:39:16+00:00
4k
oven-lab/tuya_cloud_map_extractor
custom_components/tuya_cloud_map_extractor/config_flow.py
[ { "identifier": "get_map", "path": "custom_components/tuya_cloud_map_extractor/tuya_vacuum_map_extractor/main.py", "snippet": "def get_map(\n server: str, client_id: str, secret_key: str, device_id: str, colors={}, settings={}, urls={}\n) -> Image:\n \"\"\"Downloads and parses vacuum map from tuya...
import logging import voluptuous as vol from typing import Any from .tuya_vacuum_map_extractor import ( get_map, ClientIDError, ClientSecretError, DeviceIDError, ServerError, ) from homeassistant import config_entries from homeassistant.core import HomeAssistant, callback from homeassistant.helpers....
1,925
from __future__ import annotations CONF_SERVERS = { CONF_SERVER_CHINA: "China", CONF_SERVER_WEST_AMERICA: "Western America", CONF_SERVER_EAST_AMERICA: "Eastern America", CONF_SERVER_CENTRAL_EUROPE: "Central Europe", CONF_SERVER_WEST_EUROPE: "Western Europe", CONF_SERVER_INDIA: "India" } _L...
from __future__ import annotations CONF_SERVERS = { CONF_SERVER_CHINA: "China", CONF_SERVER_WEST_AMERICA: "Western America", CONF_SERVER_EAST_AMERICA: "Eastern America", CONF_SERVER_CENTRAL_EUROPE: "Central Europe", CONF_SERVER_WEST_EUROPE: "Western Europe", CONF_SERVER_INDIA: "India" } _L...
except ServerError:
4
2023-10-22 10:48:25+00:00
4k
mlbio-epfl/hume
hume.py
[ { "identifier": "parse_args", "path": "argparser.py", "snippet": "def parse_args(args):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--phi1_path', \n type=str,\n required=True,\n help=\"Path to the embeddings in ...
import os import pickle import torch import torch.nn as nn import torch.nn.functional as F import learn2learn as l2l import numpy as np from tqdm import tqdm from argparser import parse_args from activations import Sparsemax from utils import fix_seed, get_cv_score, check_both_none_or_not_none from metrics import clust...
2,848
else: phi1_val = np.copy(phi1) phi2_val = np.copy(phi2) y_true_val = np.load(args.gt_labels_path) assert phi1.shape[0] == phi2.shape[0] assert phi1_val.shape[0] == phi2_val.shape[0] assert phi1_val.shape[0] == y_true_val.shape[0] n_train = phi1.shape[0] d1, d2 = phi2.shape[1]...
def run(args=None): args = parse_args(args) device = torch.device(args.device) fix_seed(args.seed) if not os.path.exists(args.exp_path): os.makedirs(args.exp_path) phi1 = np.load(args.phi1_path).astype(np.float32) phi2 = np.load(args.phi2_path).astype(np.float32) assert c...
print(f"Cluster ACC epoch {i}:", cluster_acc(preds_all_val, y_true_val))
5
2023-10-20 15:32:06+00:00
4k
lwaekfjlk/TRAMS
utils/src.py
[ { "identifier": "TransfoXLLMHeadModel", "path": "utils/modeling_transfo_xl.py", "snippet": "_CHECKPOINT_FOR_DOC = \"transfo-xl-wt103\"\n_CONFIG_FOR_DOC = \"TransfoXLConfig\"\n_TOKENIZER_FOR_DOC = \"TransfoXLTokenizer\"\nTRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"transfo-xl-wt103\",\n # See a...
import os import logging import wandb import torch import sys from torch.nn.parallel import DistributedDataParallel from torch.optim import Adam from utils.modeling_transfo_xl import TransfoXLLMHeadModel, TransfoXLConfig from torch.optim.lr_scheduler import ExponentialLR, LambdaLR from transformers import get_linear_sc...
3,306
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(__file__))) class Trainer(object): def __init__(self, args): super().__init__() self.args = args self.set_tool() self.set_dist() self.set_seed() ...
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(__file__))) class Trainer(object): def __init__(self, args): super().__init__() self.args = args self.set_tool() self.set_dist() self.set_seed() ...
config = TransfoXLConfig(
0
2023-10-19 00:49:29+00:00
4k
npgrosser/autowired
autowired/_container.py
[ { "identifier": "component_scan", "path": "autowired/_component_scan.py", "snippet": "def component_scan(root_module: ModuleType) -> Iterable[ClassComponentInfo]:\n scanner = ClassScanner(root_module)\n component_infos = (get_component_info(cls) for cls in scanner.get_classes())\n return (c for...
import dataclasses import inspect import re from abc import ABC, abstractmethod from dataclasses import dataclass from types import FunctionType, ModuleType from typing import ( Type, Callable, Any, List, Optional, Union, Generic, Dict, TypeVar, ) from ._component_scan import compone...
2,707
@staticmethod def from_supplier( supplier: Callable[[], _T], type: Optional[Type[_T]] = None, name: Optional[str] = None, ) -> "Provider[_T]": """ Creates a provider from the given supplier function. :param supplier: The supplier function. Will be called every...
_T = TypeVar("_T") @dataclass(frozen=True) class Dependency(Generic[_T]): """ A dependency specification. """ name: str type: Type[_T] required: bool = True default_factory: Optional[Callable[[], _T]] = None class Provider(ABC, Generic[_T]): @abstractmethod def get_instance( ...
raise AmbiguousDependencyException(
2
2023-10-16 09:22:20+00:00
4k
chenxn2020/GOSE
GOSEfinetune/data/datasets/xfun.py
[ { "identifier": "load_image", "path": "GOSEfinetune/data/utils.py", "snippet": "def load_image(image_path):\n image = read_image(image_path, format=\"BGR\")\n h = image.shape[0]\n w = image.shape[1]\n img_trans = TransformList([ResizeTransform(h=h, w=w, new_h=224, new_w=224)])\n image = t...
import json import logging import os import datasets from GOSEfinetune.data.utils import load_image, merge_bbox, normalize_bbox, simplify_bbox from transformers import AutoTokenizer
2,050
"relations": datasets.Sequence( { "head": datasets.Value("int64"), "tail": datasets.Value("int64"), "start_index": datasets.Value("int64"), "end_index": datasets.Va...
# Lint as: python3 _URL = "https://github.com/doc-analysis/XFUN/releases/download/v1.0/" _LANG = ["zh", "de", "es", "fr", "en", "it", "ja", "pt"] logger = logging.getLogger(__name__) class XFUNConfig(datasets.BuilderConfig): """BuilderConfig for XFUN.""" def __init__(self, lang, additional_langs=None, *...
bbox.append(normalize_bbox(merge_bbox(tmp_box), size))
1
2023-10-19 14:36:32+00:00
4k
mklissa/dceo
dopamine/jax/agents/rainbow/rainbow_agent.py
[ { "identifier": "losses", "path": "dopamine/jax/losses.py", "snippet": "def huber_loss(targets: jnp.array,\n predictions: jnp.array,\n delta: float = 1.0) -> jnp.ndarray:\ndef mse_loss(targets: jnp.array, predictions: jnp.array) -> jnp.ndarray:\ndef softmax_cross_entropy_loss...
import functools import gin import jax import jax.numpy as jnp import numpy as onp import optax import tensorflow as tf from dopamine.jax import losses from dopamine.jax import networks from dopamine.jax.agents.dqn import dqn_agent from dopamine.metrics import statistics_instance from dopamine.replay_memory import prio...
3,135
def loss_fn(params, target, loss_multipliers): def q_online(state): return network_def.apply(params, state, support) logits = jax.vmap(q_online)(states).logits # Fetch the logits for its selected action. We use vmap to perform this # indexing across the batch. chosen_action_logits = jax.vma...
# coding=utf-8 # Copyright 2018 The Dopamine Authors. # # 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 law...
class JaxRainbowAgent(dqn_agent.JaxDQNAgent):
2
2023-10-15 22:14:16+00:00
4k
keepfoolisher/My-DocTr-Plus
GeoTr.py
[ { "identifier": "BasicEncoder", "path": "extractor.py", "snippet": "class BasicEncoder(nn.Module):\n def __init__(self, output_dim=128, norm_fn='batch'):\n super(BasicEncoder, self).__init__()\n self.norm_fn = norm_fn\n\n if self.norm_fn == 'group':\n self.norm1 = nn.G...
from extractor import BasicEncoder from position_encoding import build_position_encoding from torch import nn, Tensor from typing import Optional import argparse import numpy as np import torch import torch.nn.functional as F import copy
3,037
bs, c, h, w = imgf.shape imgf = imgf.flatten(2).permute(2, 0, 1) # query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1) pos = pos.flatten(2).permute(2, 0, 1) for layer in self.layers: query_embed = layer(query_embed, [imgf], pos=pos, memory_pos=[pos, pos]) ...
class attnLayer(nn.Module): def __init__(self, d_model, nhead=8, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn_list = nn.ModuleL...
self.fnet = BasicEncoder(output_dim=hdim, norm_fn='instance')
0
2023-10-17 11:06:30+00:00
4k
zzbuzzard/stable-diffusion-infinite-scroll
sd_scroll.py
[ { "identifier": "next_image", "path": "util.py", "snippet": "def next_image(pipe, image, base_size, prompt, shiftx, shifty, pipe_args):\n \"\"\"Given an image, uses inpainting to produce the next image (which overlaps with the previous image)\"\"\"\n assert image.size == (base_size, base_size)\n\n...
import torch import numpy as np import tkinter as tk import time import random import argparse import util from diffusers import StableDiffusionInpaintPipeline from PIL import Image from multiprocessing import Process, Queue from util import next_image from slider import Slider
2,006
parser = util.get_argparser() parser.add_argument("-spd", "--speed", default=1., type=float, help="Speed multiplier (between 0 and 1). A value of 1 causes images to be generated as fast as " "possible. A value less than 1 leads to intentional breaks between generations to ...
parser = util.get_argparser() parser.add_argument("-spd", "--speed", default=1., type=float, help="Speed multiplier (between 0 and 1). A value of 1 causes images to be generated as fast as " "possible. A value less than 1 leads to intentional breaks between generations to ...
front = next_image(pipe, image=front, base_size=base_size, prompt=prompt, shiftx=shiftx, shifty=shifty,
0
2023-10-15 14:43:52+00:00
4k
MaxDude132/django-register-field
tests/models.py
[ { "identifier": "Register", "path": "django_register/base.py", "snippet": "class Register:\n def __init__(self):\n self._key_to_class = {}\n self._class_to_key = {}\n\n def register(self, klass, db_key=None):\n if db_key is None:\n try:\n db_key = kla...
from dataclasses import dataclass from django.db import models from django_register import Register, RegisterChoices, RegisterField
1,625
# Standard libraries # Django # django_register @dataclass(unsafe_hash=True) class CountryInfo: population: int capital: str class CountryChoices(RegisterChoices): CANADA = CountryInfo(population=37_742_154, capital="Ottawa") FRANCE = CountryInfo(population=65_273_511, capital="Paris") GERMANY...
# Standard libraries # Django # django_register @dataclass(unsafe_hash=True) class CountryInfo: population: int capital: str class CountryChoices(RegisterChoices): CANADA = CountryInfo(population=37_742_154, capital="Ottawa") FRANCE = CountryInfo(population=65_273_511, capital="Paris") GERMANY...
country = RegisterField(
2
2023-10-23 18:11:08+00:00
4k
hsouri/bob-classification
timm_dataset.py
[ { "identifier": "INAT2019", "path": "datasets/inat_loader.py", "snippet": "class INAT2019(data.Dataset):\n def __init__(self, root, mode='train', year=\"2019\", transform=None):\n # load annotations\n ann_file = os.path.join(root, f\"{mode}{year}.json\")\n with open(ann_file) as ...
from datasets.transfer_cls_datasets import * from timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset from wilds import get_dataset from datasets.inat_loader import INAT2019, INAT2021 import wilds import torchvision.transforms as transforms
2,833
transfer_datasets = { 'flower102': 'Flower102', 'aircraft': 'Aircraft', # 'birdsnap': 'Birdsnap', 'dtd': 'DTD', 'voc2007': 'VOC2007', 'pets': 'Pets', 'sun397': 'SUN397', 'cars': 'Cars', 'food101': 'Food101', 'caltech101': 'Caltech101', 'cifar10': 'Cifar10', 'cifar100': 'Cifar100', 'eurosat': 'eurosa...
transfer_datasets = { 'flower102': 'Flower102', 'aircraft': 'Aircraft', # 'birdsnap': 'Birdsnap', 'dtd': 'DTD', 'voc2007': 'VOC2007', 'pets': 'Pets', 'sun397': 'SUN397', 'cars': 'Cars', 'food101': 'Food101', 'caltech101': 'Caltech101', 'cifar10': 'Cifar10', 'cifar100': 'Cifar100', 'eurosat': 'eurosa...
ds = INAT2021(root,
1
2023-10-20 16:28:17+00:00
4k
Salz0/telegram_flea
main.py
[ { "identifier": "User", "path": "models.py", "snippet": "class User(BaseModel):\n \"\"\"\n The model for the Telegram user.\n\n This model stores all the information about the user.\n It is also used to store all the authentication-related information.\n \"\"\"\n\n id = fields.BigIntFi...
import os import aiogram from asyncio import gather from pathlib import Path from aiogram import types from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.contrib.middlewares.i18n import I18nMiddleware from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import CommandStart fr...
2,177
load_dotenv() compile_all_languages() bot = aiogram.Bot(os.environ["TELEGRAM_BOT_TOKEN"]) dp = aiogram.Dispatcher(bot, storage=MemoryStorage()) BASE_DIR = Path(__file__).parent LOCALES_DIR = BASE_DIR / "locales" BOT_LANGUAGE = os.environ.get("BOT_LANGUAGE") i18n = I18nMiddleware("bot", LOCALES_DIR, default="en"...
load_dotenv() compile_all_languages() bot = aiogram.Bot(os.environ["TELEGRAM_BOT_TOKEN"]) dp = aiogram.Dispatcher(bot, storage=MemoryStorage()) BASE_DIR = Path(__file__).parent LOCALES_DIR = BASE_DIR / "locales" BOT_LANGUAGE = os.environ.get("BOT_LANGUAGE") i18n = I18nMiddleware("bot", LOCALES_DIR, default="en"...
reply_markup=sell_keyboard,
8
2023-10-19 17:28:55+00:00
4k
RobertCsordas/moe_layer
triton_src/moe_layer/moe_layer_simple.py
[ { "identifier": "cvmm", "path": "triton_src/moe_layer/cvmm.py", "snippet": "def cvmm(x: torch.Tensor, sel: Union[torch.Tensor, CVMMSel], keys: torch.Tensor):\n if not isinstance(sel, CVMMSel):\n sel = cvmm_prepare_sel(sel, keys.shape[0])\n\n return CVMM.apply(x, sel.sel_index, sel.sel, keys...
import torch import torch.distributed import torch.nn.functional as F import math from typing import Tuple, List, Optional from .cvmm import cvmm, cvmm_prepare_sel2, CVMMSel
1,944
activation_after_topk: bool = False, activation=F.relu, bias: bool = False, v_dim: Optional[int] = None, sinkhorn_n_iters: int = 3, expert_dropout: float = 0.0, weight_std_scale: float = 1.0): super().__init__() self.k...
def dist_logsumexp(x: torch.Tensor, dim: int, keepdim: bool = False) -> torch.Tensor: # Calculate numerically stable distributed logsumexp xmax = x.max(dim=dim, keepdim=True).values torch.distributed.all_reduce(xmax, op=torch.distributed.ReduceOp.MAX) xe = (x - xmax).exp().sum(dim=dim, keepdim=True) ...
sel_indices = cvmm_prepare_sel2(sel_index.int())
1
2023-10-16 11:00:47+00:00
4k
BurgerBurgerBurger/AA
model.py
[ { "identifier": "process_long_input", "path": "long_seq.py", "snippet": "def process_long_input(model, input_ids, attention_mask, start_tokens, end_tokens):\n # Split the input to 2 overlapping chunks. Now BERT can encode inputs of which the length are up to 1024.\n n, c = input_ids.size()\n st...
import torch import torch.nn as nn import torch.nn.functional as F from opt_einsum import contract from long_seq import process_long_input from losses import ATLoss from graph import AttentionGCNLayer
2,125
class DocREModel(nn.Module): def __init__(self, args, config, model, tokenizer, emb_size=768, block_size=64, num_labels=-1, max_sent_num=25, evi_thresh=0.2): super().__init__() self.config = config self.model = model self.tokenizer = tokenizer ...
class DocREModel(nn.Module): def __init__(self, args, config, model, tokenizer, emb_size=768, block_size=64, num_labels=-1, max_sent_num=25, evi_thresh=0.2): super().__init__() self.config = config self.model = model self.tokenizer = tokenizer ...
self.loss_fnt = ATLoss()
1
2023-10-20 05:53:25+00:00
4k
hnesk/flipper-raw-rfid
tests/test_rifl_file.py
[ { "identifier": "Rifl", "path": "flipper_raw_rfid/rifl.py", "snippet": "class Rifl:\n \"\"\"\n A raw rfid file from flipper (xyz.ask.raw or xyz.psk.raw)\n\n \"\"\"\n header: RiflHeader\n \"\"\" The header of the file \"\"\"\n\n pulse_and_durations: npt.NDArray[numpy.int64] = None\n ...
from io import BytesIO from pathlib import Path from unittest import TestCase from numpy.testing import assert_array_equal from flipper_raw_rfid.rifl import Rifl, RiflHeader import numpy
1,690
TEST_BASE_PATH = Path(__file__).parent.absolute() class RiflFileTest(TestCase): example_bytes = bytes.fromhex('f101a903ae028506a604fb05bb028706ad04b90404c403') example_ints = [241, 425, 302, 773, 550, 763, 315, 775, 557, 569, 4, 452] def test_header_to_bytes_and_back(self):
TEST_BASE_PATH = Path(__file__).parent.absolute() class RiflFileTest(TestCase): example_bytes = bytes.fromhex('f101a903ae028506a604fb05bb028706ad04b90404c403') example_ints = [241, 425, 302, 773, 550, 763, 315, 775, 557, 569, 4, 452] def test_header_to_bytes_and_back(self):
header = RiflHeader(1, 125_000, 0.5, 2048)
1
2023-10-20 13:06:00+00:00
4k
xingchenshanyao/YOLOP-E
lib/dataset/DemoDataset.py
[ { "identifier": "clean_str", "path": "lib/utils/utils.py", "snippet": "def clean_str(s):\n # Cleans a string by replacing special characters with underscore _\n return re.sub(pattern=\"[|@#!¡·$€%&()=?¿^*;:,¨´><+]\", repl=\"_\", string=s)" }, { "identifier": "letterbox_for_img", "path":...
import glob import os import random import shutil import time import cv2 import math import numpy as np import torch from pathlib import Path from threading import Thread from PIL import Image, ExifTags from torch.utils.data import Dataset from tqdm import tqdm from ..utils import letterbox_for_img, clean_str
1,794
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng'] vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv'] class LoadImages: # for inference def __init__(self, path, img_size=640): p = str(Path(path)) # os-agnostic p = os.path.abspath(p) # absolut...
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng'] vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv'] class LoadImages: # for inference def __init__(self, path, img_size=640): p = str(Path(path)) # os-agnostic p = os.path.abspath(p) # absolut...
self.sources = [clean_str(x) for x in sources] # clean source names for later
0
2023-10-24 02:08:25+00:00
4k
giulio98/functional-diffusion-processes
src/functional_diffusion_processes/models/base_maml.py
[ { "identifier": "clip_learning_rates", "path": "src/functional_diffusion_processes/utils/common.py", "snippet": "def clip_learning_rates(params):\n \"\"\"Clip the learning rates to the range [0, 1].\n\n Args:\n params: A dictionary of parameters.\n\n Returns:\n A dictionary contai...
import abc import logging import flax.linen as nn import hydra import jax import jax.numpy as jnp import optax from functools import partial from typing import Any, Callable, Mapping, Optional, Tuple, TypeVar from flax.core import FrozenDict, unfreeze from omegaconf import DictConfig from ..utils.common import clip_lea...
3,321
) -> Tuple[jax.random.PRNGKey, jnp.ndarray, jnp.ndarray]: """Apply the (outer) forward pass and update the model parameters. Args: rng (jax.random.PRNGKey): Random key. params (Params): Initial model parameters. batch_input (jnp.ndarray): ...
Params = FrozenDict[str, Any] T = TypeVar("T") pylogger = logging.getLogger(__name__) @partial(jax.vmap, in_axes=0) def mean_square_error(y_corrupted: jnp.ndarray, y_reconstructed: jnp.ndarray, y_psm: jnp.ndarray) -> jnp.ndarray: """Calculate the mean squared error between the predicted and actual values of ...
merged_updates = merge_learning_rates(unfreeze(updates_params), unfreeze(learning_rates))
2
2023-10-24 22:01:35+00:00
4k
godisboy0/nonebot-adapter-wcf
adapters/wechatferry/eventconverter.py
[ { "identifier": "Event", "path": "adapters/wechatferry/event.py", "snippet": "class Sender (OnebotSender):\nclass PrivateMessageEvent (OnebotPrivateMessageEvent):\nclass GroupMessageEvent (OnebotGroupMessageEvent):\nclass TTT(BaseModel):\nclass TTTB(TTT):" }, { "identifier": "MessageSegment", ...
from wcferry import Wcf, WxMsg from .event import Event, PrivateMessageEvent, GroupMessageEvent, Sender from .message import MessageSegment, Message from .type import WxType from .utils import logger from nonebot.utils import escape_tag from .sqldb import database from .msg_converters import convert_to_bot_msg from .co...
2,572
""" onebot11标准要求:https://github.com/botuniverse/onebot-11/blob/master/README.md onebot11 message segment 类型: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md """ adapter_config = AdapterConfig.parse_obj(get_driver().config) async def echo_root_msg_as_json_file(msg: WxMsg, wcf: Wcf = None): ...
""" onebot11标准要求:https://github.com/botuniverse/onebot-11/blob/master/README.md onebot11 message segment 类型: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md """ adapter_config = AdapterConfig.parse_obj(get_driver().config) async def echo_root_msg_as_json_file(msg: WxMsg, wcf: Wcf = None): ...
onebot_msg: Message = await convert_to_bot_msg(msg, login_wx_id, wcf, db)
5
2023-10-22 10:52:27+00:00
4k
R1999RC-official/Reverse1999ResonanceCalculator
python/python_env/Lib/site-packages/pip/_vendor/urllib3/util/retry.py
[ { "identifier": "ConnectTimeoutError", "path": "python/python_env/Lib/site-packages/pip/_vendor/urllib3/exceptions.py", "snippet": "class ConnectTimeoutError(TimeoutError):\n \"\"\"Raised when a socket timeout occurs while connecting to a server\"\"\"\n\n pass" }, { "identifier": "InvalidH...
import email import logging import re import time import warnings from collections import namedtuple from itertools import takewhile from ..exceptions import ( ConnectTimeoutError, InvalidHeader, MaxRetryError, ProtocolError, ProxyError, ReadTimeoutError, ResponseError, ) from ..packages imp...
2,191
from __future__ import absolute_import log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple( "RequestHistory", ["method", "url", "error", "status", "redirect_location"] ) # TODO: In v2 we can remove this sentinel and ...
from __future__ import absolute_import log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple( "RequestHistory", ["method", "url", "error", "status", "redirect_location"] ) # TODO: In v2 we can remove this sentinel and ...
@six.add_metaclass(_RetryMeta)
7
2023-10-24 06:48:58+00:00
4k
mentpy/mentpy
mentpy/operators/controlled_ment.py
[ { "identifier": "PauliX", "path": "mentpy/operators/gates.py", "snippet": "CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])\nSWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])\n U = unitary_group.rvs(2**n_qubits)\n U = U / np.power(detU, 1 / (2**n_qu...
from typing import Optional, Union, Callable from .gates import PauliX, PauliY, PauliZ from .ment import Ment, MentOutcome import numpy as np import warnings
2,653
# Copyright 2023 Luis Mantilla # # Licensed under the Apache License, Version 2.0. # See <http://www.apache.org/licenses/LICENSE-2.0> for details. """Controlled measurement operator.""" class ControlMent(Ment): def __init__( self,
# Copyright 2023 Luis Mantilla # # Licensed under the Apache License, Version 2.0. # See <http://www.apache.org/licenses/LICENSE-2.0> for details. """Controlled measurement operator.""" class ControlMent(Ment): def __init__( self,
condition: Optional[Union[bool, MentOutcome]] = None,
2
2023-10-18 18:29:42+00:00
4k
rnag/cert-hero
tests/integration/test_cert_hero.py
[ { "identifier": "cert_please", "path": "cert_hero/cert_hero.py", "snippet": "def cert_please(hostname: str,\n context: ssl.SSLContext = None,\n user_agent: str | None = _DEFAULT_USER_AGENT,\n default_encoding='latin-1',\n ) -> CertHero[str, str...
import json from cert_hero import cert_please, certs_please, set_expired
3,566
def test_cert_please(): cert = cert_please('google.com') print('Cert is Valid Till:', cert.not_after_date.isoformat()) # To get the output as a JSON string, use `str(cert)` or remove `!r` from below print(f'Cert -> \n{cert!r}') assert cert['Subject Name']['Common Name'] == '*.google.com'
def test_cert_please(): cert = cert_please('google.com') print('Cert is Valid Till:', cert.not_after_date.isoformat()) # To get the output as a JSON string, use `str(cert)` or remove `!r` from below print(f'Cert -> \n{cert!r}') assert cert['Subject Name']['Common Name'] == '*.google.com'
set_expired(cert)
2
2023-10-16 19:02:05+00:00
4k
KosinskiLab/pyTME
tme/tests/test_parser.py
[ { "identifier": "Parser", "path": "tme/parser.py", "snippet": "class Parser(ABC):\n \"\"\"\n Base class for structure file parsers.\n\n Classes inheriting from :py:class:`Parser` need to define\n a ``parse_input`` method that accepts a list of lines and returns a\n dictionary representati...
import pytest from tme.parser import Parser, PDBParser
1,807
class TestParser: def setup_method(self): self.pdb_file = "./tme/tests/data/Structures/5khe.pdb" def teardown_method(self): self.pdb_file = None def test_initialize_parser_error(self): with pytest.raises(TypeError):
class TestParser: def setup_method(self): self.pdb_file = "./tme/tests/data/Structures/5khe.pdb" def teardown_method(self): self.pdb_file = None def test_initialize_parser_error(self): with pytest.raises(TypeError):
_ = Parser(self.pdb_file)
0
2023-10-20 13:46:01+00:00
4k
hookla/DreamTeamGPT
dream_team_gpt/meeting.py
[ { "identifier": "Chairman", "path": "dream_team_gpt/agents/chairman.py", "snippet": "class Chairman(Agent):\n def __init__(self, client_factory: Callable, executives: list[SME], name: str = \"Chairman\"):\n # Construct the user_prompt string with details of the executives\n self.user_pr...
from dataclasses import dataclass, field from pathlib import Path from textwrap import dedent from loguru import logger from dream_team_gpt.agents import SME, Chairman from dream_team_gpt.agents.idea_refiner import IdeaRefiner from dream_team_gpt.clients import AIClientConfig, AIClientType, Models, ai_client_factory fr...
1,897
@dataclass class Transcript(str): idea: str refined_idea: str = None opinions: list[str] = field(default_factory=list) def __str__(self) -> str: opinions = "\n".join(opinion for opinion in self.opinions) return dedent( f"""\ We are here to discuss the followi...
@dataclass class Transcript(str): idea: str refined_idea: str = None opinions: list[str] = field(default_factory=list) def __str__(self) -> str: opinions = "\n".join(opinion for opinion in self.opinions) return dedent( f"""\ We are here to discuss the followi...
self.smes = [SME(client_factory=client_factory, **d) for d in sme_dict]
1
2023-10-18 22:45:50+00:00
4k
MeetingAgent/MeetingAgent-Core
meeting_buddy.py
[ { "identifier": "MyTTS", "path": "voice_cloning/clone.py", "snippet": "class MyTTS:\n def __init__(self):\n # Get device\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n self.tts = TTS(\"tts_models/en/ljspeech/tacotron2-DDC\")\n self.use_default_speak...
import pyaudio import wave import whisper import threading import time import pygame from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.switch import Switch from kivy.uix.label import Label from kivy.clock import Clock from kivy.uix.textinput import TextIn...
2,694
play_audio('meeting_buddy_audio/output.mp3') else: # Update the answer text without text-to-speech Clock.schedule_once(lambda dt: app.update_answer_text(aggregated_text)) return query, answer def meeting_buddy(meeting_context: str) -> None: global audio_thread audio_thr...
# Audio Processing # GUI install_twisted_reactor() # gtts text to speech # personalized voice text to speech # Local recording = False audio_thread = None def get_audio() -> None: global recording recording = True p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paInt16, channels=1, rate=44...
self.tts = MyTTS()
0
2023-10-18 06:50:56+00:00
4k
tonnetonne814/MB-iSTFT-BERT-VITS2-44100-Ja
modules.py
[ { "identifier": "init_weights", "path": "commons.py", "snippet": "def init_weights(m, mean=0.0, std=0.01):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n m.weight.data.normal_(mean, std)" }, { "identifier": "get_padding", "path": "commons.py", "sni...
import math import torch import commons from torch import nn from torch.nn import functional as F from torch.nn import Conv1d from torch.nn.utils import weight_norm, remove_weight_norm from commons import init_weights, get_padding from transforms import piecewise_rational_quadratic_transform from attentions import Enco...
2,950
dilation_rate, n_layers, gin_channels=0, p_dropout=0, ): super(WN, self).__init__() assert kernel_size % 2 == 1 self.hidden_channels = hidden_channels self.kernel_size = (kernel_size,) self.dilation_rate = dilation_rate self.n_layers = ...
LRELU_SLOPE = 0.1 class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = eps self.gamma = nn.Parameter(torch.ones(channels)) self.beta = nn.Parameter(torch.zeros(channels)) def forward(self, x): ...
self.convs1.apply(init_weights)
0
2023-10-16 10:04:32+00:00
4k
KaichengGroup/FUSE-Flow
test.py
[ { "identifier": "NPZDataset", "path": "data_modules/npz_dataset.py", "snippet": "class NPZDataset(VisionDataset):\n \"\"\"Load datasets from NPZ files.\n NPZ files are assumed to have 2 files named \"x\" and \"y\"\n that represent the input and target, respectively.\n\n Parameters\n -----...
import os import pytorch_lightning as pl import torch from pytorch_lightning import Trainer from torch.utils.data import DataLoader from torchvision.transforms import ToTensor, Compose from data_modules.npz_dataset import NPZDataset from utils.utils import load_config, create_subset, save_train_results, CONFIG_PATH, de...
1,937
if __name__ == '__main__': pl.seed_everything(42) # "highest" (default), float32 matrix multiplications use the float32 datatype for internal computations. # "high", float32 matrix multiplications use the TensorFloat32 or bfloat16_3x # "medium", float32 matrix multiplications use the bfloat16 dataty...
if __name__ == '__main__': pl.seed_everything(42) # "highest" (default), float32 matrix multiplications use the float32 datatype for internal computations. # "high", float32 matrix multiplications use the TensorFloat32 or bfloat16_3x # "medium", float32 matrix multiplications use the bfloat16 dataty...
config = load_config(CONFIG_PATH)
1
2023-10-19 06:49:31+00:00
4k
TheAcharya/Airlift
airlift/airtable_upload.py
[ { "identifier": "new_client", "path": "airlift/airtable_client.py", "snippet": "class new_client:\n\n def __init__(self,token:str,base:str,table:str):\n\n self.api = token\n self.base = base\n self.table = table\n self.headers = {\n \"Authorization\": \"Bear...
import logging import concurrent.futures import os from airlift.airtable_client import new_client from typing import Any, Dict, Iterable, Iterator, List, Optional from queue import Queue, Empty from airlift.dropbox_client import dropbox_client from tqdm import tqdm from icecream import ic from airlift.dropbox_client im...
2,823
logger = logging.getLogger(__name__) ATDATA = List[Dict[str, Dict[str, str]]] class Upload:
logger = logging.getLogger(__name__) ATDATA = List[Dict[str, Dict[str, str]]] class Upload:
def __init__(self,client: new_client, new_data:ATDATA,dbx:dropbox_client,args:dict):
0
2023-10-21 01:57:41+00:00
4k
zytedata/zyte-spider-templates
zyte_spider_templates/spiders/base.py
[ { "identifier": "GEOLOCATION_OPTIONS_WITH_CODE", "path": "zyte_spider_templates/_geolocations.py", "snippet": "GEOLOCATION_OPTIONS_WITH_CODE = {\n code: f\"{name} ({code})\" for code, name in GEOLOCATION_OPTIONS.items()\n}" }, { "identifier": "Geolocation", "path": "zyte_spider_templates/...
from importlib.metadata import version from typing import Any, Dict, Optional from pydantic import BaseModel, Field from scrapy.crawler import Crawler from scrapy.utils.url import parse_url from zyte_spider_templates._geolocations import ( GEOLOCATION_OPTIONS_WITH_CODE, Geolocation, ) import scrapy
2,504
# Higher priority than command-line-defined settings (40). ARG_SETTING_PRIORITY: int = 50 class BaseSpiderParams(BaseModel): url: str = Field( title="URL", description="Initial URL for the crawl.", pattern=r"^https?:\/\/[^:\/\s]+(:\d{1,5})?(\/[^\s]*)*(#[^\s]*)?$", )
# Higher priority than command-line-defined settings (40). ARG_SETTING_PRIORITY: int = 50 class BaseSpiderParams(BaseModel): url: str = Field( title="URL", description="Initial URL for the crawl.", pattern=r"^https?:\/\/[^:\/\s]+(:\d{1,5})?(\/[^\s]*)*(#[^\s]*)?$", )
geolocation: Optional[Geolocation] = Field(
1
2023-10-18 10:58:44+00:00
4k
DegangWang97/IEEE_TGRS_PDBSNet
main.py
[ { "identifier": "PDBSNet", "path": "model.py", "snippet": "class PDBSNet(nn.Module):\n def __init__(self, nch_in=189, nch_out=189, nch_ker=64, nblk=9):\n super().__init__()\n\n ly = []\n ly += [ nn.Conv2d(nch_in, nch_ker, kernel_size=1) ]\n ly += [ nn.ReLU(inplace=True) ]\...
import argparse import torch import torch.nn as nn import scipy.io as sio import os import numpy as np import time from model import PDBSNet from dataset import PDBSNetData, pixel_shuffle_up_sampling, pixel_shuffle_down_sampling from utils import get_auc, setup_seed, TensorToHSI from torch import optim from ...
3,107
Trains a PyTorch `nn.Module` object provided in `model` on training sets provided in `dataloader` using `criterion` and `optimizer`. Saves model weight snapshots every `save_freq` epochs and saves the weights at the end of training. Parameters ---------- ...
""" See more details in papers: [1] D. Wang, L. Zhuang, L. Gao, X. Sun, M. Huang, and A. Plaza, “PDBSNet: Pixel-Shuffle Downsampling Blind-Spot Reconstruction Network for Hyperspectral Anomaly Detection,” IEEE Trans. Geosci. Remote Sens., vol. 61, 2023, Art. no. 5511914. DOI: 10.1109/TGRS.2023....
net = PDBSNet(band, band, nch_ker=opt.nch_ker, nblk=opt.nblk).to(device)
0
2023-10-16 08:28:56+00:00
4k
AVAniketh0905/fluidspy
fluidspylib/fluidspy/tests/test_fdm.py
[ { "identifier": "Bottom", "path": "fluidspylib/fluidspy/numerical/boundary/direction.py", "snippet": "class Bottom(Direction):\n \"\"\"Bottom direction.\"\"\"\n\n def __init__(\n self,\n initial_value: float,\n state: SimulationState,\n boundary_condition: BoundaryCondi...
import pytest from ..numerical.boundary import Bottom from ..numerical.boundary import CompositeBoundary from ..numerical.boundary import Constant from ..numerical.boundary import Insulated from ..numerical.boundary import Left from ..numerical.boundary import Right from ..numerical.boundary import Top from ..numerical...
3,076
def create_state_dim(state, dim, shape): dim = dim(state) dim.create_grid(shape) return dim def test_ftcs(): state = SimulationState() dim = create_state_dim(state, OneDimSpatial, 10) boundary = CompositeBoundary( Left(5, state, Constant()), Right(10, state, Insulated()) ) ...
def create_state_dim(state, dim, shape): dim = dim(state) dim.create_grid(shape) return dim def test_ftcs(): state = SimulationState() dim = create_state_dim(state, OneDimSpatial, 10) boundary = CompositeBoundary( Left(5, state, Constant()), Right(10, state, Insulated()) ) ...
step = Step(0.1, Vector(0.1))
13
2023-10-21 06:55:58+00:00
4k
jobless-devs/Jobhub
lambdas/packages/python/psycopg2/extras.py
[ { "identifier": "PY2", "path": "lambdas/packages/python/psycopg2/compat.py", "snippet": "PY2 = True\nPY3 = False\nPY2 = False\nPY3 = True" }, { "identifier": "adapt", "path": "lambdas/packages/python/psycopg2/extensions.py", "snippet": "ISOLATION_LEVEL_AUTOCOMMIT = 0\nISOLATION_LEVEL_REA...
import logging as _logging import os as _os import re as _re import time as _time import psycopg2 import uuid import warnings import select from collections import namedtuple, OrderedDict from psycopg2 import extensions as _ext from psycopg2._ipaddress import register_ipaddress # noqa from psycopg2._json i...
2,715
if self._prefetch: res = super(DictCursorBase, self).fetchmany(size) if self._query_executed: self._build_index() if not self._prefetch: res = super(DictCursorBase, self).fetchmany(size) return res def fetchall(self): if self._prefetch: ...
"""Miscellaneous goodies for psycopg2 This module is a generic place used to hold little helper functions and classes until a better place in the distribution is found. """ # psycopg/extras.py - miscellaneous extra goodies for psycopg # # Copyright (C) 2003-2019 Federico Di Gregorio <fog@debian.org> # Copyright (C) 2...
if PY2:
0
2023-10-22 20:09:51+00:00
4k
kyegomez/gradient-ascent
visualization.py
[ { "identifier": "GradientAscent", "path": "gradient_ascent/main.py", "snippet": "class GradientAscent:\n \"\"\"\n Gradient Ascent Optimizer\n\n Optimizer that performs gradient ascent on the parameters of the model.\n\n Args:\n parameters (iterable): iterable of parameters to optimize...
import matplotlib.pyplot as plt import numpy as np import torch from matplotlib.animation import FuncAnimation from gradient_ascent import GradientAscent from gradient_ascent.main import GradientAscent
2,636
class SimpleModel(torch.nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc = torch.nn.Linear(1, 1) def forward(self, x): return self.fc(x) # Set up real-time plotting plt.ion() # Turn on interactive mode fig, ax = plt.subplots(figsize=(10, 6)) ax.set_xlim(...
class SimpleModel(torch.nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc = torch.nn.Linear(1, 1) def forward(self, x): return self.fc(x) # Set up real-time plotting plt.ion() # Turn on interactive mode fig, ax = plt.subplots(figsize=(10, 6)) ax.set_xlim(...
optimizer = GradientAscent(
1
2023-10-21 01:14:22+00:00
4k
cfs-energy/cfspopcon
cfspopcon/formulas/scrape_off_layer_model/lambda_q.py
[ { "identifier": "LambdaQScaling", "path": "cfspopcon/named_options.py", "snippet": "class LambdaQScaling(Enum):\n \"\"\"Options for heat flux decay length scaling.\"\"\"\n\n Brunner = auto()\n EichRegression14 = auto()\n EichRegression15 = auto()" }, { "identifier": "wraps_ufunc", ...
from ...named_options import LambdaQScaling from ...unit_handling import ureg, wraps_ufunc
2,160
"""Routines to calculate the heat flux decay length (lambda_q), for several different scalings.""" @wraps_ufunc( return_units=dict(lambda_q=ureg.millimeter), input_units=dict( lambda_q_scaling=None, average_total_pressure=ureg.atm, power_crossing_separatrix=ureg.megawatt, majo...
"""Routines to calculate the heat flux decay length (lambda_q), for several different scalings.""" @wraps_ufunc( return_units=dict(lambda_q=ureg.millimeter), input_units=dict( lambda_q_scaling=None, average_total_pressure=ureg.atm, power_crossing_separatrix=ureg.megawatt, majo...
lambda_q_scaling: LambdaQScaling,
0
2023-10-19 16:58:23+00:00
4k
GXimingLu/IPA
policy_gp3.py
[ { "identifier": "ConstrainedHypothesis", "path": "lexical_constraints.py", "snippet": "class ConstrainedHypothesis:\n\n def __init__(self,\n constraint_list: List[List[List[int]]],\n eos_tokens: List[int]) -> None:\n self.clauses = []\n for idx, clause in...
import torch import torch.nn.functional as F import json import numpy as np import openai from typing import Union, List, Dict from transformers import GPT2LMHeadModel, GPT2Tokenizer from lexical_constraints import ConstrainedHypothesis, init_batch from utils.constants import NEGATIVE_INF, OPENAI_API_KEY from utils.ut...
2,234
openai.api_key = OPENAI_API_KEY class Policy: def __init__(self, value_model_name, value_model_checkpoint, device, tree_tokens, alpha, force_eos): self.device = device self.value_model = GPT2LMHeadModel.from_pretrained(value_model_name) self.tokenizer = GPT2Tokenizer.from_pretrained(valu...
openai.api_key = OPENAI_API_KEY class Policy: def __init__(self, value_model_name, value_model_checkpoint, device, tree_tokens, alpha, force_eos): self.device = device self.value_model = GPT2LMHeadModel.from_pretrained(value_model_name) self.tokenizer = GPT2Tokenizer.from_pretrained(valu...
value_outputs, value_next_token_logits = get_model_output(self.value_model, step, value_input_ids,
6
2023-10-20 08:30:18+00:00
4k
yifei-he/GOAT
experiments.py
[ { "identifier": "ot_ablation", "path": "ot_util.py", "snippet": "def ot_ablation(size, mode):\n ns, nt = size, size\n plan = np.zeros((ns, nt))\n ran = np.arange(ns*nt)\n np.random.shuffle(ran)\n idx = ran[:size]\n\n for i in idx:\n row = i // nt\n col = i-i//nt * nt\n ...
import torch import torch.optim as optim import copy import argparse import random import torch.backends.cudnn as cudnn import time from model import * from train_model import * from util import * from ot_util import ot_ablation from da_algo import * from ot_util import generate_domains from dataset import *
1,769
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def get_source_model(args, trainset, testset, n_class, mode, encoder=None, epochs=50, verbose=True): print("Start training source model") model = Classifier(encoder, MLP(mode=mode, n_class=n_class, hidden=1024)).to(device) optimizer ...
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def get_source_model(args, trainset, testset, n_class, mode, encoder=None, epochs=50, verbose=True): print("Start training source model") model = Classifier(encoder, MLP(mode=mode, n_class=n_class, hidden=1024)).to(device) optimizer ...
plan = ot_ablation(len(src_trainset), "random")
0
2023-10-20 16:41:00+00:00
4k
ansible/django-ansible-base
ansible_base/tests/unit/utils/test_validation.py
[ { "identifier": "to_python_boolean", "path": "ansible_base/utils/validation.py", "snippet": "def to_python_boolean(value, allow_none=False):\n value = str(value)\n if value.lower() in ('true', '1', 't'):\n return True\n elif value.lower() in ('false', '0', 'f'):\n return False\n ...
import pytest from rest_framework.exceptions import ValidationError from ansible_base.utils.validation import to_python_boolean, validate_cert_with_key, validate_image_data, validate_url
1,721
@pytest.mark.parametrize( "valid,url,schemes,allow_plain_hostname", [ (False, 4, [], True), (False, "https://example", ['https'], False), (True, "https://example", ['https'], True), (True, "https://somedomain.example.com/sso/complete/saml/", ['https'], True), (False, "...
@pytest.mark.parametrize( "valid,url,schemes,allow_plain_hostname", [ (False, 4, [], True), (False, "https://example", ['https'], False), (True, "https://example", ['https'], True), (True, "https://somedomain.example.com/sso/complete/saml/", ['https'], True), (False, "...
res = validate_image_data(image_data)
2
2023-10-20 13:20:12+00:00
4k
violet-sto/HN-GFN
dataset.py
[ { "identifier": "MolMDPExtended", "path": "mol_mdp_ext.py", "snippet": "class MolMDPExtended(MolMDP):\n\n def build_translation_table(self):\n \"\"\"build a symmetry mapping for blocks. Necessary to compute parent transitions\"\"\"\n self.translation_table = {}\n for blockidx in ...
import pandas as pd import numpy as np import torch import time import threading import json from sklearn.utils import shuffle from mol_mdp_ext import MolMDPExtended, BlockMoleculeDataExtended from tqdm import tqdm from botorch.utils.multi_objective.hypervolume import Hypervolume
3,098
class Dataset: def __init__(self, args, bpath, oracle, device): self.test_split_rng = np.random.RandomState(142857) self.train_rng = np.random.RandomState(int(time.time())) self.train_mols = [] self.test_mols = [] self.all_mols = [] self.train_mols_map = {}
class Dataset: def __init__(self, args, bpath, oracle, device): self.test_split_rng = np.random.RandomState(142857) self.train_rng = np.random.RandomState(int(time.time())) self.train_mols = [] self.test_mols = [] self.all_mols = [] self.train_mols_map = {}
self.mdp = MolMDPExtended(bpath)
0
2023-10-24 14:10:35+00:00
4k
line/Skeleton-Temporal-Action-Localization
evaluation/eval.py
[ { "identifier": "getClassificationMAP", "path": "evaluation/classificationMAP.py", "snippet": "def getClassificationMAP(confidence, labels):\n \"\"\" confidence and labels are of dimension n_samples x n_label \"\"\"\n\n AP = []\n for i in range(np.shape(labels)[1]):\n AP.append(getAP(con...
import numpy as np import torch import torch.nn.functional as F from torch.autograd import Variable from .classificationMAP import getClassificationMAP as cmAP from .detectionMAP import getSingleStreamDetectionMAP as dsmAP from .detectionMAP import getTwoStreamDetectionMAP as dtmAP from .utils import write_results_to_e...
1,845
def ss_eval(epoch, dataloader, args, logger, model, device): vid_preds = [] frm_preds = [] vid_lens = [] labels = [] for num, sample in enumerate(dataloader): if (num + 1) % 100 == 0: print("Testing test data point %d of %d" % (num + 1, len(dataloader))) features = s...
def ss_eval(epoch, dataloader, args, logger, model, device): vid_preds = [] frm_preds = [] vid_lens = [] labels = [] for num, sample in enumerate(dataloader): if (num + 1) % 100 == 0: print("Testing test data point %d of %d" % (num + 1, len(dataloader))) features = s...
dmap, iou = dtmAP(
0
2023-10-20 05:38:16+00:00
4k
SALT-NLP/Efficient_Unlearning
src/models/transformers/parameter-efficient-finetuning/modeling.py
[ { "identifier": "AdapterConfig", "path": "src/models/transformers/parameter-efficient-finetuning/configuration.py", "snippet": "class AdapterConfig(AdapterConfigBase):\n \"\"\"\n Base class that models the architecture of an adapter.\n\n Args:\n mh_adapter (:obj:`bool`): If True, add ada...
import math import torch from torch import nn from transformers.activations import get_activation from .configuration import AdapterConfig, AdapterFusionConfig from .context import ForwardContext
2,948
class Activation_Function_Class(nn.Module): """ Implementation of various activation function. """ def __init__(self, hidden_act): super().__init__() if hidden_act.lower() == "leakyrelu": self.f = nn.functional.leaky_relu else: self.f = get_activatio...
class Activation_Function_Class(nn.Module): """ Implementation of various activation function. """ def __init__(self, hidden_act): super().__init__() if hidden_act.lower() == "leakyrelu": self.f = nn.functional.leaky_relu else: self.f = get_activatio...
config: AdapterConfig,
0
2023-10-18 18:05:54+00:00
4k
yntha/cstruct
cstruct/_classwrap.py
[ { "identifier": "collect_metadata", "path": "cstruct/_metadata.py", "snippet": "def collect_metadata(class_obj: dataclass) -> StructMetadata:\n metadata = StructMetadata()\n\n for field in dataclasses.fields(class_obj):\n # the parameters passed to the dataclass constructor individually\n ...
import dataclasses import typing from dataclasses import dataclass from ._metadata import collect_metadata from ._lexer import CStructLexer
3,155
# -------------------------------------------------------------------------------------- # Copyright(C) 2023 yntha - # - # This program is free software: you can redistribut...
# -------------------------------------------------------------------------------------- # Copyright(C) 2023 yntha - # - # This program is free software: you can redistribut...
self.meta = collect_metadata(self)
0
2023-10-22 18:33:32+00:00
4k
sehyun03/MulActSeg
trainer/active_joint_multi_lossdecomp.py
[ { "identifier": "active_joint_multi", "path": "trainer/active_joint_multi.py", "snippet": "class ActiveTrainer(active.ActiveTrainer):\n def __init__(self, args, logger, selection_iter):\n def get_criterion(self):\n def zero_if_nan(self, loss):\n def check_loss_sanity(self, loss):\n def up...
import torch import numpy as np import torch.nn.functional as F from torch import nn from tqdm import tqdm from torch_scatter import scatter from trainer import active_joint_multi from trainer.active_joint_multi_predignore_mclossablation2 import GroupMultiLabelCE_onlymulti from utils.loss import MultiChoiceCE
2,380
r""" Decomposition of previous multi-positive loss & group-multi loss - One-hot spxs: CE loss - Multi-hot spxs: Multi-positive, Group Multi - without predignore """ class OnehotCEMultihotChoice(MultiChoiceCE): def __init__(self, num_class, temperature=1.0, reduction='mean'): super().__init__(num_class, tem...
r""" Decomposition of previous multi-positive loss & group-multi loss - One-hot spxs: CE loss - Multi-hot spxs: Multi-positive, Group Multi - without predignore """ class OnehotCEMultihotChoice(MultiChoiceCE): def __init__(self, num_class, temperature=1.0, reduction='mean'): super().__init__(num_class, tem...
class ActiveTrainer(active_joint_multi.ActiveTrainer):
0
2023-10-24 09:19:58+00:00
4k
hms-dbmi/CHIEF
train.py
[ { "identifier": "read_yaml", "path": "utils/utils.py", "snippet": "def read_yaml(fpath=\"./configs/sample.yaml\"):\n with open(fpath, mode=\"r\") as file:\n yml = yaml.load(file, Loader=yaml.Loader)\n return Dict(yml)" }, { "identifier": "seed_torch", "path": "utils/utils.py...
import argparse import os import shutil import torch from utils.utils import read_yaml, seed_torch from utils.trainer import Trainer
2,304
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--config_path', type=str) parser.add_argument('--begin', type=int, default=0) parser.add_argument('--end', type=int, default=10) return parser.parse_args() if __name__ == '__main__': args = get_args() device = to...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--config_path', type=str) parser.add_argument('--begin', type=int, default=0) parser.add_argument('--end', type=int, default=10) return parser.parse_args() if __name__ == '__main__': args = get_args() device = to...
cfg = read_yaml(args.config_path)
0
2023-10-17 21:19:25+00:00
4k
justincui03/tesla
buffer.py
[ { "identifier": "get_dataset", "path": "utils.py", "snippet": "def get_dataset(dataset, data_path, batch_size=1, args=None):\n\n class_map = None\n loader_train_dict = None\n class_map_inv = None\n\n if dataset == 'CIFAR10':\n channel = 3\n im_size = (32, 32)\n num_class...
import os import argparse import torch import torch.nn as nn import copy import warnings from tqdm import tqdm from utils import get_dataset, get_network, get_daparam,\ TensorDataset, epoch, ParamDiffAug from PIL import PngImagePlugin
3,186
LARGE_ENOUGH_NUMBER = 100 PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2) warnings.filterwarnings("ignore", category=DeprecationWarning) def main(args): args.dsa = True if args.dsa == 'True' else False args.device = 'cuda' if torch.cuda.is_available() else 'cpu' args.dsa_param = ParamDif...
LARGE_ENOUGH_NUMBER = 100 PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2) warnings.filterwarnings("ignore", category=DeprecationWarning) def main(args): args.dsa = True if args.dsa == 'True' else False args.device = 'cuda' if torch.cuda.is_available() else 'cpu' args.dsa_param = ParamDif...
channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader, loader_train_dict, class_map, class_map_inv = get_dataset(args.dataset, args.data_path, args.batch_real, args=args)
0
2023-10-17 23:11:36+00:00
4k
upiterbarg/hihack
models/hierarchical_transformer_lstm.py
[ { "identifier": "generate_square_subsequent_mask", "path": "models/transformer_lstm.py", "snippet": "def generate_square_subsequent_mask(sz: int, device: str = \"cpu\") -> torch.Tensor:\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = (\n mask.float()\n .masked...
import json import numpy as np import os import pathlib import pdb import torch import sys from nle import nethack from nle.nethack.actions import ACTIONS as A from torch import nn from torch.nn import functional as F from .transformer_lstm import ( generate_square_subsequent_mask, PositionalEncoding ) from cha...
2,541
self.inference_unroll_length = flags.unroll_length if not 'inference_unroll_length' in flags else flags.inference_unroll_length self.wrapped = False def initial_state(self, batch_size=1): return ( torch.zeros(1, batch_size, self.inference_unroll_length, self.inference_unroll_le...
base_path = pathlib.Path().resolve() sys.path.insert(0, os.path.join(base_path, '..', 'dungeonsdata-neurips2022/experiment_code/hackrl/models')) class HierarchicalTransformerLSTM(nn.Module): def __init__(self, shape, action_space, flags, device, num_strategies=20): super(HierarchicalTransformerLSTM, sel...
trnsfrmr_core_mask = generate_square_subsequent_mask(T, trnsfrmr_core_input.device)
0
2023-10-23 15:44:32+00:00
4k
nmathey/finasync
finasync/realt.py
[ { "identifier": "GNOSIS_API_TOKENLIST_URI", "path": "finasync/constants.py", "snippet": "GNOSIS_API_TOKENLIST_URI = (\n \"https://blockscout.com/xdai/mainnet/api?module=account&action=tokenlist&address=\"\n)" }, { "identifier": "REALT_API_TOKENLIST_URI", "path": "finasync/constants.py", ...
import requests import re import json import time import os import logging from pathlib import Path from datetime import datetime, timedelta from json.decoder import JSONDecodeError from finary_uapi.user_real_estates import ( get_user_real_estates, delete_user_real_estates, update_user_real_estates, add...
2,393
logging.debug("My RealT Finary portfolio") logging.debug(myFinary_real_estates) myFinary_realT = {} for item in myFinary_real_estates: contractAddress = re.findall(r"0x.+", str(item.get("description"))) name = re.findall(r"- (.*) -", str(item.get("description"))) myFinary_realT.u...
def get_realt_token_details(realt_token_contractAdress): Now_Time = datetime.today() RealT_OfflineTokensList_Path = Path(REALT_OFFLINE_TOKENS_LIST) RealT_OfflineTokensList_Path.touch(exist_ok=True) with open(RealT_OfflineTokensList_Path) as json_file: try: RealT_OfflineTokensLis...
user_estimated_value = token_details["totalTokens"] * convert_currency(
3
2023-10-24 00:32:05+00:00
4k
vitaliisili/petoshield-rest
petoshield_api/apps/policy/filters.py
[ { "identifier": "ServiceProvider", "path": "petoshield_api/apps/policy/models.py", "snippet": "class ServiceProvider(ExportModelOperationsMixin('service_provider'), BaseModel):\n \"\"\"Model representing a service provider.\n Attributes:\n company_name (CharField): The name of the company. ...
from django_filters import rest_framework as filters from .models import ServiceProvider, Policy, InsuranceCase, IncomingInvoice
1,723
class ServiceProviderFilter(filters.FilterSet): """A filter class for the ServiceProvider model. Attributes: user (CharFilter): Filter for the 'user__name' field using the 'icontains' lookup. created_at__year__exact (NumberFilter): Filter for the 'created_at__year' field with exact matching. ...
class ServiceProviderFilter(filters.FilterSet): """A filter class for the ServiceProvider model. Attributes: user (CharFilter): Filter for the 'user__name' field using the 'icontains' lookup. created_at__year__exact (NumberFilter): Filter for the 'created_at__year' field with exact matching. ...
model = ServiceProvider
0
2023-10-19 08:09:10+00:00
4k
biggzlar/plausible-uncertainties
train.py
[ { "identifier": "get_device", "path": "utils.py", "snippet": "def get_device():\n return torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")" }, { "identifier": "UnivariateDummyData", "path": "utils.py", "snippet": "class UnivariateDummyData:\n\tdef __init__(self, N, X_ra...
import tqdm import torch import numpy as np import matplotlib.pyplot as plt from utils import get_device, UnivariateDummyData, get_predicted_cdf from evidential_regression.networks import UnivariateDerNet from evidential_regression.losses import UnivariateEvidentialRegressionLoss from mle_mc_dropout.networks import Uni...
2,487
# plot settings plt.rcParams.update( { "font.size": 12, "text.usetex": False, "font.family": "stixgeneral", "mathtext.fontset": "stix", } ) if __name__ == "__main__": device = get_device() print(f"Working on {device}!") EPOCHS = 120 in_lower = -2.0 in_upper = 10.0 trai...
# plot settings plt.rcParams.update( { "font.size": 12, "text.usetex": False, "font.family": "stixgeneral", "mathtext.fontset": "stix", } ) if __name__ == "__main__": device = get_device() print(f"Working on {device}!") EPOCHS = 120 in_lower = -2.0 in_upper = 10.0 trai...
criterion = UnivariateEvidentialRegressionLoss()
4
2023-10-19 08:44:08+00:00
4k
avilliai/Bert_Vits2_Sever
modules.py
[ { "identifier": "init_weights", "path": "commons.py", "snippet": "def init_weights(m, mean=0.0, std=0.01):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n m.weight.data.normal_(mean, std)" }, { "identifier": "get_padding", "path": "commons.py", "snippet": "...
import copy import math import numpy as np import scipy import torch import commons from torch import nn from torch.nn import functional as F from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d from torch.nn.utils import weight_norm, remove_weight_norm from commons import init_weights, get_padding from tran...
2,812
self.n_layers = n_layers self.p_dropout = p_dropout self.drop = nn.Dropout(p_dropout) self.convs_sep = nn.ModuleList() self.convs_1x1 = nn.ModuleList() self.norms_1 = nn.ModuleList() self.norms_2 = nn.ModuleList() for i in range(n_layers): dilation = kernel_size ** i padding...
LRELU_SLOPE = 0.1 class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = eps self.gamma = nn.Parameter(torch.ones(channels)) self.beta = nn.Parameter(torch.zeros(channels)) def forward(self, x): x = x.transpose(1, -1) ...
self.convs1.apply(init_weights)
0
2023-10-23 08:24:12+00:00
4k
t-ega/whatsapp-cloud-sdk
whatsapp_cloud_sdk/_files/contact.py
[ { "identifier": "File", "path": "whatsapp_cloud_sdk/_files/file_object.py", "snippet": "class File:\n \"\"\"Base Class for all file objects.\"\"\"\n\n __slots__ = ()\n _id_attrs = ()\n\n def __str__(self):\n \"\"\"Return a string representation of the object.\"\"\"\n attributes...
from typing import List, Optional, Union from whatsapp_cloud_sdk._files.file_object import File from whatsapp_cloud_sdk._utils.types import JSONDict from whatsapp_cloud_sdk._validators.messages import ( AddressValidator, NameValidator, PhoneValidator, OrgValidator, URLValidator, EmailValidator, ...
1,630
"""This module contains an object that represents a Whatsapp Contact and it related details.""" # pylint: disable=redefined-builtin # pylint: disable=too-few-public-methods class Address(File): """ Represents a contact address. Args: street (str): The street address. city (str): The ci...
"""This module contains an object that represents a Whatsapp Contact and it related details.""" # pylint: disable=redefined-builtin # pylint: disable=too-few-public-methods class Address(File): """ Represents a contact address. Args: street (str): The street address. city (str): The ci...
validator = AddressValidator(
2
2023-10-15 21:12:45+00:00
4k
caglarkucuk/earthformer-satellite-to-radar
ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer.py
[ { "identifier": "CuboidSelfAttentionPatterns", "path": "ef-sat2rad/earthformer/cuboid_transformer/cuboid_transformer_patterns.py", "snippet": "def full_attention(input_shape):\ndef self_axial(input_shape):\ndef self_video_swin(input_shape, P=2, M=4):\ndef self_divided_space_time(input_shape):\ndef self_...
from typing import Sequence, Union from functools import lru_cache from collections import OrderedDict from torch import nn from einops import rearrange from .cuboid_transformer_patterns import CuboidSelfAttentionPatterns, CuboidCrossAttentionPatterns from .utils import ( get_activation, get_norm_layer, _genera...
3,433
# spatiotemporal learned positional embedding if self.typ == 't+h+w': self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim) self.H_embed = nn.Embedding(num_embeddings=maxH, embedding_dim=embed_dim) self.W_embed = nn.Embedding(num_embeddings=maxW, e...
"""Only change done in this file is the added upsampling layer to the CuboidTransformerModel, which increaes `h` and `w` dimensions of the input tensor by 2x to match the dimensions of the output tensor! The rest is same with the original file from EarthFormer repo! """ """A space-time Transformer with Cuboid Attenti...
self.layer_norm = get_norm_layer(normalization=normalization,
2
2023-10-23 11:45:50+00:00
4k
DTennant/GPC
data/fgvc_aircraft.py
[ { "identifier": "subsample_instances", "path": "data/data_utils.py", "snippet": "def subsample_instances(dataset, prop_indices_to_subsample=0.8):\n\n np.random.seed(0)\n subsample_indices = np.random.choice(range(len(dataset)), replace=False,\n size=(int(pro...
import os import pandas as pd import numpy as np import tarfile from copy import deepcopy from torchvision.datasets.folder import default_loader from torch.utils.data import Dataset from data.data_utils import subsample_instances from config import aircraft_root from six.moves import urllib
2,580
index (int): Index Returns: tuple: (sample, target) where target is class_index of the target class. """ path, target = self.samples[index] sample = self.loader(path) if self.transform is not None: sample = self.transform(sample) if s...
def make_dataset(dir, image_ids, targets): assert(len(image_ids) == len(targets)) images = [] dir = os.path.expanduser(dir) for i in range(len(image_ids)): item = (os.path.join(dir, 'data', 'images', '%s.jpg' % image_ids[i]), targets[i]) images.append(item...
whole_training_set = FGVCAircraft(root=aircraft_root, transform=train_transform, split='trainval')
1
2023-10-23 18:23:22+00:00
4k
camenduru/MiniGPT-v2-hf
minigpt4/models/base_model.py
[ { "identifier": "download_cached_file", "path": "minigpt4/common/dist_utils.py", "snippet": "def download_cached_file(url, check_hash=True, progress=False):\n \"\"\"\n Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again.\n If distributed, only...
import os import logging import contextlib import numpy as np import torch import torch.nn as nn from omegaconf import OmegaConf from transformers import BertTokenizer, LlamaTokenizer from transformers.models.llama.modeling_llama import LlamaForCausalLM from peft import ( LoraConfig, get_peft_model, prepare...
1,732
"""Base class for models.""" def __init__(self): super().__init__() @property def device(self): return list(self.parameters())[-1].device def load_checkpoint(self, url_or_filename): """ Load from a finetuned checkpoint. This should expect no mismatch in th...
""" 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 BaseModel(nn.Module): """Base class for models.""" def __init__(self): ...
visual_encoder = create_eva_vit_g(
4
2023-10-15 19:54:22+00:00
4k
deepghs/sdeval
sdeval/corrupt/aicorrupt.py
[ { "identifier": "load_images", "path": "sdeval/utils/images.py", "snippet": "def _yield_images(images: ImagesTyping) -> Iterator[Image.Image]:\ndef load_images(images: ImagesTyping) -> List[Image.Image]:" }, { "identifier": "tqdm", "path": "sdeval/utils/tqdm_.py", "snippet": "def tqdm(*a...
import json import numpy as np from functools import lru_cache from typing import Tuple, Optional, Mapping from PIL import Image from huggingface_hub import hf_hub_download from imgutils.data import rgb_encode, ImageTyping, load_image from imgutils.utils import open_onnx_model from ..utils import ImagesTyping, load_ima...
1,616
This function downloads and opens the meta information of the AI image corrupted detection model specified by the given model name using Hugging Face Hub. :param model_name: The name of the AI image corrupted detection model. :type model_name: str :return: The opened meta information of the AI image c...
""" Overview: AI image corrupt evaluation metrics. """ _DEFAULT_MODEL_NAME = 'caformer_s36_v0_focal' @lru_cache() def _open_anime_aicop_model(model_name: str): """ Open the AI image corrupted detection model. This function downloads and opens the AI image corrupted detection model specified by the...
for image in tqdm(image_list, silent=self.silent if silent is None else silent, desc=self.tqdm_desc)
1
2023-10-18 03:35:52+00:00
4k
nju-websoft/SCR
framework/dataloader.py
[ { "identifier": "trigger_combine_event", "path": "framework/utils.py", "snippet": "def trigger_combine_event(old_data, new_data):\n if len(new_data) == 0:\n return old_data\n init = False\n res = []\n if len(old_data) == 0:\n init = True\n old_data = copy.deepcopy(new_da...
import torch import os import copy import numpy as np import random import json from torch.utils.data import Dataset, DataLoader from framework.utils import trigger_combine_event, args_combine_event from transformers import BertTokenizer from transformers import logging
3,446
# ner2id self.ner2id = json.load(open(self.data_root+'ner2id.json', 'r')) self.ner2id['None'] = 0 self.id2ner = {} for key, value in self.ner2id.items(): self.id2ner[value] = key # iter self.stream_turn = config.stream_turn self.batch ...
logging.set_verbosity_warning() logging.set_verbosity_error() class ACETriDataset(Dataset): def __init__(self, data): self.data = data def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] def collate_fn(self, data): ...
tr_args_data = args_combine_event([], tr_args_data)
1
2023-10-17 02:40:04+00:00
4k
IBM/VillanDiffusion
caption_dataset.py
[ { "identifier": "Log", "path": "util.py", "snippet": "class Log:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n \n ...
import io import json import os import pathlib import random import shutil import tempfile import traceback import warnings import jsonlines import datasets import numpy as np import requests import torch from random import sample from typing import Callable, List, Tuple, Union from functools import lru_cache, partial ...
2,900
IMAGE = "image" IS_CLEAN = "is_clean" RAW = "raw" LABEL = "label" CAPTION = "caption" RAW_CAPTION = "raw_caption" CAPTION_AUGMENT_KEY: str = "caption_aug" # CAPTION_TOKEN = "caption_token" def __init__(self, name: str, label: int=None, root: str=None, channel: ...
# %% """ Backdoor Poisoned Dataset """ # from tmp_parse_dataset import LaionCoco DEFAULT_VMIN = float(-1.0) DEFAULT_VMAX = float(1.0) class DatasetLoader(object): # Dataset generation mode MODE_FIXED = "FIXED" MODE_FLEX = "FLEX" # Dataset names MNIST = "MNIST" CIFAR10 = "CIFAR10" C...
transforms.Lambda(lambda x: normalize(vmin_in=0, vmax_in=1, vmin_out=self.__vmin, vmax_out=self.__vmax, x=x)),
1
2023-10-17 19:57:37+00:00
4k
WHUlwb/Assisted_learning
train_t.py
[ { "identifier": "Dice_loss", "path": "loss.py", "snippet": "def Dice_loss(inputs, target, beta=1, smooth = 1e-5):\r\n # inputs B, C, H, W, and target B, H, W, C. \r\n # There are C dimensions in total, each dimension representing a class.\r\n n, c, h, w = inputs.size()\r\n nt, ht, wt, ct = t...
import torch import numpy as np import os import torch.nn as nn import metric import time from torch.utils.data import DataLoader from loss import Dice_loss,CE_Loss from torch.autograd import Variable from dataset import MyDataset from config import config from hrnet.hrnet import HRnet from torch.cuda.amp import GradSc...
2,152
scaler = Gradscaler() traindd = MyDataset(config.trainroot,is_training=True) traindata = DataLoader(traindd,batch_size=config.batch_size, shuffle=True) valdata = DataLoader(MyDataset(config.valroot,is_training=False), num_workers=0, batch_size=config.batch_size, shuffle=False) net = HRnet(in_channel=3,num_classes=conf...
scaler = Gradscaler() traindd = MyDataset(config.trainroot,is_training=True) traindata = DataLoader(traindd,batch_size=config.batch_size, shuffle=True) valdata = DataLoader(MyDataset(config.valroot,is_training=False), num_workers=0, batch_size=config.batch_size, shuffle=False) net = HRnet(in_channel=3,num_classes=conf...
dice = Dice_loss(rgbresult,seg)
0
2023-10-17 06:19:02+00:00
4k
dagedarr/telegram-budget
handlers/registration_handler.py
[ { "identifier": "get_by_id", "path": "core/crud.py", "snippet": "async def get_by_id(\n model: ModelType,\n obj_id: int,\n session: AsyncSession\n) -> ModelType:\n \"\"\"\n Получение объекта по ID.\n\n Parameters:\n - model (ModelType): Тип модели SQLAlchemy.\n - obj_id (int): Ид...
from aiogram import F, Router from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, Message from sqlalchemy.ext.asyncio import AsyncSession from core.crud import get_by_id, get_or_create, update from forms import RegistrationForm from keyboards import set_info_keyboard, universal_keyboard ...
1,742
router = Router(name='registration_router') # ------------------------ REGISTRATION ------------------------ @router.callback_query(F.data == 'registration') async def registration(callback: CallbackQuery, session: AsyncSession): """Регистрация пользователя."""
router = Router(name='registration_router') # ------------------------ REGISTRATION ------------------------ @router.callback_query(F.data == 'registration') async def registration(callback: CallbackQuery, session: AsyncSession): """Регистрация пользователя."""
await get_or_create(
1
2023-10-23 17:30:24+00:00
4k
nchen909/Pass-Tuning
evaluator/CodeBLEU/calc_code_bleu.py
[ { "identifier": "bleu", "path": "evaluator/CodeBLEU/bleu.py", "snippet": "def sentence_bleu(\r\n references,\r\n hypothesis,\r\n weights=(0.25, 0.25, 0.25, 0.25),\r\n smoothing_function=None,\r\n auto_reweigh=False,\r\n):\r\ndef corpus_bleu(\r\n list_of_references,\r\n hypotheses,\r...
import argparse import os from evaluator.CodeBLEU import bleu, weighted_ngram_match, syntax_match, dataflow_match from utils import get_lang_by_task
1,902
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # -*- coding:utf-8 -*- # import evaluator.CodeBLEU.weighted_ngram_match # import evaluator.CodeBLEU.syntax_match # import evaluator.CodeBLEU.dataflow_match def get_codebleu(refs, hyp, lang, params='0.25,0.25,0.25,0.25',args=None): if...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # -*- coding:utf-8 -*- # import evaluator.CodeBLEU.weighted_ngram_match # import evaluator.CodeBLEU.syntax_match # import evaluator.CodeBLEU.dataflow_match def get_codebleu(refs, hyp, lang, params='0.25,0.25,0.25,0.25',args=None): if...
args.lang = get_lang_by_task(args.task, args.sub_task)
4
2023-10-20 09:24:44+00:00
4k
openfoodfacts/open-prices
app/tasks.py
[ { "identifier": "crud", "path": "app/crud.py", "snippet": "def get_users_query(filters: ProductFilter | None = None):\ndef get_users(db: Session, filters: ProductFilter | None = None):\ndef get_user(db: Session, user_id: str):\ndef get_user_by_user_id(db: Session, user_id: str):\ndef get_user_by_token(d...
import datetime import tqdm from openfoodfacts import DatasetType, Flavor, ProductDataset from openfoodfacts.types import JSONType from openfoodfacts.utils import get_logger from sqlalchemy import or_, select from sqlalchemy.orm import Session from app import crud from app.models import Product from app.schemas import ...
2,889
logger = get_logger(__name__) # Users # ------------------------------------------------------------------------------ def increment_user_price_count(db: Session, user: UserCreate): crud.increment_user_price_count(db, user=user) # Products # -------------------------------------------------------------------...
logger = get_logger(__name__) # Users # ------------------------------------------------------------------------------ def increment_user_price_count(db: Session, user: UserCreate): crud.increment_user_price_count(db, user=user) # Products # -------------------------------------------------------------------...
for key in OFF_FIELDS:
6
2023-10-21 14:02:15+00:00
4k
krasnoukhov/homeassistant-smart-maic
custom_components/smart_maic/config_flow.py
[ { "identifier": "DEVICE_NAME", "path": "custom_components/smart_maic/const.py", "snippet": "DEVICE_NAME = \"device_name\"" }, { "identifier": "DEVICE_ID", "path": "custom_components/smart_maic/const.py", "snippet": "DEVICE_ID = \"devid\"" }, { "identifier": "DEVICE_TYPE", "pa...
import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from typing import Any from homeassistant import config_entries from homeassistant.components import mqtt from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import AbortFlow from .const import ( ...
1,627
"""Config flow for Smart MAIC integration.""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) USER_SCHEMA = vol.Schema( { vol.Required(IP_ADDRESS): cv.string, vol.Required(PIN): cv.string, vol.Required(DEVICE_NAME, default="Energy"): cv.string, } ) async ...
"""Config flow for Smart MAIC integration.""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) USER_SCHEMA = vol.Schema( { vol.Required(IP_ADDRESS): cv.string, vol.Required(PIN): cv.string, vol.Required(DEVICE_NAME, default="Energy"): cv.string, } ) async ...
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
3
2023-10-16 17:24:45+00:00
4k
JoaoPedro9674/django-ledger
django_ledger/models/customer.py
[ { "identifier": "ContactInfoMixIn", "path": "django_ledger/models/mixins.py", "snippet": "class ContactInfoMixIn(models.Model):\n \"\"\"\n Implements a common set of fields used to document contact information.\n\n Attributes\n ----------\n address_1: str\n A string used to documen...
from uuid import uuid4 from django.core.exceptions import ObjectDoesNotExist from django.db import models, transaction, IntegrityError from django.db.models import Q, F, QuerySet from django.utils.translation import gettext_lazy as _ from django_ledger.models.mixins import ContactInfoMixIn, CreateUpdateMixIn, TaxCollec...
2,326
class CustomerModelQueryset(QuerySet): """ A custom defined QuerySet for the CustomerModel. This implements multiple methods or queries needed to get a filtered QuerySet based on the CustomerModel status. For example, we might want to have list of Customers that are active or hidden. All these sepa...
""" Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement. Contributions to this module: * Miguel Sanda <msanda@arrobalytics.com> * Pranav P Tulshyan <ptulshyan77@gmail.com> A Customer refers to the person or entity that buys product and ...
if isinstance(entity_slug, lazy_loader.get_entity_model()):
3
2023-10-20 01:07:20+00:00
4k
HLTCHKUST/InstructAlign
run_t2t_finetuning.py
[ { "identifier": "load_flores_datasets", "path": "data_utils.py", "snippet": "def load_flores_datasets(pivot_langs=['eng_Latn'], augmentation='multilingual', num_train_ratio=1.0):\n def inject_lang(row, lang1, lang2):\n row['lang1'] = lang_map[lang1]\n row['lang2'] = lang_map[lang2]\n ...
import logging import os import sys import random import numpy as np import pandas as pd import torch import transformers import datasets from dataclasses import dataclass, field from typing import Optional from transformers import ( AutoConfig, AutoModelForSeq2SeqLM, AutoModelForCausalLM, AutoTokenizer...
3,399
"than this will be truncated, sequences shorter will be padded." ) }, ) max_target_length: Optional[int] = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences lon...
#!/usr/bin/env python # coding=utf-8 # Copyright The HuggingFace Team and The HuggingFace Inc. 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.ap...
raw_datasets = load_flores_datasets(pivot_langs=['eng_Latn'], augmentation=data_args.augmentation_type, num_train_ratio=data_args.num_train_ratio)
0
2023-10-24 07:46:05+00:00
4k
acolas1/KGSimple
eval_KGSimp/eval_baselines.py
[ { "identifier": "args", "path": "cli.py", "snippet": "" }, { "identifier": "SaliencyBERTScore", "path": "scoring/saliency_scorer.py", "snippet": "class SaliencyBERTScore:\n def __init__(self, lmscorer = \"bertscore\", lang=\"en\"):\n self.bertscore = evaluate.load(lmscorer)\n ...
import os import sys import logging import random import numpy as np import torch import pandas as pd import stanza import sacrebleu.tokenizers.tokenizer_13a as tok from ast import literal_eval from eval_utils import * from eval_batched import * from cli import args from scoring.saliency_scorer import Sali...
1,745
#### read in result files, format, run eval functions from __future__ import absolute_import from __future__ import division from __future__ import print_function # setting path sys.path.append('../../') sys.path.append('/blue/daisyw/acolas1/KGSimplification/') def eval():
#### read in result files, format, run eval functions from __future__ import absolute_import from __future__ import division from __future__ import print_function # setting path sys.path.append('../../') sys.path.append('/blue/daisyw/acolas1/KGSimplification/') def eval():
eval_mod = args.eval_mod ## model + eval type
0
2023-10-24 13:24:23+00:00
4k
yuanxy92/DANTE
train_electric_optical_kernel.py
[ { "identifier": "train_complex", "path": "optical_layer.py", "snippet": "def train_complex(label_nopad, folder_prefix, epoch, whole_dim, phase_dim, wave_lambda, focal_length, pixel_size, compute_loss_region, factor):\n image = np.zeros((1, whole_dim, whole_dim))\n image[0, whole_dim//2, whole_dim/...
import torch.nn.functional as F import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import os import os.path import time import torch import math import platform import torchsummary import logging import math from optical_layer import train_complex from utils import padding, tile_kernels from impor...
2,523
elif platform.system().lower() == 'linux': server_dir = '/data/xiaoyun/Elec-Opt-D2NN/' os.environ["CUDA_VISIBLE_DEVICES"] = '1' device_cpu = torch.device('cpu') device_gpu = torch.device('cuda:0') model_idx = '3bs' whole_dim = 2000 phase_dim = 1200 wave_lambda = 532e-9 focal_length = 14.5e-2 pixel_size = 8e-6...
# -*- coding: utf-8 -*- ######################################################################## if platform.system().lower() == 'windows': server_dir = './' # os.environ["CUDA_VISIBLE_DEVICES"] = '0' elif platform.system().lower() == 'linux': server_dir = '/data/xiaoyun/Elec-Opt-D2NN/' os.environ["CUD...
folder_fitting, loss = train_complex(psf_to_fit, folder_prefix, train_epoch, whole_dim, phase_dim, wave_lambda, focal_length, pixel_size, compute_loss_region, factor)
0
2023-10-19 10:42:47+00:00
4k
CAMeL-Lab/camel_parser
src/data_preparation.py
[ { "identifier": "ConllParams", "path": "src/classes.py", "snippet": "class ConllParams:\n file_path: str\n parse_model_path: str\n \n def __iter__(self):\n return iter(astuple(self))" }, { "identifier": "TextParams", "path": "src/classes.py", "snippet": "class TextPara...
import re import pandas as pd from typing import List, Union from camel_tools.disambig.common import DisambiguatedWord from src.classes import ConllParams, TextParams, PreprocessedTextParams, TokenizedParams, TokenizedTaggedParams from src.dependency_parser.biaff_parser import parse_conll, parse_text_tuples from src.in...
2,083
FileTypeParams = Union[ConllParams, TextParams, PreprocessedTextParams, TokenizedParams, TokenizedTaggedParams] def get_feats_from_text_tuples(text_tuples: List[List[tuple]]) -> List[List[str]]: """Extract the FEATS columns from the unparsed data. FEATS will exist only for text and pre-processed text input...
FileTypeParams = Union[ConllParams, TextParams, PreprocessedTextParams, TokenizedParams, TokenizedTaggedParams] def get_feats_from_text_tuples(text_tuples: List[List[tuple]]) -> List[List[str]]: """Extract the FEATS columns from the unparsed data. FEATS will exist only for text and pre-processed text input...
token_lines = split_lines_words(lines)
11
2023-10-21 10:39:28+00:00
4k
aiueola/neurips2023-future-dependent-ope
src/ope/value_based.py
[ { "identifier": "DiscreteStateLSTMVfunction", "path": "src/ope/v_func.py", "snippet": "class DiscreteStateLSTMVfunction(nn.Module):\n def __init__(\n self,\n n_states: int = 500,\n n_actions: int = 6,\n memory_length: int = 0,\n future_length: int = 0,\n lstm...
from dataclasses import dataclass from typing import Tuple, Optional, Union from torch import optim from sklearn.utils import check_random_state from policy.policy import BasePolicy from .v_func import DiscreteStateLSTMVfunction, ContinuousStateLSTMVfunction from .base import BaseNeuralValueBasedOffPolicyEstimator from...
3,512
"""Value-Based Estimator.""" @dataclass class NeuralFutureDependentValueBasedOPE(BaseNeuralValueBasedOffPolicyEstimator): behavior_policy: BasePolicy evaluation_policy: BasePolicy
"""Value-Based Estimator.""" @dataclass class NeuralFutureDependentValueBasedOPE(BaseNeuralValueBasedOffPolicyEstimator): behavior_policy: BasePolicy evaluation_policy: BasePolicy
v_function: Union[DiscreteStateLSTMVfunction, ContinuousStateLSTMVfunction]
0
2023-10-24 06:09:37+00:00
4k
JerBouma/FinancePortfolio
financeportfolio/portfolio_controller.py
[ { "identifier": "excel_model", "path": "financeportfolio/excel_model.py", "snippet": "def create_portfolio_performance_excel_report(\n writer: pd.ExcelWriter, dataset: pd.DataFrame, sheet_name: str, currency: str = \"$\"\n):\ndef create_transactions_performance_excel_report(\n writer: pd.ExcelWrit...
import pandas as pd from financetoolkit import Toolkit from financeportfolio import excel_model, helpers, portfolio_model
3,123
Returns: DataFrame: A DataFrame containing transaction performance metrics. Raises: ValueError: If an invalid or unsupported period_string is provided. """ if self._daily_historical_data.empty: try: self.collect_historical_da...
"""Portfolio Module""" # pylint: disable=too-many-instance-attributes,abstract-class-instantiated, # pylint: disable=too-few-public-methods,protected-access,too-many-lines class Portfolio: """ A class for managing and analyzing your portfolio. This class provides functionality for loadin...
excel_model.create_portfolio_overview_excel_report(
0
2023-10-15 09:16:04+00:00
4k
gschramm/2023-MIC-ImageRecon-Shortcourse
07_osem_varnet_evaluation.py
[ { "identifier": "EMUpdateModule", "path": "layers.py", "snippet": "class EMUpdateModule(torch.nn.Module):\n\n def __init__(\n self,\n projector: parallelproj.LinearOperator,\n ) -> None:\n\n super().__init__()\n self._projector = projector\n\n self._fwd_op_layer ...
import argparse import json import utils import parallelproj import array_api_compat.torch as torch import array_api_compat.numpy as np import pymirc.viewer as pv from layers import EMUpdateModule from models import Unet3D, SimpleOSEMVarNet, PostReconNet from data import load_brain_image_batch, simulate_data_batch from...
3,351
"""minimal script that evaluates trained OSEM varnets """ from __future__ import annotations parser = argparse.ArgumentParser(description='OSEM-VARNet evaluation') parser.add_argument('--run_dir') parser.add_argument('--sens', type=float, default=1) args = parser.parse_args() run_dir = Path(args.run_dir) sens =...
"""minimal script that evaluates trained OSEM varnets """ from __future__ import annotations parser = argparse.ArgumentParser(description='OSEM-VARNet evaluation') parser.add_argument('--run_dir') parser.add_argument('--sens', type=float, default=1) args = parser.parse_args() run_dir = Path(args.run_dir) sens =...
emission_image_database, attenuation_image_database = load_brain_image_batch(
4
2023-10-16 07:18:26+00:00
4k
ZiaWang/jqtrade
jqtrade/account/api.py
[ { "identifier": "InvalidParam", "path": "jqtrade/common/exceptions.py", "snippet": "class InvalidParam(UserError):\n \"\"\" 用户参数错误 \"\"\"\n pass" }, { "identifier": "sys_logger", "path": "jqtrade/common/log.py", "snippet": "class SystemLogFormatter(logging.Formatter):\n class Co...
from ..common.exceptions import InvalidParam from ..common.log import sys_logger from ..scheduler.context import Context from .order import OrderSide, OrderStatus, OrderStyle, MarketOrderStyle, LimitOrderStyle from .position import Position
2,969
# -*- coding: utf-8 -*- logger = sys_logger.getChild("account.api") def _check_code(code): if not (code[-4:] in ("XSHE", "XSHG") and code[:-5].isdigit()): raise InvalidParam(f"标的代码错误: {code}") def _check_amount(amount): if not isinstance(amount, int) or amount == 0: raise InvalidParam(f"委...
# -*- coding: utf-8 -*- logger = sys_logger.getChild("account.api") def _check_code(code): if not (code[-4:] in ("XSHE", "XSHG") and code[:-5].isdigit()): raise InvalidParam(f"标的代码错误: {code}") def _check_amount(amount): if not isinstance(amount, int) or amount == 0: raise InvalidParam(f"委...
ctx = Context.get_instance()
2
2023-10-24 01:34:27+00:00
4k
Glasgow-AI4BioMed/GenKIE
data/pretrain_data/unify_dataset.py
[ { "identifier": "data_utils", "path": "data/data_utils.py", "snippet": "def infer_language_pair(path):\ndef collate_tokens(\n values,\n pad_idx,\n eos_idx=None,\n left_pad=False,\n move_eos_to_beginning=False,\n pad_to_length=None,\n pad_to_multiple=1,\n pad_to_bsz=None,\n):\n ...
from io import BytesIO from torchvision import transforms from PIL import Image, ImageFile from data import data_utils from data.ofa_dataset import OFADataset from utils.vision_helper import RandomAugment import math import logging import random import warnings import numpy as np import torch import base64 import utils...
2,902
batch = { "id": id, "nsentences": len(samples), "ntokens": ntokens, "net_input": { "src_tokens": src_tokens, "src_lengths": src_lengths, "patch_images": patch_images, "patch_masks": patch_masks, "code_masks": code_masks, ...
# Copyright 2022 The OFA-Sys Team. # All rights reserved. # This source code is licensed under the Apache 2.0 license # found in the LICENSE file in the root directory. ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.MAX_IMAGE_PIXELS = None Image.MAX_IMAGE_PIXELS = None logger = logging.getLogger(__name__) warn...
RandomAugment(2, 7, isPIL=True, augs=['Identity', 'AutoContrast', 'Equalize', 'Brightness', 'Sharpness',
2
2023-10-20 20:01:42+00:00
4k
ArnaudParant/sel
tests/test_parser_n_formator.py
[ { "identifier": "query_string_parser", "path": "sel/query_string_parser.py", "snippet": "AGGREG_TYPES = [\"aggreg\", \"histogram\", \"count\", \"distinct\", \"min\", \"max\", \"sum\", \"average\", \"stats\"]\nAGGREG_PARAMETER_MAPPING = {\n \"subaggreg\": None,\n \"interval\": None,\n \"size\": ...
import json import pytest import traceback from sel import query_string_parser from sel.query_string_parser import ( Value, QueryString, Comparator, Not, RangeFilter, Filter, Context, Aggreg, Sort, Group, NoBracketGroup, Query ) from sel import query_object_formator
1,743
class TestParserNFormator: @pytest.mark.parametrize(["query", "expected"], [ ["toto", "toto"], ['"toto tata titi"', "toto tata titi"], ["toto tata titi", None], # Exception, does not match type Value ]) def test_value(self, query, expected): try:
class TestParserNFormator: @pytest.mark.parametrize(["query", "expected"], [ ["toto", "toto"], ['"toto tata titi"', "toto tata titi"], ["toto tata titi", None], # Exception, does not match type Value ]) def test_value(self, query, expected): try:
res = query_string_parser.parse(query, grammar=Value)
0
2023-10-16 09:03:13+00:00
4k
Qualcomm-AI-research/outlier-free-transformers
quantization/autoquant_utils.py
[ { "identifier": "FP32Acts", "path": "quantization/base_quantized_classes.py", "snippet": "class FP32Acts(nn.Module):\n def forward(self, x):\n return x\n\n def reset_ranges(self):\n pass" }, { "identifier": "QuantizedActivation", "path": "quantization/base_quantized_class...
import copy import warnings from torch import nn from torch.nn import functional as F from torch.nn.modules.pooling import _AdaptiveAvgPoolNd, _AvgPoolNd from quantization.base_quantized_classes import ( FP32Acts, QuantizedActivation, QuantizedModule, ) from quantization.hijacker import QuantizationHijacker...
3,541
def run_forward(self, x, weight, bias, offsets=None): return F.layer_norm( input=x.contiguous(), normalized_shape=self.normalized_shape, weight=weight.contiguous(), bias=bias.contiguous(), eps=self.eps, ) class QuantEmbedding(Quantization...
# Copyright (c) 2023 Qualcomm Technologies, Inc. # All Rights Reserved. class QuantLinear(QuantizationHijacker, nn.Linear): def run_forward(self, x, weight, bias, offsets=None): return F.linear(x.contiguous(), weight.contiguous(), bias=bias) class QuantizedActivationWrapper(QuantizedActivation): "...
if isinstance(model[i], QuantizedModule):
2
2023-10-23 15:59:50+00:00
4k
QgZhan/ESVAE
main_snn_ae.py
[ { "identifier": "aboutCudaDevices", "path": "utils.py", "snippet": "class aboutCudaDevices():\r\n def __init__(self):\r\n pass\r\n\r\n def num_devices(self):\r\n \"\"\"Return number of devices connected.\"\"\"\r\n return cuda.Device.count()\r\n\r\n def devices(self):\r\n ...
import os import os.path import numpy as np import logging import argparse import pycuda.driver as cuda import torch import torchvision import svae_models.sae as sae from torch.utils.tensorboard import SummaryWriter from utils import aboutCudaDevices from utils import AverageMeter from utils import aboutCud...
1,921
max_accuracy = 0 min_loss = 1000 def train(network, trainloader, opti, epoch, n_step): loss_meter = AverageMeter() network = network.train() for batch_idx, (real_img, label) in enumerate(trainloader): opti.zero_grad() real_img = real_img.to(device) ...
max_accuracy = 0 min_loss = 1000 def train(network, trainloader, opti, epoch, n_step): loss_meter = AverageMeter() network = network.train() for batch_idx, (real_img, label) in enumerate(trainloader): opti.zero_grad() real_img = real_img.to(device) ...
train_loader, test_loader = load_dataset_snn.load_mnist(data_path, args.batch_size, input_size, True)
3
2023-10-23 07:33:27+00:00
4k
iesl/softmax_CPR_recommend
run_hyper.py
[ { "identifier": "HyperTuning", "path": "recbole/trainer/hyper_tuning.py", "snippet": "class HyperTuning(object):\n r\"\"\"HyperTuning Class is used to manage the parameter tuning process of recommender system models.\n Given objective funciton, parameters range and optimization algorithm, using Hy...
import argparse from recbole.trainer import HyperTuning from recbole.quick_start import objective_function
2,441
# -*- coding: utf-8 -*- # @Time : 2020/7/24 15:57 # @Author : Shanlei Mu # @Email : slmu@ruc.edu.cn # @File : run_hyper.py # UPDATE: # @Time : 2020/8/20 21:17, 2020/8/29 # @Author : Zihan Lin, Yupeng Hou # @Email : linzihan.super@foxmail.com, houyupeng@ruc.edu.cn def main(): parser = argparse.ArgumentPa...
# -*- coding: utf-8 -*- # @Time : 2020/7/24 15:57 # @Author : Shanlei Mu # @Email : slmu@ruc.edu.cn # @File : run_hyper.py # UPDATE: # @Time : 2020/8/20 21:17, 2020/8/29 # @Author : Zihan Lin, Yupeng Hou # @Email : linzihan.super@foxmail.com, houyupeng@ruc.edu.cn def main(): parser = argparse.ArgumentPa...
hp = HyperTuning(objective_function, algo='exhaustive',
1
2023-10-21 16:31:44+00:00
4k
timapage/pyqt6-yolov8
src/models/tracking/deep_sort/deep_sort.py
[ { "identifier": "Extractor", "path": "src/models/tracking/deep_sort/deep/feature_extractor.py", "snippet": "class Extractor(object):\n def __init__(self, model_path, use_cuda=True):\n self.net = Net(reid=True)\n self.device = \"cuda\" if torch.cuda.is_available() and use_cuda else \"cpu...
import numpy as np import torch from .deep.feature_extractor import Extractor from .sort.nn_matching import NearestNeighborDistanceMetric from .sort.detection import Detection from .sort.tracker import Tracker
2,484
__all__ = ['DeepSort'] class DeepSort(object): def __init__(self, model_path, max_dist=0.2, max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=100, use_cuda=True): self.extractor = Extractor(model_path, use_cuda=use_cuda) max_cosine_distance = max_dist nn_budget = 100
__all__ = ['DeepSort'] class DeepSort(object): def __init__(self, model_path, max_dist=0.2, max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=100, use_cuda=True): self.extractor = Extractor(model_path, use_cuda=use_cuda) max_cosine_distance = max_dist nn_budget = 100
metric = NearestNeighborDistanceMetric(
1
2023-10-18 09:21:01+00:00
4k
OthersideAI/self-operating-computer
operate/dialog.py
[ { "identifier": "ModelNotRecognizedException", "path": "operate/exceptions.py", "snippet": "class ModelNotRecognizedException(Exception):\n \"\"\"Exception raised for unrecognized models.\n\n Attributes:\n model -- the unrecognized model\n message -- explanation of the error\n \"\...
import sys import os import platform import asyncio from prompt_toolkit.shortcuts import message_dialog from prompt_toolkit import prompt from operate.exceptions import ModelNotRecognizedException from operate.prompts import USER_QUESTION from operate.settings import Config from operate.utils.style import ( ANSI_GR...
2,962
# Load configuration config = Config() def main(model, terminal_prompt, voice_mode=False): """ Main function for the Self-Operating Computer. Parameters: - model: The model used for generating responses. - terminal_prompt: A string representing the prompt provided in the terminal. - voice_mo...
# Load configuration config = Config() def main(model, terminal_prompt, voice_mode=False): """ Main function for the Self-Operating Computer. Parameters: - model: The model used for generating responses. - terminal_prompt: A string representing the prompt provided in the terminal. - voice_mo...
f"{ANSI_GREEN}[Self-Operating Computer]{ANSI_BLUE} Objective complete {ANSI_RESET}"
3
2023-11-04 03:13:45+00:00
4k
netease-youdao/EmotiVoice
demo_page_databaker.py
[ { "identifier": "g2p_cn_en", "path": "frontend.py", "snippet": "def g2p_cn_en(text, g2p, lexicon):\ndef contains_chinese(text):" }, { "identifier": "JETSGenerator", "path": "models/prompt_tts_modified/jets.py", "snippet": "class JETSGenerator(nn.Module):\n def __init__(self, config) -...
import streamlit as st import os, glob import numpy as np import torch import re import base64 from yacs import config as CONFIG from frontend import g2p_cn_en, ROOT_DIR, read_lexicon, G2p from exp.DataBaker.config.config import Config from models.prompt_tts_modified.jets import JETSGenerator from models.prompt_tts_mod...
1,692
# Copyright 2023, YOUDAO # # 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 law or agreed to in writing, s...
# Copyright 2023, YOUDAO # # 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 law or agreed to in writing, s...
generator = JETSGenerator(conf).to(DEVICE)
1
2023-11-08 10:15:27+00:00
4k
daveshap/OpenAI_Agent_Swarm
agents/tool_maker/unit_manager.py
[ { "identifier": "AssistantManager", "path": "agents/tool_maker/assistant_manager.py", "snippet": "class AssistantManager:\n\n def __init__(self, client):\n self.client = client\n self.assistant = None\n self.agent_builder = AgentBuilder(client=self.client)\n Path(__file__)...
from agents.tool_maker.assistant_manager import AssistantManager from agents.tool_maker.chat_manager import ChatManager from shared.openai_config import get_openai_client
2,723
class Unit: """ A class which creates and exposes chat functionality for a Unit Agent. A Unit is a first prototype for a Minmium Viable Agent (MVA). A `Unit` is two `Assistant`s in a symbiotic relationship. One `Assistant` is the Interface with a thread sharing input with the contents passed via ...
class Unit: """ A class which creates and exposes chat functionality for a Unit Agent. A Unit is a first prototype for a Minmium Viable Agent (MVA). A `Unit` is two `Assistant`s in a symbiotic relationship. One `Assistant` is the Interface with a thread sharing input with the contents passed via ...
self.chat_manager = ChatManager(client=client)
1
2023-11-07 23:12:05+00:00
4k
S-LoRA/S-LoRA
slora/models/llama/layer_infer/post_layer_infer.py
[ { "identifier": "LlamaPreAndPostLayerWeight", "path": "slora/models/llama/layer_weights/pre_and_post_layer_weight.py", "snippet": "class LlamaPreAndPostLayerWeight(PreAndPostLayerWeight):\n def __init__(self, tp_rank, world_size, data_type, network_config, mode):\n super().__init__(tp_rank, wo...
import torch import torch.functional as F import torch.distributed as dist import numpy as np from slora.models.llama.layer_weights.pre_and_post_layer_weight import LlamaPreAndPostLayerWeight from einops import rearrange from slora.models.llama.infer_struct import LlamaInferStateInfo from slora.models.llama.triton_kern...
1,649
class LlamaPostLayerInfer(PostLayerInferTpl): """ """ def __init__(self, tp_rank, world_size, network_config, mode): super().__init__(tp_rank, world_size, network_config, mode) self.eps_ = network_config["rms_norm_eps"] self.vocab_size_ = network_config["vocab_size"] self....
class LlamaPostLayerInfer(PostLayerInferTpl): """ """ def __init__(self, tp_rank, world_size, network_config, mode): super().__init__(tp_rank, world_size, network_config, mode) self.eps_ = network_config["rms_norm_eps"] self.vocab_size_ = network_config["vocab_size"] self....
def _norm(self, input, infer_state, layer_weight:LlamaPreAndPostLayerWeight) -> torch.Tensor:
0
2023-11-05 04:08:36+00:00
4k
Yuliang-Liu/Monkey
data_generation/grit/grit/modeling/backbone/vit.py
[ { "identifier": "PatchEmbed", "path": "data_generation/grit/grit/modeling/backbone/utils.py", "snippet": "class PatchEmbed(nn.Module):\n \"\"\"\n Image to Patch Embedding.\n \"\"\"\n\n def __init__(\n self, kernel_size=(16, 16), stride=(16, 16), padding=(0, 0), in_chans=3, embed_dim=7...
import logging import math import fvcore.nn.weight_init as weight_init import torch import torch.nn as nn import sys import torch.utils.checkpoint as checkpoint from functools import partial from detectron2.layers import CNNBlockBase, Conv2d, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY fro...
3,506
bottleneck_channels, norm="LN", act_layer=nn.GELU, ): """ Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. bottleneck_channels (int): number of output channels for the 3x3 "bo...
# Modified by Jialian Wu from https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py sys.path.insert(0, 'models/grit_src/third_party/CenterNet2/projects/CenterNet2/') logger = logging.getLogger(__name__) __all__ = ["ViT"] class Attention(nn.Module): """Multi-head Attent...
x, pad_hw = window_partition(x, self.window_size)
3
2023-11-09 14:31:48+00:00
4k
disler/multi-agent-postgres-data-analytics
postgres_da_ai_agent/agents/agents.py
[ { "identifier": "PostgresAgentInstruments", "path": "postgres_da_ai_agent/agents/instruments.py", "snippet": "class PostgresAgentInstruments(AgentInstruments):\n \"\"\"\n Unified Toolset for the Postgres Data Analytics Multi-Agent System\n\n Advantages:\n - All agents have access to the ...
from typing import Optional, List, Dict, Any from postgres_da_ai_agent.agents.instruments import PostgresAgentInstruments from postgres_da_ai_agent.modules import orchestrator from postgres_da_ai_agent.agents import agent_config import autogen import guidance
3,173
sr_data_analyst = autogen.AssistantAgent( name="Sr_Data_Analyst", llm_config=agent_config.run_sql_config, system_message=SR_DATA_ANALYST_PROMPT, code_execution_config=False, human_input_mode="NEVER", function_map={ "run_sql": instruments.run_sql, }...
# ------------------------ PROMPTS ------------------------ USER_PROXY_PROMPT = "A human admin. Interact with the Product Manager to discuss the plan. Plan execution needs to be approved by this admin." DATA_ENGINEER_PROMPT = "A Data Engineer. Generate the initial SQL based on the requirements provided. Send it to t...
) -> orchestrator.Orchestrator:
1
2023-11-04 20:15:46+00:00
4k
OpenBMB/ProAgent
ProAgent/running_recorder.py
[ { "identifier": "CONFIG", "path": "ProAgent/config.py", "snippet": "CONFIG = RPAgentConfig.get_default_config()" }, { "identifier": "ENVIRONMENT", "path": "ProAgent/router/utils.py", "snippet": "class ENVIRONMENT(Enum):\n '''\n 决定了 record cache 的访问形式\n - Development:不访问缓存,从头开始\n...
import os import time import json from colorama import Fore from termcolor import colored from ProAgent.config import CONFIG from ProAgent.router.utils import ENVIRONMENT from ProAgent.utils import Action from ProAgent.loggers.logs import logger
2,556
Fore.RED, record_dir, ) self.newly_start = False for dir_name in os.listdir(record_dir): if dir_name == "LLM_inout_pair": inout_pair_list = os.listdir(os.path.join(record_dir,dir_name)) inout_pair_list.sort() for...
def dump_common_things(object): """ Generates a function comment for the given function body. Args: object: The object to be processed. Returns: The processed object. """ if type(object) in [str,int,float, bool]: return object if type(object) == dict: ...
def regist_tool_call(self, action: Action, now_code: str):
2
2023-11-03 01:20:14+00:00
4k
LLaVA-VL/LLaVA-Plus-Codebase
llava/eval/run_llava.py
[ { "identifier": "IMAGE_TOKEN_INDEX", "path": "llava/constants.py", "snippet": "IMAGE_TOKEN_INDEX = -200" }, { "identifier": "DEFAULT_IMAGE_TOKEN", "path": "llava/constants.py", "snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\"" }, { "identifier": "DEFAULT_IM_START_TOKEN", "path":...
import argparse import torch import requests import re from llava.constants import ( IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_PLACEHOLDER, ) from llava.conversation import conv_templates, SeparatorStyle from llava.model.builder import load_pretraine...
3,462
def image_parser(args): out = args.image_file.split(args.sep) return out def load_image(image_file): if image_file.startswith("http") or image_file.startswith("https"): response = requests.get(image_file) image = Image.open(BytesIO(response.content)).convert("RGB") else: i...
def image_parser(args): out = args.image_file.split(args.sep) return out def load_image(image_file): if image_file.startswith("http") or image_file.startswith("https"): response = requests.get(image_file) image = Image.open(BytesIO(response.content)).convert("RGB") else: i...
image_token_se = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
1
2023-11-07 13:06:02+00:00
4k
opendilab/LLMRiddles
llmriddles/questions/level4.py
[ { "identifier": "register_question", "path": "llmriddles/questions/question.py", "snippet": "def register_question(text: Union[Mapping[str, str], str],\n checkers: Union[Mapping[str, SingleLangCheckerTyping], MultiLangCheckerTyping],\n name=Union[Mapping[str, st...
import re from .question import register_question from .question import Checker from typing import Callable from .utility import count_words, word_reverse_text from .math_tools import check_if_is_number, get_all_numbers
1,743
CN_TEXT_1 = """ 第四章第一题(循环往复),请构造一个问题A,它的回复是不同于A的B,然后以B提问能再次得到A。 请在下面的输入框内填写你构造并点击按钮提交。 """ EN_TEXT_1 = """ For the first question in chapter 4, please make a question A whose answer is B that is different from A, and then ask B to get A again. Please enter your query below and click the submit button ...
CN_TEXT_1 = """ 第四章第一题(循环往复),请构造一个问题A,它的回复是不同于A的B,然后以B提问能再次得到A。 请在下面的输入框内填写你构造并点击按钮提交。 """ EN_TEXT_1 = """ For the first question in chapter 4, please make a question A whose answer is B that is different from A, and then ask B to get A again. Please enter your query below and click the submit button ...
if not check_if_is_number(user_text):
4
2023-11-07 03:09:55+00:00
4k