Datasets:
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 |
|---|---|---|---|---|---|---|---|---|---|---|
DLYuanGod/TinyGPT-V | minigpt4/processors/blip_processors.py | [
{
"identifier": "registry",
"path": "minigpt4/common/registry.py",
"snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_task(cls, name):\n def wrap(task_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def ... | import re
from minigpt4.common.registry import registry
from minigpt4.processors.base_processor import BaseProcessor
from minigpt4.processors.randaugment import RandomAugment
from omegaconf import OmegaConf
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode | 756 | """
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
"""
| """
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 BlipImageBaseProcessor(BaseProcessor): | 1 | 2023-12-28 05:47:18+00:00 | 2k |
jianchang512/vocal-separate | start.py | [
{
"identifier": "cfg",
"path": "vocal/cfg.py",
"snippet": "LANG = \"en\" if locale.getdefaultlocale()[0].split('_')[0].lower() != 'zh' else \"zh\"\nROOT_DIR = os.getcwd()\nMODEL_DIR = os.path.join(ROOT_DIR, 'pretrained_models')\nSTATIC_DIR = os.path.join(ROOT_DIR, 'static')\nTMP_DIR = os.path.join(STATI... | import logging
import threading
import sys
import os
import subprocess
from flask import Flask, request, render_template, jsonify, send_from_directory
from gevent.pywsgi import WSGIServer, WSGIHandler,LoggingLogAdapter
from logging.handlers import RotatingFileHandler
from vocal import cfg, tool
from vocal.cfg import RO... | 795 |
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static',
template_folder=o... |
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'static'), static_url_path='/static',
template_folder=o... | rs = tool.runffmpeg(params) | 1 | 2023-12-26 06:20:35+00:00 | 2k |
ali-vilab/dreamtalk | core/networks/dynamic_fc_decoder.py | [
{
"identifier": "_get_activation_fn",
"path": "core/networks/transformer.py",
"snippet": "def _get_activation_fn(activation):\r\n \"\"\"Return an activation function given a string\"\"\"\r\n if activation == \"relu\":\r\n return F.relu\r\n if activation == \"gelu\":\r\n return F.g... | import torch.nn as nn
import torch
from core.networks.transformer import _get_activation_fn, _get_clones
from core.networks.dynamic_linear import DynamicLinear | 1,476 |
class DynamicFCDecoderLayer(nn.Module):
def __init__(
self,
d_model,
nhead,
d_style,
dynamic_K,
dynamic_ratio,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
):
super().__init__()
se... |
class DynamicFCDecoderLayer(nn.Module):
def __init__(
self,
d_model,
nhead,
d_style,
dynamic_K,
dynamic_ratio,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
):
super().__init__()
se... | self.layers = _get_clones(decoder_layer, num_layers) | 1 | 2023-12-28 05:39:31+00:00 | 2k |
jiawei-ren/dreamgaussian4d | diffusers/src/diffusers/models/activations.py | [
{
"identifier": "USE_PEFT_BACKEND",
"path": "diffusers/src/diffusers/utils/constants.py",
"snippet": "USE_PEFT_BACKEND = _required_peft_version and _required_transformers_version"
},
{
"identifier": "LoRACompatibleLinear",
"path": "diffusers/src/diffusers/models/lora.py",
"snippet": "cla... | import torch
import torch.nn.functional as F
from torch import nn
from ..utils import USE_PEFT_BACKEND
from .lora import LoRACompatibleLinear | 1,423 | # coding=utf-8
# Copyright 2023 HuggingFace Inc.
#
# 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 ag... | # coding=utf-8
# Copyright 2023 HuggingFace Inc.
#
# 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 ag... | linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear | 1 | 2023-12-28 08:17:40+00:00 | 2k |
Meituan-AutoML/MobileVLM | mobilevlm/model/mobilevlm.py | [
{
"identifier": "build_vision_tower",
"path": "mobilevlm/model/vision_encoder.py",
"snippet": "def build_vision_tower(model_cfg, **kwargs):\n vision_tower = getattr(model_cfg, 'mm_vision_tower', getattr(model_cfg, 'vision_tower', None))\n is_absolute_path_exists = os.path.exists(vision_tower)\n ... | import torch
import torch.nn as nn
from abc import ABC, abstractmethod
from transformers import AutoTokenizer, BitsAndBytesConfig
from mobilevlm.model.vision_encoder import build_vision_tower
from mobilevlm.model.vision_projector import build_vision_projector
from mobilevlm.constants import IGNORE_INDEX, IMAGE_TOKEN_IN... | 1,423 |
class MobileVLMMetaModel:
def __init__(self, config):
super(MobileVLMMetaModel, self).__init__(config)
if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=False)
self.mm_projector = build_vision_projector(config)
def get_... |
class MobileVLMMetaModel:
def __init__(self, config):
super(MobileVLMMetaModel, self).__init__(config)
if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=False)
self.mm_projector = build_vision_projector(config)
def get_... | if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0: | 3 | 2023-12-29 03:35:49+00:00 | 2k |
kinggongzilla/ai-clone-whatsapp | utils/config_utils.py | [
{
"identifier": "datasets",
"path": "configs/datasets.py",
"snippet": "class custom_dataset:"
},
{
"identifier": "lora_config",
"path": "configs/peft.py",
"snippet": "class lora_config:\n r: int=8\n lora_alpha: int=32\n target_modules: List[str] = field(default_factory=lambda... | import inspect
import torch.distributed as dist
from dataclasses import asdict
from torch.utils.data import DistributedSampler
from peft import (
LoraConfig,
AdaptionPromptConfig,
PrefixTuningConfig,
)
from transformers import default_data_collator
from transformers.data import DataCollatorForSeq2Seq
from c... | 1,507 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
def update_config(config, **kwargs):
if isinstance(config, (tuple, list)):
for c in config:
update_config(c, **kwargs)
else... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
def update_config(config, **kwargs):
if isinstance(config, (tuple, list)):
for c in config:
update_config(c, **kwargs)
else... | configs = (lora_config, llama_adapter_config, prefix_config) | 1 | 2023-12-28 00:02:08+00:00 | 2k |
FoundationVision/UniRef | projects/UniRef/uniref/models/deformable_detr/matcher.py | [
{
"identifier": "box_cxcywh_to_xyxy",
"path": "projects/UniRef/uniref/util/box_ops.py",
"snippet": "def box_cxcywh_to_xyxy(x):\n # print('box:\\n', x)\n\n x_c, y_c, w, h = x.unbind(-1)\n b = [(x_c - 0.5 * w), (y_c - 0.5 * h),\n (x_c + 0.5 * w), (y_c + 0.5 * h)]\n return torch.stack(b... | import torch
import torch.nn.functional as F
import torchvision.ops as ops
from scipy.optimize import linear_sum_assignment
from torch import nn
from ...util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou | 1,206 | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... | # ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... | cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(bz_boxes), box_cxcywh_to_xyxy(bz_gtboxs)) | 1 | 2023-12-22 13:31:33+00:00 | 2k |
xhuangcv/humannorm | threestudio/models/materials/neural_radiance_material.py | [
{
"identifier": "BaseMaterial",
"path": "threestudio/models/materials/base.py",
"snippet": "class BaseMaterial(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n requires_normal: bool = False\n requires_tangent: bool = False\n\n def configure(s... | import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import threestudio
from dataclasses import dataclass, field
from threestudio.models.materials.base import BaseMaterial
from threestudio.models.networks import get_encoding, get_mlp
from threestudio.utils.ops import dot, get_activation
from... | 1,149 |
@threestudio.register("neural-radiance-material")
class NeuralRadianceMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
input_feature_dims: int = 8
color_activation: str = "sigmoid"
dir_encoding_config: dict = field(
default_factory=lambda: {"otype": "... |
@threestudio.register("neural-radiance-material")
class NeuralRadianceMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
input_feature_dims: int = 8
color_activation: str = "sigmoid"
dir_encoding_config: dict = field(
default_factory=lambda: {"otype": "... | self.encoding = get_encoding(3, self.cfg.dir_encoding_config) | 1 | 2023-12-23 12:37:48+00:00 | 2k |
jianchang512/stt | start.py | [
{
"identifier": "cfg",
"path": "stslib/cfg.py",
"snippet": "LANG = \"en\" if locale.getdefaultlocale()[0].split('_')[0].lower() != 'zh' else \"zh\"\nROOT_DIR = os.getcwd()\nMODEL_DIR = os.path.join(ROOT_DIR, 'models')\nSTATIC_DIR = os.path.join(ROOT_DIR, 'static')\nTMP_DIR = os.path.join(STATIC_DIR, 'tm... | import logging
import re
import threading
import sys
import torch
import os
from flask import Flask, request, render_template, jsonify, send_from_directory
from gevent.pywsgi import WSGIServer, WSGIHandler, LoggingLogAdapter
from logging.handlers import RotatingFileHandler
from stslib import cfg, tool
from stslib.cfg i... | 836 |
device = "cuda" if torch.cuda.is_available() else "cpu"
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 配置日志
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'st... |
device = "cuda" if torch.cuda.is_available() else "cpu"
class CustomRequestHandler(WSGIHandler):
def log_request(self):
pass
# 配置日志
# 禁用 Werkzeug 默认的日志处理器
log = logging.getLogger('werkzeug')
log.handlers[:] = []
log.setLevel(logging.WARNING)
app = Flask(__name__, static_folder=os.path.join(ROOT_DIR, 'st... | rs = tool.runffmpeg(params) | 1 | 2023-12-28 16:02:55+00:00 | 2k |
jesenzhang/ComfyUI_StreamDiffusion | streamdiffusion/pipeline.py | [
{
"identifier": "SimilarImageFilter",
"path": "streamdiffusion/image_filter.py",
"snippet": "class SimilarImageFilter:\n def __init__(self, threshold: float = 0.98, max_skip_frame: float = 10) -> None:\n self.threshold = threshold\n self.prev_tensor = None\n self.cos = torch.nn.C... | import time
import numpy as np
import PIL.Image
import torch
from typing import List, Optional, Union, Any, Dict, Tuple, Literal
from diffusers import LCMScheduler, StableDiffusionPipeline
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img... | 1,162 |
class StreamDiffusion:
def __init__(
self,
pipe: StableDiffusionPipeline,
t_index_list: List[int],
torch_dtype: torch.dtype = torch.float16,
width: int = 512,
height: int = 512,
do_add_noise: bool = True,
use_denoising_batch: bool = True,
f... |
class StreamDiffusion:
def __init__(
self,
pipe: StableDiffusionPipeline,
t_index_list: List[int],
torch_dtype: torch.dtype = torch.float16,
width: int = 512,
height: int = 512,
do_add_noise: bool = True,
use_denoising_batch: bool = True,
f... | self.similar_filter = SimilarImageFilter() | 0 | 2023-12-29 09:00:03+00:00 | 2k |
neobundy/MLX-Stable-Diffusion-WebUI | model_inspector.py | [
{
"identifier": "PathConfig",
"path": "stable_diffusion/config.py",
"snippet": "class DiffuserModelPathConfig:\nclass BaseConfig:\nclass AutoencoderConfig(BaseConfig):\nclass CLIPTextModelConfig(BaseConfig):\nclass UNetConfig(BaseConfig):\nclass DiffusionConfig(BaseConfig):\n def __init__(self, model... | from stable_diffusion.config import PathConfig
from stable_diffusion.model_io import preload_models_from_safetensor_weights
from utils import _state_dict
from utils import get_state_dict_from_safetensor | 1,090 |
INSPECTION_FILE = "model_inspection.txt"
NUM_ITEMS = 100
MODEL_FILE = "./models/v2-1_512-ema-pruned.safetensors"
MODEL_FILE1 = "./unet/diffusion_pytorch_model_test.safetensors"
MODEL_FILE2 = "./unet/xxmix9realistic_v40.safetensors"
# Recreate the inspection file at every execution of the script
with open(INSPECTI... |
INSPECTION_FILE = "model_inspection.txt"
NUM_ITEMS = 100
MODEL_FILE = "./models/v2-1_512-ema-pruned.safetensors"
MODEL_FILE1 = "./unet/diffusion_pytorch_model_test.safetensors"
MODEL_FILE2 = "./unet/xxmix9realistic_v40.safetensors"
# Recreate the inspection file at every execution of the script
with open(INSPECTI... | for key, value in _state_dict(model).items(): | 2 | 2023-12-25 05:49:34+00:00 | 2k |
ffmemes/ff-backend | src/storage/service.py | [
{
"identifier": "language",
"path": "src/database.py",
"snippet": "DATABASE_URL = str(settings.DATABASE_URL)\nasync def fetch_one(select_query: Select | Insert | Update) -> dict[str, Any] | None:\nasync def fetch_all(select_query: Select | Insert | Update) -> list[dict[str, Any]]:\nasync def execute(sel... | from typing import Any
from datetime import datetime
from sqlalchemy import select, nulls_first, text
from sqlalchemy.dialects.postgresql import insert
from src.database import (
language,
meme,
meme_source,
meme_raw_telegram,
meme_raw_vk,
execute, fetch_one, fetch_all,
)
from src.storage.parser... | 1,154 |
async def insert_parsed_posts_from_telegram(
meme_source_id: int,
telegram_posts: list[TgChannelPostParsingResult],
) -> None:
posts = [
post.model_dump() | {"meme_source_id": meme_source_id}
for post in telegram_posts
]
insert_statement = insert(meme_raw_telegram).values(posts)
... |
async def insert_parsed_posts_from_telegram(
meme_source_id: int,
telegram_posts: list[TgChannelPostParsingResult],
) -> None:
posts = [
post.model_dump() | {"meme_source_id": meme_source_id}
for post in telegram_posts
]
insert_statement = insert(meme_raw_telegram).values(posts)
... | .where(meme_source.c.type == MemeSourceType.TELEGRAM) | 3 | 2023-12-23 12:55:43+00:00 | 2k |
Con6924/SPM | src/configs/prompt.py | [
{
"identifier": "imagenet_templates",
"path": "src/misc/clip_templates.py",
"snippet": ""
},
{
"identifier": "encode_prompts",
"path": "src/engine/train_util.py",
"snippet": "def encode_prompts(\n tokenizer: CLIPTokenizer,\n text_encoder: CLIPTokenizer,\n prompts: list[str],\n ... | from typing import Literal, Optional, Union
from pathlib import Path
from pydantic import BaseModel, root_validator
from transformers import CLIPTextModel, CLIPTokenizer
from src.misc.clip_templates import imagenet_templates
from src.engine.train_util import encode_prompts
import yaml
import pandas as pd
import random
... | 1,147 |
class PromptEmbedsXL:
text_embeds: torch.FloatTensor
pooled_embeds: torch.FloatTensor
def __init__(self, embeds) -> None:
self.text_embeds, self.pooled_embeds = embeds
PROMPT_EMBEDDING = Union[torch.FloatTensor, PromptEmbedsXL]
class PromptEmbedsCache:
prompts: dict[str, PROMPT_EMBEDDING] =... |
ACTION_TYPES = Literal[
"erase",
"erase_with_la",
]
class PromptEmbedsXL:
text_embeds: torch.FloatTensor
pooled_embeds: torch.FloatTensor
def __init__(self, embeds) -> None:
self.text_embeds, self.pooled_embeds = embeds
PROMPT_EMBEDDING = Union[torch.FloatTensor, PromptEmbedsXL]
cla... | self.target = encode_prompts(tokenizer, text_encoder, [target_prompt]) | 1 | 2023-12-26 03:19:16+00:00 | 2k |
dakpinaroglu/Frame2seq | frame2seq/utils/score.py | [
{
"identifier": "residue_constants",
"path": "frame2seq/utils/residue_constants.py",
"snippet": "def load_stereo_chemical_props() -> Tuple[Mapping[str, List[Bond]],\n def make_bond_key(atom1_name, atom2_name):\ndef sequence_to_onehot(\n sequence: str,\n mapping: Mapping[str, int],\n) -> np.ndarra... | import os
import torch
from tqdm import tqdm
from frame2seq.utils import residue_constants
from frame2seq.utils.util import get_neg_pll, read_fasta_file
from frame2seq.utils.pdb2input import get_inference_inputs
from frame2seq.utils.pred2output import output_csv, output_indiv_csv | 1,471 |
def score(self, pdb_file, chain_id, fasta_file, save_indiv_neg_pll):
temperature = 1.0
seq_mask, aatype, X = get_inference_inputs(pdb_file, chain_id)
seq_mask = seq_mask.to(self.device)
aatype = aatype.to(self.device)
X = X.to(self.device)
str_form = [residue_constants.ID_TO_AA[int(i)] for i ... |
def score(self, pdb_file, chain_id, fasta_file, save_indiv_neg_pll):
temperature = 1.0
seq_mask, aatype, X = get_inference_inputs(pdb_file, chain_id)
seq_mask = seq_mask.to(self.device)
aatype = aatype.to(self.device)
X = X.to(self.device)
str_form = [residue_constants.ID_TO_AA[int(i)] for i ... | input_seqs = read_fasta_file(fasta_file) | 2 | 2023-12-25 09:29:36+00:00 | 2k |
davep/oshit | oshit/app/oshit.py | [
{
"identifier": "load_configuration",
"path": "oshit/app/data/config.py",
"snippet": "@lru_cache(maxsize=None)\ndef load_configuration() -> Configuration:\n \"\"\"Load the configuration.\n\n Returns:\n The configuration.\n\n Note:\n As a side-effect, if the configuration doesn't e... | from textual.app import App
from .data import load_configuration, save_configuration
from .screens import Main | 1,359 | """The main application class."""
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class OSH... | """The main application class."""
##############################################################################
# Textual imports.
##############################################################################
# Local imports.
##############################################################################
class OSH... | self.push_screen(Main()) | 2 | 2023-12-25 14:06:07+00:00 | 2k |
Maximilian-Winter/llama-cpp-agent | src/llama_cpp_agent/agent_memory/memory_tools.py | [
{
"identifier": "LlamaCppFunctionTool",
"path": "src/llama_cpp_agent/function_calling.py",
"snippet": "class LlamaCppFunctionTool:\n def __init__(self, pydantic_model: Type[BaseModel], has_markdown_code_block=False, has_triple_quoted_string=False,\n **additional_parameters):\n ... | from pydantic import BaseModel, Field
from ..function_calling import LlamaCppFunctionTool
from .core_memory_manager import CoreMemoryManager
from .retrieval_memory_manager import RetrievalMemoryManager, RetrievalMemory | 1,362 |
class AddCoreMemory(BaseModel):
"""
Add a new entry to the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry.")
field: str = Field(..., description="A secondary key or field within the core memory entry.")
value: str = Field(..., description="The... |
class AddCoreMemory(BaseModel):
"""
Add a new entry to the core memory.
"""
key: str = Field(..., description="The key identifier for the core memory entry.")
field: str = Field(..., description="A secondary key or field within the core memory entry.")
value: str = Field(..., description="The... | self.retrieval_memory = RetrievalMemory(persistent_db_path, embedding_model_name, collection_name) | 2 | 2023-12-29 16:54:39+00:00 | 2k |
tedivm/paracelsus | paracelsus/cli.py | [
{
"identifier": "Dot",
"path": "paracelsus/transformers/dot.py",
"snippet": "class Dot:\n comment_format: str = \"dot\"\n metadata: MetaData\n graph: pydot.Dot\n\n def __init__(self, metaclass: MetaData) -> None:\n self.metadata = metaclass\n self.graph = pydot.Dot(\"database\"... | import importlib
import re
import sys
import typer
from enum import Enum
from pathlib import Path
from typing import List
from typing_extensions import Annotated
from .transformers.dot import Dot
from .transformers.mermaid import Mermaid
from . import _version | 1,289 |
app = typer.Typer()
transformers = {
"mmd": Mermaid,
"mermaid": Mermaid,
|
app = typer.Typer()
transformers = {
"mmd": Mermaid,
"mermaid": Mermaid, | "dot": Dot, | 0 | 2023-12-29 22:13:23+00:00 | 2k |
winniesi/tg-gemini-bot | api/handle.py | [
{
"identifier": "is_authorized",
"path": "api/auth.py",
"snippet": "def is_authorized(from_id: int, user_name: str) -> bool:\n if str(user_name) in ALLOWED_USERS:\n return True\n return False"
},
{
"identifier": "ChatManager",
"path": "api/context.py",
"snippet": "class Chat... | from .auth import is_authorized
from .context import ChatManager, ImageChatManger
from .telegram import Update, send_message | 971 | """
All the chat that comes through the Telegram bot gets passed to the
handle_message function. This function checks out if the user has the
green light to chat with the bot. Once that's sorted, it figures out if
the user sent words or an image and deals with it accordingly.
For text messages, it fires up the ChatMan... | """
All the chat that comes through the Telegram bot gets passed to the
handle_message function. This function checks out if the user has the
green light to chat with the bot. Once that's sorted, it figures out if
the user sent words or an image and deals with it accordingly.
For text messages, it fires up the ChatMan... | send_message(update.from_id, "😫 You are not allowed to use this bot.") | 4 | 2023-12-25 03:27:43+00:00 | 2k |
usail-hkust/LLMTSCS | run_advanced_maxpressure.py | [
{
"identifier": "oneline_wrapper",
"path": "utils/utils.py",
"snippet": "def oneline_wrapper(dic_agent_conf, dic_traffic_env_conf, dic_path, roadnet, trafficflow):\n results_table = []\n all_rewards = []\n all_queue_len = []\n all_travel_time = []\n for i in range(1):\n dic_path[\"... | from utils.utils import oneline_wrapper
from utils import error
from multiprocessing import Process
import os
import time
import argparse | 1,154 |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--memo", type=str, default='AdvancedMaxPressure')
parser.add_argument("--model", type=str, default="AdvancedMaxPressure")
parser.add_argument("--proj_name", type=str, default="chatgpt-TSCS")
parser.add_argument("--eightphase... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--memo", type=str, default='AdvancedMaxPressure')
parser.add_argument("--model", type=str, default="AdvancedMaxPressure")
parser.add_argument("--proj_name", type=str, default="chatgpt-TSCS")
parser.add_argument("--eightphase... | raise error.flowFileException('Flow file does not exist.') | 1 | 2023-12-26 08:31:47+00:00 | 2k |
ohadmata/shmessy | src/shmessy/types/unix_timestamp.py | [
{
"identifier": "InferredField",
"path": "src/shmessy/schema.py",
"snippet": "class InferredField(BaseModel):\n inferred_type: Optional[str] = None\n inferred_pattern: Optional[Any] = None"
},
{
"identifier": "ValidatorTypes",
"path": "src/shmessy/schema.py",
"snippet": "class Vali... | import logging
import math
from datetime import datetime
from enum import Enum
from typing import Optional
from numpy import ndarray
from pandas import Series, to_datetime
from ..schema import InferredField, ValidatorTypes
from .base import BaseType | 669 |
logger = logging.getLogger(__name__)
class TimestampResolution(str, Enum):
SECONDS = "s"
MILLISECONDS = "ms"
NANOSECONDS = "ns"
class UnixTimestampType(BaseType):
weight = 4
validator_types = (ValidatorTypes.NUMERIC,)
min_valid_year: int = 1980
max_valid_year: int = 2100
@staticm... |
logger = logging.getLogger(__name__)
class TimestampResolution(str, Enum):
SECONDS = "s"
MILLISECONDS = "ms"
NANOSECONDS = "ns"
class UnixTimestampType(BaseType):
weight = 4
validator_types = (ValidatorTypes.NUMERIC,)
min_valid_year: int = 1980
max_valid_year: int = 2100
@staticm... | def validate(self, data: ndarray) -> Optional[InferredField]: | 0 | 2023-12-27 20:15:01+00:00 | 2k |
kokiez/solana-sniper | monitor_price_strategy.py | [
{
"identifier": "get_price",
"path": "birdeye.py",
"snippet": "def get_price(token_address):\r\n url = f\"https://api.dexscreener.com/latest/dex/tokens/{token_address}\"\r\n exclude = ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB']\r\n response =... | import time
from birdeye import get_price, getSymbol
from webhook import sendWebhook
| 1,376 |
"""If you have ton of trades then best to use Simulate Transaction and modify this part of code to your needs"""
"""
Only Take Profit
"""
def limit_order(bought_token_price,desired_token_address, take_profit_ratio, execution_time, txB):
token_symbol, SOl_Symbol = getSymbol(desired_token_address)
... |
"""If you have ton of trades then best to use Simulate Transaction and modify this part of code to your needs"""
"""
Only Take Profit
"""
def limit_order(bought_token_price,desired_token_address, take_profit_ratio, execution_time, txB):
token_symbol, SOl_Symbol = getSymbol(desired_token_address)
... | bought_token_curr_price = get_price(desired_token_address)
| 0 | 2023-12-26 11:40:05+00:00 | 2k |
enochyearn/MLX_RoBERTa | mlx_roberta.py | [
{
"identifier": "LayerNormBasselCorrected",
"path": "custom/nn/layers/normalization.py",
"snippet": "class LayerNormBasselCorrected(Module):\n r\"\"\"Applies layer normalization [1] on the inputs with Bessel's Correction used by default like PyTorch.\n\n Computes\n\n .. math::\n\n y = \\... | import argparse
import time
import mlx.core as mx
import mlx.nn as nn
import numpy as np
import math
from mlx.utils import tree_unflatten
from collections import OrderedDict
from custom.nn.layers.normalization import LayerNormBasselCorrected, LayerNormTorchAlike
from transformers import RobertaTokenizer
from dataclasse... | 1,439 |
# utils
@dataclass
class ModelConfig:
intermediate_size: int = 3072
hidden_size: int = 768
no_heads: int = 12
hidden_layers: int = 12
vocab_size: int = 50265
attention_probs_dropout_prob: float = 0.1
hidden_dropout_prob: float = 0.1
layer_norm_eps: float = 1e-5
max_position_e... |
# utils
@dataclass
class ModelConfig:
intermediate_size: int = 3072
hidden_size: int = 768
no_heads: int = 12
hidden_layers: int = 12
vocab_size: int = 50265
attention_probs_dropout_prob: float = 0.1
hidden_dropout_prob: float = 0.1
layer_norm_eps: float = 1e-5
max_position_e... | self.LayerNorm = LayerNormTorchAlike(config.hidden_size, eps=config.layer_norm_eps, correction=True) | 1 | 2023-12-22 05:48:57+00:00 | 2k |
zy7y/dfs-generate | main.py | [
{
"identifier": "CodeGen",
"path": "entity.py",
"snippet": "class CodeGen(BaseVo):\n name: str\n code: str\n\n @field_serializer(\"code\")\n def serialize_code(self, code: str, _info):\n _code = black.format_str(code, mode=black.FileMode())\n return isort.code(_code)"
},
{
... | from fastapi import FastAPI, Query
from fastapi.requests import Request
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from entity import CodeGen, Conf, DBConf, R, RList, Table
from generate.main import generate_code
import uvicorn | 789 |
app = FastAPI(
title="dfs-generate", description="FastAPI SQLModel 逆向生成代码", docs_url=None
)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", include_in_schema=False)
def index():
return FileResponse("static/index.html")
|
app = FastAPI(
title="dfs-generate", description="FastAPI SQLModel 逆向生成代码", docs_url=None
)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", include_in_schema=False)
def index():
return FileResponse("static/index.html")
| @app.get("/tables", response_model=RList[Table]) | 5 | 2023-12-23 08:32:58+00:00 | 2k |
CrawlScript/Torch-MGDCF | torch_mgdcf/evaluation/ranking.py | [
{
"identifier": "ndcg_score",
"path": "torch_mgdcf/metrics/ranking.py",
"snippet": "def ndcg_score(reference, hypothesis):\n \"\"\"\n Normalized Discounted Cumulative Gain (nDCG)\n Normalized version of DCG:\n nDCG = DCG(hypothesis)/DCG(reference)\n\n Parameters:\n reference ... | from tqdm import tqdm
from torch_mgdcf.metrics.ranking import ndcg_score, precision_score, recall_score
from torch_mgdcf.vector_search.vector_search import VectorSearchEngine
import numpy as np
import torch | 765 | # coding=utf-8
# The code is from our another project GRecX: https://github.com/maenzhier/grecx_datasets
def score(ground_truth, pred_items, k_list, metrics):
pred_match = [1 if item in ground_truth else 0 for item in pred_items]
max_k = k_list[-1]
if len(ground_truth) > max_k:
ndcg_gold = [1] ... | # coding=utf-8
# The code is from our another project GRecX: https://github.com/maenzhier/grecx_datasets
def score(ground_truth, pred_items, k_list, metrics):
pred_match = [1 if item in ground_truth else 0 for item in pred_items]
max_k = k_list[-1]
if len(ground_truth) > max_k:
ndcg_gold = [1] ... | v_search = VectorSearchEngine(item_embedding) | 3 | 2023-12-26 10:26:50+00:00 | 2k |
KyanChen/TTP | opencd/models/data_preprocessor.py | [
{
"identifier": "SampleList",
"path": "mmseg/utils/typing_utils.py",
"snippet": ""
},
{
"identifier": "MODELS",
"path": "opencd/registry.py",
"snippet": "MODELS = Registry('model', parent=MMENGINE_MODELS, locations=['opencd.models'])"
}
] | from numbers import Number
from typing import Any, Dict, List, Optional, Sequence, Union
from mmengine.model import BaseDataPreprocessor
from mmseg.utils import SampleList
from opencd.registry import MODELS
import numpy as np
import torch
import torch.nn.functional as F | 1,234 | # Copyright (c) Open-CD. All rights reserved.
def stack_batch(inputs: List[torch.Tensor],
data_samples: Optional[SampleList] = None,
size: Optional[tuple] = None,
size_divisor: Optional[int] = None,
pad_val: Union[int, float] = 0,
seg_p... | # Copyright (c) Open-CD. All rights reserved.
def stack_batch(inputs: List[torch.Tensor],
data_samples: Optional[SampleList] = None,
size: Optional[tuple] = None,
size_divisor: Optional[int] = None,
pad_val: Union[int, float] = 0,
seg_p... | @MODELS.register_module() | 1 | 2023-12-23 08:36:47+00:00 | 2k |
N0rz3/Phunter | lib/lookup.py | [
{
"identifier": "free",
"path": "lib/free_lookup.py",
"snippet": "async def free(phone_number):\r\n r = await Request(\"https://free-lookup.net/{}\".format(phone_number), headers={'user-agent': random.choice(agent)}).get()\r\n\r\n html_body = BeautifulSoup(r.text, \"html.parser\")\r\n list_info... | import phonenumbers
import json
from phonenumbers import carrier
from .reputation import *
from .free_lookup import free
from .spam import spamcalls
from lib.text import *
| 809 |
async def lookup(phone_number):
print()
parsed = phonenumbers.parse(phone_number)
operator = carrier.name_for_number(parsed, "fr")
line = phonenumbers.number_type(parsed)
if line == phonenumbers.PhoneNumberType.FIXED_LINE:
ligne = f" [{GREEN}>{WHITE}] Line type: Fixed"
e... |
async def lookup(phone_number):
print()
parsed = phonenumbers.parse(phone_number)
operator = carrier.name_for_number(parsed, "fr")
line = phonenumbers.number_type(parsed)
if line == phonenumbers.PhoneNumberType.FIXED_LINE:
ligne = f" [{GREEN}>{WHITE}] Line type: Fixed"
e... | await free(str(phone_number).replace("+", ""))
| 0 | 2023-12-30 13:21:14+00:00 | 2k |
dan-r/HomeAssistant-Ohme | custom_components/ohme/binary_sensor.py | [
{
"identifier": "DOMAIN",
"path": "custom_components/ohme/const.py",
"snippet": "DOMAIN = \"ohme\""
},
{
"identifier": "DATA_COORDINATORS",
"path": "custom_components/ohme/const.py",
"snippet": "DATA_COORDINATORS = \"coordinators\""
},
{
"identifier": "COORDINATOR_CHARGESESSIONS"... | import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity
)
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import generate_entity_id
from homeass... | 823 | """Platform for sensor integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Setup sensors and configure coordinator."""
client = hass.data[... | """Platform for sensor integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Setup sensors and configure coordinator."""
client = hass.data[... | coordinator = hass.data[DOMAIN][DATA_COORDINATORS][COORDINATOR_CHARGESESSIONS] | 1 | 2023-12-24 20:59:18+00:00 | 2k |
Almas-Ali/SpyIP | spyip/backend.py | [
{
"identifier": "TooManyRequests",
"path": "spyip/exceptions.py",
"snippet": "class TooManyRequests(Exception):\n pass"
},
{
"identifier": "ConnectionTimeout",
"path": "spyip/exceptions.py",
"snippet": "class ConnectionTimeout(Exception):\n pass"
},
{
"identifier": "StatusE... | from typing import List, Union
from .exceptions import (
TooManyRequests,
ConnectionTimeout,
StatusError,
)
from .models import (
IPResponse,
DNSResponse,
)
import asyncio
import random
import string
import httpx | 1,207 |
def get_random_string(length: int = 32) -> str:
"""Generate a random string of fixed length."""
letters = string.ascii_lowercase + string.digits
return ''.join(random.sample(letters, length))
# API endpoints for IP address lookup
trace_me_url = 'http://ip-api.com/json/'
trace_ip_url = 'http://ip-api.c... |
def get_random_string(length: int = 32) -> str:
"""Generate a random string of fixed length."""
letters = string.ascii_lowercase + string.digits
return ''.join(random.sample(letters, length))
# API endpoints for IP address lookup
trace_me_url = 'http://ip-api.com/json/'
trace_ip_url = 'http://ip-api.c... | ) -> Union[IPResponse, None]: | 3 | 2023-12-31 19:43:38+00:00 | 2k |
leopedroso45/Stable-Diffusion-ImageGen | tests/test_process_task.py | [
{
"identifier": "check_cuda_and_clear_cache",
"path": "sevsd/process_task.py",
"snippet": "def check_cuda_and_clear_cache():\n r\"\"\"\n Clears the CUDA cache if available, otherwise performs garbage collection.\n This function is called to manage memory usage, particularly when working with la... | import unittest
import sys
from unittest.mock import patch, MagicMock
from sevsd.process_task import check_cuda_and_clear_cache, process_task, check_os_path | 991 | sys.path.append('../')
class TestProcessTask(unittest.TestCase):
@patch('sevsd.process_task.generate_image')
def test_process_task(self, mock_generate_image):
mock_image = MagicMock()
mock_image.save = MagicMock()
mock_generate_image.return_value = [mock_image]
fake_job = {"pr... | sys.path.append('../')
class TestProcessTask(unittest.TestCase):
@patch('sevsd.process_task.generate_image')
def test_process_task(self, mock_generate_image):
mock_image = MagicMock()
mock_image.save = MagicMock()
mock_generate_image.return_value = [mock_image]
fake_job = {"pr... | process_task(fake_job, fake_pipeline, fake_executor, fake_path, parallel_exec=True) | 1 | 2023-12-28 16:19:12+00:00 | 2k |
RepoBench v1.1 (Python)
Introduction
This dataset presents the Python portion of RepoBench v1.1 (ICLR 2024). The data encompasses a collection from GitHub, spanning the period from October 6th to December 31st, 2023. With a commitment to data integrity, we've implemented a deduplication process based on file content against the Stack v2 dataset (coming soon), aiming to mitigate data leakage and memorization concerns.
Resources and Links
FAQs
Q: What do the features in the dataset mean?
A: Imagine you're coding in Python and you want to write the next line of your code. The dataset provides you the following information:
repo_name(string): the name of the repositoryfile_path(string): the path of the current filecontext(list): the cross-file code snippets that might be helpful for writing the next line:identifier(string): the identifier of the code snippetpath(string): the path of the code snippetsnippet(string): the code snippet
import_statement(string): the import statement of the current filecropped_code(string): the cropped code of the current file (up to previous 120 lines)all_code(string): the entire code of the current file (not cropped)next_line(string): the next line of the code (this serves as the target)gold_snippet_index(int): the index of the gold snippet in the context (which will be used in next line, just for reference, you should not use this for next line prediction)created_at(string): the creation time of the repositorylevel(string): the level of next line completion, which is measured by the number of tokens for the whole prompt (including all the context, import statement, cropped code and some neccessary separator tokens)
Q: How does the level be defined?
A: The level is determined by the number of tokens for the whole prompt (including all the context, import statement, cropped code and some neccessary separator tokens). The token number is calculated by the tokenizer of GPT-4 by using tiktoken. The following table shows the level definition:
Level Prompt Length (Number of Tokens) 2k 640 - 1,600 4k 1,600 - 3,600 8k 3,600 - 7,200 12k 7,200 - 10,800 16k 10,800 - 14,400 24k 14,400 - 21,600 32k 21,600 - 28,800 64k 28,800 - 57,600 128k 57,600 - 100,000 Q: What does the different splits mean?
A: The dataset is split into three parts:
cross_file_first: the next line of code utilizes content from a cross-file code snippet and it is its first usage within current file.cross_file_random: the next line of code utilizes content from a cross-file code snippet and it is NOT its first usage within current file.in_file: the next line of code does not utilize content from a cross-file code snippet.
Q: How to construct the prompt for next line prediction?
A: We hereby provide the official implementation for constructing prompts. Please note that the methods described below are not necessarily the optimal way of construction. Reordering, retrieval argumentation, or employing different cropping/construction techniques could potentially lead to varying degrees of improvement. Ensure that your model evaluations are conducted in a fair manner.
import re def construct_prompt( data: dict, language: str = "python", tokenizer= None, max_token_nums: int = 15800 ) -> str: """ Construct the prompt for next line prediction. :param data: data point from the dataset :param language: the language of the code :param tokenizer: the tokenizer of the evaluation model :param max_token_nums: the maximum number of tokens constraint for the prompt :return: the constructed prompt """ # comment symbol for different languages comment_symbol = "#" if language == "python" else "//" # construct the cross-file prompt and in-file prompt separately # cross-file prompt cross_file_prompt = f"{comment_symbol} Repo Name: {data['repo_name']}\n" for snippet in data['context']: cross_file_prompt += f"{comment_symbol} Path: {snippet['path']}\n{snippet['snippet']}" + "\n\n" # in-file prompt in_file_prompt = f"{comment_symbol} Path: {data['file_path']}\n{data['import_statement']}\n{data['cropped_code']}\n" # if we assign the tokenizer and the max_token_nums, we will truncate the cross-file prompt to meet the constraint if tokenizer is not None and max_token_nums is not None: cross_file_prompt_token_nums = len(tokenizer.encode(cross_file_prompt)) in_file_prompt_token_nums = len(tokenizer.encode(in_file_prompt)) exceed_token_nums = cross_file_prompt_token_nums + in_file_prompt_token_nums - max_token_nums if exceed_token_nums > 0: # split the cross-file prompt into lines cross_file_prompt_lines = cross_file_prompt.split("\n") # drop lines from end until the extra token number is less than 0 for i in range(len(repo_prompt_lines)-1, -1, -1): extra_token_num -= len(tokenizer.encode(cross_file_prompt_lines[i])) if extra_token_num < 0: break # join the lines back cross_file_prompt = "\n".join(cross_file_prompt_lines[:i]) + "\n\n" # combine the cross-file prompt and in-file prompt prompt = cross_file_prompt + in_file_prompt # normalize some empty lines prompt = re.sub(r'\n{4,}', '\n\n', prompt) return promptQ: How to load the dataset?
A: You can simply use the following code to load the dataset:
from datasets import load_dataset dataset = load_dataset("tianyang/repobench_python_v1.1")To construct the prompt for next line prediction, you can refer to the official implementation provided in the previous question and use the
construct_promptfunction to construct the prompt, for example:from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-1.3b-base") model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-1.3b-base") prompt = construct_prompt(dataset['cross_file_first'][0], tokenizer=tokenizer, max_token_nums=15800)Q: How often will the dataset be updated?
A: We plan to update the dataset every three months, but there might be slight delays considering the time required for data crawling and our own schedules. If you require updated data, please feel free to contact us, and we can coordinate the timing and expedite the process.
Q: What models should I use to evaluate the dataset?
A: RepoBench is designed to evaluate base models, not those that have been instruction fine-tuned. Please use base models for evaluation.
Q: I am training a new model but the knowledge cutoff date is after the dataset's. Can you provide me with the latest data?
A: Sure! We are happy to provide you with the latest data (even customized data with specific requirements). Please feel free to contact us.
Q: Can I opt-out?
A: Yes, you can opt-out your repository from the dataset. Please check Am I in RepoBench?, we will upload the raw data of the repository information we crawled at least 15 days before the dataset creation and release. We will respect your decision and remove your repository from the dataset if you opt-out.
Citation
If you find RepoBench useful in your research, please consider citing the paper using the following BibTeX entry:
@misc{liu2023repobench,
title={RepoBench: Benchmarking Repository-Level Code Auto-Completion Systems},
author={Tianyang Liu and Canwen Xu and Julian McAuley},
year={2024},
url={https://arxiv.org/abs/2306.03091},
booktitle={International Conference on Learning Representations}
}
Your interest and contributions to RepoBench are immensely valued. Happy coding! 🚀
- Downloads last month
- 1,217