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 |
Emperor-WS/PyEmber | ember/autograd/numeric.py | [
{
"identifier": "Hook",
"path": "ember/autograd/hook.py",
"snippet": "class Hook:\n \"\"\"\n Hook class for attaching gradient functions to tensors.\n\n Hooks allow users to attach custom gradient functions to tensors for\n monitoring or modifying gradients during backpropagation.\n\n Att... | import numpy as np
import ember
from .hook import Hook
from ._utils import numpy_unpad, inv_permutation | 742 |
def _T(t):
"""
Transpose operation on the input tensor.
Args:
- t: Input tensor.
Returns:
- Tensor: Resultant tensor with the transpose operation applied.
"""
t = ember.to_tensor(t) # Convert the input tensor to a Tensor
data = t.data.T # Transpose operation
requires_grad =... |
def _T(t):
"""
Transpose operation on the input tensor.
Args:
- t: Input tensor.
Returns:
- Tensor: Resultant tensor with the transpose operation applied.
"""
t = ember.to_tensor(t) # Convert the input tensor to a Tensor
data = t.data.T # Transpose operation
requires_grad =... | hooks.append(Hook(t, lambda grad: grad.T)) | 0 | 2023-12-23 23:11:58+00:00 | 2k |
Hassi34/iot-device-identification | src/stage_03_preprocess_data.py | [
{
"identifier": "read_yaml",
"path": "src/utils/common.py",
"snippet": "def read_yaml(path_to_yaml: str) -> dict:\n with open(path_to_yaml) as yaml_file:\n content = yaml.safe_load(yaml_file)\n return content"
},
{
"identifier": "get_logger",
"path": "src/utils/sys_logging.py",
... | import argparse
import joblib
import pandas as pd
from src.utils.common import read_yaml
from src.utils.sys_logging import get_logger
from sklearn.preprocessing import LabelEncoder
from src.utils.common import write_dict_to_yaml
from src.utils.data_ops import gzip_np_arr
from sklearn.model_selection import train_test_s... | 1,022 |
STAGE = "Preprocess Data"
def preprocess_data():
complete_df = pd.read_parquet(RAW_DATA_FILE_PATH)
logger.info(
f'The raw data file has been loaded from "{RAW_DATA_FILE_PATH}" with the shape "{complete_df.shape}"'
)
duplicate_rows = complete_df.duplicated().sum()
if duplicate_rows > 0:
... |
STAGE = "Preprocess Data"
def preprocess_data():
complete_df = pd.read_parquet(RAW_DATA_FILE_PATH)
logger.info(
f'The raw data file has been loaded from "{RAW_DATA_FILE_PATH}" with the shape "{complete_df.shape}"'
)
duplicate_rows = complete_df.duplicated().sum()
if duplicate_rows > 0:
... | labels_dict = read_yaml(parsed_args.params)["labels_mapping"] | 0 | 2023-12-25 10:40:19+00:00 | 2k |
see2023/Bert-VITS2-ext | for_deploy/infer_utils.py | [
{
"identifier": "config",
"path": "config.py",
"snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ... | import sys
import torch
from transformers import (
AutoModelForMaskedLM,
AutoTokenizer,
DebertaV2Model,
DebertaV2Tokenizer,
ClapModel,
ClapProcessor,
)
from config import config
from text.japanese import text2sep_kata | 1,223 |
class BertFeature:
def __init__(self, model_path, language="ZH"):
self.model_path = model_path
self.language = language
self.tokenizer = None
self.model = None
self.device = None
self._prepare()
def _get_device(self, device=config.bert_gen_config.device):
... |
class BertFeature:
def __init__(self, model_path, language="ZH"):
self.model_path = model_path
self.language = language
self.tokenizer = None
self.model = None
self.device = None
self._prepare()
def _get_device(self, device=config.bert_gen_config.device):
... | text = "".join(text2sep_kata(text)[0]) | 1 | 2023-12-27 03:09:11+00:00 | 2k |
chinhsuanwu/ifusion-threestudio | threestudio/models/materials/no_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,291 |
@threestudio.register("no-material")
class NoMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
n_output_dims: int = 3
color_activation: str = "sigmoid"
input_feature_dims: Optional[int] = None
mlp_network_config: Optional[dict] = None
requires_norm... |
@threestudio.register("no-material")
class NoMaterial(BaseMaterial):
@dataclass
class Config(BaseMaterial.Config):
n_output_dims: int = 3
color_activation: str = "sigmoid"
input_feature_dims: Optional[int] = None
mlp_network_config: Optional[dict] = None
requires_norm... | color = get_activation(self.cfg.color_activation)(features) | 4 | 2023-12-27 20:30:33+00:00 | 2k |
jasursadikov/mud | commands.py | [
{
"identifier": "TEXT",
"path": "utils.py",
"snippet": "TEXT = {\n 'white': '\\033[37m',\n 'gray': '\\033[90m',\n 'black': '\\033[30m',\n 'red': '\\033[31m',\n 'green': '\\033[32m',\n 'yellow': '\\033[33m',\n 'blue': '\\033[34m',\n 'magenta': '\\033[35m',\n 'cyan': '\\033[36m'... | import utils
import asyncio
import subprocess
from utils import TEXT, BACK, RESET, STYLES, END_STYLES, glyph
from typing import List, Dict
from collections import Counter
from prettytable import PrettyTable, PLAIN_COLUMNS | 880 |
class Commands:
def __init__(self, repos):
self.repos = repos
self.label_color_cache = {}
self.current_color_index = 0
# `mud status` command implementation
def status(self, repos: Dict[str, List[str]]) -> None:
table = self._get_table()
for path, tags in repos.it... |
class Commands:
def __init__(self, repos):
self.repos = repos
self.label_color_cache = {}
self.current_color_index = 0
# `mud status` command implementation
def status(self, repos: Dict[str, List[str]]) -> None:
table = self._get_table()
for path, tags in repos.it... | origin_sync += f'{TEXT["bright_green"]}{glyph("ahead")} {ahead}{RESET}' | 5 | 2023-12-28 13:09:31+00:00 | 2k |
Q-MM/PureMM | model/PureMM_arch.py | [
{
"identifier": "build_vision_tower",
"path": "model/multimodal_encoder/builder.py",
"snippet": "def build_vision_tower(vision_tower_cfg, **kwargs):\n vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))\n is_absolute_path_exists = os.path.ex... | from abc import ABC, abstractmethod
from .multimodal_encoder.builder import build_vision_tower
from .multimodal_projector.builder import build_vision_projector
import torch
import torch.nn as nn | 837 | # Copyright 2023 Haotian Liu
#
# 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 agre... | # Copyright 2023 Haotian Liu
#
# 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 agre... | self.mm_projector = build_vision_projector(config) | 1 | 2023-12-27 09:54:09+00:00 | 2k |
Ananya2001-an/spotify-py-sdk | tests/endpoints/test_recommendations.py | [
{
"identifier": "SpotifyApi",
"path": "spotify_py_sdk/spotify_api.py",
"snippet": "class SpotifyApi:\n \"\"\"Create an api instance and call the various endpoint methods.\n\n :param client_id: Client_ID for your app\n :type client_id: str\n :param client_secret: Client_Secret for your app\n ... | import json
import pytest
import os
from spotify_py_sdk import SpotifyApi
from spotify_py_sdk.endpoints.recommendations import RecommendationsRequestRequiredArguments
from dotenv import load_dotenv | 1,007 |
load_dotenv()
@pytest.fixture
def api():
|
load_dotenv()
@pytest.fixture
def api(): | return SpotifyApi(os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET")) | 0 | 2023-12-27 20:12:31+00:00 | 2k |
kyleliang919/Optimizer-Zoo | optimizer_zoo/Trainer/utils.py | [
{
"identifier": "AsyncTrainer",
"path": "optimizer_zoo/Trainer/async_trainer.py",
"snippet": "class AsyncTrainer(Trainer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.accelerator.sync_gradients = None\n\n def training_step(self, model, inputs):\n... | from transformers import Trainer, Seq2SeqTrainer
from trl import SFTTrainer, DPOTrainer
from .async_trainer import AsyncTrainer, AsyncSFTTrainer, AsyncDPOTrainer, AsyncSeq2SeqTrainer | 1,215 | def create_trainer(training_args):
if training_args.task == "pretraining":
return AsyncTrainer if training_args.async_grad else Trainer
elif training_args.task == "sft":
return AsyncSFTTrainer if training_args.async_grad else SFTTrainer
elif training_args.task == "dpo":
return AsyncD... | def create_trainer(training_args):
if training_args.task == "pretraining":
return AsyncTrainer if training_args.async_grad else Trainer
elif training_args.task == "sft":
return AsyncSFTTrainer if training_args.async_grad else SFTTrainer
elif training_args.task == "dpo":
return AsyncD... | return AsyncSeq2SeqTrainer if training_args.async_grad else Seq2SeqTrainer | 3 | 2023-12-22 17:07:00+00:00 | 2k |
giaminhgist/3D-DAM | lib/model/DuoAttention.py | [
{
"identifier": "SpatialAttention3D",
"path": "lib/model/attention_block.py",
"snippet": "class SpatialAttention3D(nn.Module):\n def __init__(self, out_channel=64, kernel_size=3, stride=1, padding=1):\n super(SpatialAttention3D, self).__init__()\n\n self.conv = nn.Conv3d(2, out_channel,... | import numpy as np
import torch
from torch import nn
from lib.model.attention_block import SpatialAttention3D, ChannelAttention3D, residual_block | 804 |
class DAM(nn.Module):
def __init__(self, channels=64):
super(DAM, self).__init__()
self.sa = SpatialAttention3D(out_channel=channels)
self.ca = ChannelAttention3D(in_planes=channels)
def forward(self, x):
residual = x
out = self.ca(x)
out = self.sa(out)
... |
class DAM(nn.Module):
def __init__(self, channels=64):
super(DAM, self).__init__()
self.sa = SpatialAttention3D(out_channel=channels)
self.ca = ChannelAttention3D(in_planes=channels)
def forward(self, x):
residual = x
out = self.ca(x)
out = self.sa(out)
... | residual_block(channel_size=16), | 2 | 2023-12-22 10:15:55+00:00 | 2k |
itsluminous/EasyEncryption | script.py | [
{
"identifier": "generate_key",
"path": "core.py",
"snippet": "def generate_key():\n \"\"\"Generate a Fernet key.\"\"\"\n return Fernet.generate_key()"
},
{
"identifier": "encrypt_message",
"path": "core.py",
"snippet": "def encrypt_message(message, key):\n \"\"\"Encrypt a messa... | from core import generate_key, encrypt_message, decrypt_message, encrypt_file, decrypt_file | 783 | """
Script providing a user interface for encryption and decryption operations.
"""
def generate_new_key():
"""
Generate a new encryption key.
Returns:
- bytes: New encryption key.
"""
key = generate_key()
print(f"\nGenerated Key: {key.decode()}")
return key
def enter_user_key():... | """
Script providing a user interface for encryption and decryption operations.
"""
def generate_new_key():
"""
Generate a new encryption key.
Returns:
- bytes: New encryption key.
"""
key = generate_key()
print(f"\nGenerated Key: {key.decode()}")
return key
def enter_user_key():... | decrypted_message = decrypt_message(encrypted_input.encode(), key) | 2 | 2023-12-31 13:24:53+00:00 | 2k |
gardenifi/server | tests/api/resource_not_found_test.py | [
{
"identifier": "app",
"path": "app/main_app.py",
"snippet": "INVALID_DATA = \"Invalid data: Unable to process the provided data\"\nclass GlobalVars:\nclass WifiData(BaseModel):\nclass ValveData(BaseModel):\nclass BleData(BaseModel):\n def __init__(self):\n def refresh_set(self):\n def refresh_... | import json
import pytest
from fastapi.testclient import TestClient
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
from app.main_app import app
from app.main_app import resource_not_found | 712 | """MIT License
Copyright (c) 2023, Marios Karagiannopoulos
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, merge... | """MIT License
Copyright (c) 2023, Marios Karagiannopoulos
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, merge... | response = await resource_not_found(obj, exc) | 1 | 2023-12-22 08:06:09+00:00 | 2k |
xiaoye0x0/pfgo_tg_bot | utils/task/set_args.py | [
{
"identifier": "Task",
"path": "utils/task/model.py",
"snippet": "class Task(metaclass=SingletonMeta):\n def __init__(self, args) -> None:\n self.conf_file = args.config\n\n self.bot_token: str = \"\"\n\n self.pfgo_url: str = \"\"\n self.username: str = \"\"\n self... | import os
import argparse
from .model import Task
from ..log import Logmanager | 838 |
def is_file_exists(file_path) -> bool:
r = os.path.exists(file_path)
if not r:
LOGGER.error(f"文件{file_path}不存在")
return r
def create_folder_if_not_exists(folder_path):
if not folder_path:
return
if not os.path.exists(folder_path):
os.makedirs(folder_path)
def parse_com... |
def is_file_exists(file_path) -> bool:
r = os.path.exists(file_path)
if not r:
LOGGER.error(f"文件{file_path}不存在")
return r
def create_folder_if_not_exists(folder_path):
if not folder_path:
return
if not os.path.exists(folder_path):
os.makedirs(folder_path)
def parse_com... | Logmanager(args.log) | 1 | 2023-12-28 08:55:04+00:00 | 2k |
shibing624/chatgpt-webui | src/index_func.py | [
{
"identifier": "local_embedding",
"path": "src/config.py",
"snippet": "def retrieve_openai_api(api_key=None):\ndef retrieve_proxy(proxy=None):\ndef update_doc_config(two_column_pdf):"
},
{
"identifier": "OPENAI_API_BASE",
"path": "src/presets.py",
"snippet": "OPENAI_API_BASE = \"https:/... | import os
import re
import PyPDF2
from typing import List, Optional, Any
from langchain.schema import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from loguru import logger
from tqdm import tqdm
from src.config import local_embedding, retrieve_proxy, chunk_overlap, chunk_s... | 1,337 |
pwd_path = os.path.abspath(os.path.dirname(__file__))
class ChineseRecursiveTextSplitter(RecursiveCharacterTextSplitter):
"""Recursive text splitter for Chinese text.
copy from: https://github.com/chatchat-space/Langchain-Chatchat/tree/master
"""
def __init__(
self,
separat... |
pwd_path = os.path.abspath(os.path.dirname(__file__))
class ChineseRecursiveTextSplitter(RecursiveCharacterTextSplitter):
"""Recursive text splitter for Chinese text.
copy from: https://github.com/chatchat-space/Langchain-Chatchat/tree/master
"""
def __init__(
self,
separat... | text_splitter = ChineseRecursiveTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap) | 0 | 2023-12-27 12:14:26+00:00 | 2k |
ConnectAI-E/GitMaya | server/tasks/lark/pull_request.py | [
{
"identifier": "get_bot_by_application_id",
"path": "server/tasks/lark/base.py",
"snippet": "def get_bot_by_application_id(app_id):\n application = (\n db.session.query(IMApplication)\n .filter(\n or_(\n IMApplication.app_id == app_id,\n IMAppli... | import json
import logging
from celery_app import app, celery
from connectai.lark.sdk import FeishuTextMessage
from model.schema import (
ChatGroup,
CodeApplication,
CodeUser,
IMUser,
PullRequest,
Repo,
Team,
TeamMember,
db,
)
from model.team import get_assignees_by_openid
from utils... | 930 |
@celery.task()
def send_pull_request_failed_tip(
content, app_id, message_id, *args, bot=None, **kwargs
):
"""send new card message to user.
Args:
app_id: IMApplication.app_id.
message_id: lark message id.
content: error message
"""
if not bot:
|
@celery.task()
def send_pull_request_failed_tip(
content, app_id, message_id, *args, bot=None, **kwargs
):
"""send new card message to user.
Args:
app_id: IMApplication.app_id.
message_id: lark message id.
content: error message
"""
if not bot: | bot, _ = get_bot_by_application_id(app_id) | 0 | 2023-12-22 02:43:21+00:00 | 2k |
camenduru/AnyDoor-online-hf | dinov2/dinov2/layers/block.py | [
{
"identifier": "Attention",
"path": "dinov2/dinov2/layers/attention.py",
"snippet": "class Attention(nn.Module):\n def __init__(\n self,\n dim: int,\n num_heads: int = 8,\n qkv_bias: bool = False,\n proj_bias: bool = True,\n attn_drop: float = 0.0,\n ... | import logging
import torch
from typing import Callable, List, Any, Tuple, Dict
from torch import nn, Tensor
from .attention import Attention, MemEffAttention
from .drop_path import DropPath
from .layer_scale import LayerScale
from .mlp import Mlp
from xformers.ops import fmha
from xformers.ops import scaled_in... | 1,475 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwigh... | ffn_layer: Callable[..., nn.Module] = Mlp, | 4 | 2023-12-25 04:48:34+00:00 | 2k |
OmchainFoundation/evm-indexer | tests/test_range.py | [
{
"identifier": "Fetcher",
"path": "evm_indexer/fetcher.py",
"snippet": "class Fetcher:\n def __init__(self, node_endpoint, is_poa=True):\n self.web3 = Web3(Web3.HTTPProvider(node_endpoint))\n if is_poa:\n self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)\n \n if not se... | import sys
import os
from evm_indexer.fetcher import Fetcher
from evm_indexer.decoder import Decoder
from evm_indexer.internal_tracer import InternalTracer
from web3 import Web3 | 1,584 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
NODE_URL = 'https://seed.omchain.io'
fetcher = Fetcher(NODE_URL, is_poa=True)
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
NODE_URL = 'https://seed.omchain.io'
fetcher = Fetcher(NODE_URL, is_poa=True) | decoder = Decoder(fetcher=fetcher) | 1 | 2023-12-26 17:39:42+00:00 | 2k |
omkarcloud/google-scraper | src/google_scraper.py | [
{
"identifier": "write_output",
"path": "src/write_output.py",
"snippet": "def write_output(query, data, entity_type,transformer = kebab_case):\n\n query_kebab = transformer(query)\n make_folders(query_kebab)\n\n csv_path = f\"output/{query_kebab}/csv/\" \n json_path = f\"output/{query_kebab... | from typing import List,Optional, Union, Dict
from botasaurus import bt
from .write_output import write_output
from .search import FAILED_DUE_TO_CREDITS_EXHAUSTED, FAILED_DUE_TO_NO_KEY,FAILED_DUE_TO_NOT_SUBSCRIBED, FAILED_DUE_TO_UNKNOWN_ERROR, search | 1,171 |
def clean_data(social_details):
success, credits_exhausted, not_subscribed, unknown_error, no_key = [], [], [], [], []
for detail in social_details:
if detail.get("error") is None:
success.append(detail)
elif detail["error"] == FAILED_DUE_TO_CREDITS_EXHAUSTED:
credits... |
def clean_data(social_details):
success, credits_exhausted, not_subscribed, unknown_error, no_key = [], [], [], [], []
for detail in social_details:
if detail.get("error") is None:
success.append(detail)
elif detail["error"] == FAILED_DUE_TO_CREDITS_EXHAUSTED:
credits... | def search(query: Union[str, List[str]], max: Optional[int] = None, key: Optional[str] =None, use_cache: bool = True) -> Dict: | 5 | 2023-12-30 08:14:05+00:00 | 2k |
AI2lab/comfyUI-tool-2lab | nodes/tool/preview.py | [
{
"identifier": "downloadFileToTempFolder",
"path": "nodes/common/utils.py",
"snippet": "def downloadFileToTempFolder(url: str) -> str:\n try:\n response = requests.get(url)\n response.raise_for_status()\n\n try:\n if not os.path.exists(temp_folder):\n o... | import numpy as np
import torch
from PIL import Image
from ..common.utils import downloadFileToTempFolder
from ..constants import get_project_name, get_project_category | 812 |
NODE_CATEGORY = get_project_category("util/preview")
class ShowText:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"string": ("STRING", {"forceInput": True}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_... |
NODE_CATEGORY = get_project_category("util/preview")
class ShowText:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"string": ("STRING", {"forceInput": True}),
},
"hidden": {
"unique_id": "UNIQUE_ID",
"extra_... | file_path = downloadFileToTempFolder(url) | 0 | 2023-12-24 14:44:13+00:00 | 2k |
Amirtheahmed/ddd-cqrs-fastapi | src/contexts/photostore/photo/application/createone/PhotoCreator.py | [
{
"identifier": "PhotoRepository",
"path": "src/contexts/photostore/photo/domain/PhotoRepository.py",
"snippet": "class PhotoRepository(ABC):\n\n async def create_one(self, photo: Photo) -> NoReturn:\n raise NotImplementedError()"
},
{
"identifier": "Photo",
"path": "src/contexts/p... | from src.contexts.photostore.photo.domain.PhotoRepository import PhotoRepository
from src.contexts.photostore.photo.domain.entities.Photo import Photo
from src.contexts.photostore.photo.domain.entities.PhotoFile import PhotoFile
from src.contexts.photostore.photo.domain.entities.PhotoId import PhotoId
from src.contexts... | 891 |
class PhotoCreator:
def __init__(self, photo_repository: PhotoRepository, event_bus: EventBus):
self.__photo_repository = photo_repository
self.__event_bus = event_bus
|
class PhotoCreator:
def __init__(self, photo_repository: PhotoRepository, event_bus: EventBus):
self.__photo_repository = photo_repository
self.__event_bus = event_bus
| async def run(self, photo_id: PhotoId, name: PhotoName, user_id: UserId, file: PhotoFile): | 2 | 2023-12-27 13:58:25+00:00 | 2k |
JINO-ROHIT/RAG-with-Memory | vlite_db/main.py | [
{
"identifier": "EmbeddingModel",
"path": "vlite_db/model.py",
"snippet": "class EmbeddingModel:\n '''\n EmbeddingModel runs a transformer model and returns the embedding for a given text.\n '''\n def __init__(self, model_name='sentence-transformers/all-MiniLM-L6-v2'):\n self.tokenize... | import numpy as np
import datetime
from uuid import uuid4
from .model import EmbeddingModel
from .utils import chop_and_chunk, cos_sim | 1,156 |
class VLite:
'''
vlite is a simple vector database that stores vectors in a numpy array.
'''
def __init__(self, collection=None,device='mps',model_name=None):
# Filename must be unique between runs. Saving to the same file will append vectors to previous run's vectors
if collection is None:
... |
class VLite:
'''
vlite is a simple vector database that stores vectors in a numpy array.
'''
def __init__(self, collection=None,device='mps',model_name=None):
# Filename must be unique between runs. Saving to the same file will append vectors to previous run's vectors
if collection is None:
... | chunks = chop_and_chunk(text) | 1 | 2023-12-25 07:16:09+00:00 | 2k |
avataar/bg_electricity_regulated_pricing | custom_components/bg_electricity_regulated_pricing/sensor.py | [
{
"identifier": "CONF_TARIFF_TYPE",
"path": "custom_components/bg_electricity_regulated_pricing/const.py",
"snippet": "CONF_TARIFF_TYPE = \"tariff_type\""
},
{
"identifier": "CONF_PROVIDER",
"path": "custom_components/bg_electricity_regulated_pricing/const.py",
"snippet": "CONF_PROVIDER ... | from homeassistant.components.sensor import SensorEntity, SensorEntityDescription, \
SensorStateClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import utcnow
from hom... | 753 | """Sensor platform for bg_electricity_regulated_pricing integration."""
from __future__ import annotations
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize bg_electricity_regulated_pricing conf... | """Sensor platform for bg_electricity_regulated_pricing integration."""
from __future__ import annotations
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize bg_electricity_regulated_pricing conf... | price_day = config_entry.options[CONF_CUSTOM_DAY_PRICE] | 2 | 2023-12-24 11:13:54+00:00 | 2k |
Qazalbash/jaxtro | jaxtro/main.py | [
{
"identifier": "parser",
"path": "jaxtro/utils/parser.py",
"snippet": "def parse_config(config_path: str) -> dict:"
},
{
"identifier": "PopulationGenerator",
"path": "jaxtro/utils/popgen.py",
"snippet": "class PopulationGenerator:\n \"\"\"Class to generate population and save them to... | from .utils import PopulationGenerator, parser | 981 | # Copyright 2023 The Jaxtro 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 or agreed to in writi... | # Copyright 2023 The Jaxtro 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 or agreed to in writi... | pg = PopulationGenerator(general=general, models=models) | 1 | 2023-12-24 21:55:35+00:00 | 2k |
smonsays/modular-hyperteacher | metax/learner/reptile.py | [
{
"identifier": "Dataset",
"path": "metax/data/base.py",
"snippet": "class Dataset(NamedTuple):\n x: Array\n y: Array\n info: Dict = dict()"
},
{
"identifier": "batch_generator",
"path": "metax/data/utils.py",
"snippet": "def batch_generator(rng, datastruct, steps, batch_size):\... | import jax
import jax.numpy as jnp
import jax.tree_util as jtu
import optax
from metax.data import Dataset, batch_generator
from metax.module import LearnedInit
from metax.module.init import LearnedInitMetaParams
from metax.utils import append_keys
from .base import MetaGradLearner | 1,497 | """
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... | class Reptile(MetaGradLearner): | 5 | 2023-12-22 16:35:49+00:00 | 2k |
AContesini/Convert_PDF_to_DOCX_or_vice-versa | venv/Lib/site-packages/tqdm/contrib/concurrent.py | [
{
"identifier": "tqdm",
"path": "venv/Lib/site-packages/tqdm/auto.py",
"snippet": "class tqdm(notebook_tqdm, asyncio_tqdm): # pylint: disable=inconsistent-mro\n pass"
},
{
"identifier": "TqdmWarning",
"path": "venv/Lib/site-packages/tqdm/std.py",
"snippet": "class TqdmWarning(Warning... | from contextlib import contextmanager
from operator import length_hint
from os import cpu_count
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
from warnings import warn | 1,153 | """
Thin wrappers around `concurrent.futures`.
"""
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['thread_map', 'process_map']
@contextmanager
def ensure_lock(tqdm_class, lock_name=""):
"""get (create if necessary) and then restore `tqdm_class`'s lock"""
old_lock = getattr(tqdm_class, '_lock', None)... | """
Thin wrappers around `concurrent.futures`.
"""
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['thread_map', 'process_map']
@contextmanager
def ensure_lock(tqdm_class, lock_name=""):
"""get (create if necessary) and then restore `tqdm_class`'s lock"""
old_lock = getattr(tqdm_class, '_lock', None)... | TqdmWarning, stacklevel=2) | 1 | 2023-12-24 15:46:18+00:00 | 2k |
willfinnigan/RetroBioCat_2 | rbc2/expansion/expanders/action_getters/aizynthfinder/aizynthfinder_actions.py | [
{
"identifier": "does_aizynthfinder_exist",
"path": "rbc2/configs/download_data_files/download_aizynthfinder.py",
"snippet": "def does_aizynthfinder_exist() -> bool:\n if not os.path.exists(f\"{path_to_data_folder}/aizynthfinder/uspto_model.hdf5\"):\n return False\n if not os.path.exists(f\... | import time
import numpy as np
import pandas as pd
from rdkit import Chem
from rbc2.configs.download_data_files.download_aizynthfinder import does_aizynthfinder_exist, \
download_aizynthfinder_model
from rbc2.utils.add_logger import add_logger
from rbc2.configs.data_path import path_to_data_folder
from rbc2.configs... | 1,573 |
data_folder = f'{path_to_data_folder}/aizynthfinder'
class AizynthfinderActionGetter():
def __init__(self,
template_column='retro_template',
cutoff_cumulative=0.995,
cutoff_number=50,
log_level='WARNING'):
self.logger = add_logger('A... |
data_folder = f'{path_to_data_folder}/aizynthfinder'
class AizynthfinderActionGetter():
def __init__(self,
template_column='retro_template',
cutoff_cumulative=0.995,
cutoff_number=50,
log_level='WARNING'):
self.logger = add_logger('A... | fingerprint = fingerprints.get_mol_fingerprint(mol, 2, nBits=len(self.policy_model)) | 6 | 2023-12-30 11:33:41+00:00 | 2k |
DomingoJoseCab/AutoTube | utils/edition/edit.py | [
{
"identifier": "load_videos",
"path": "utils/edition/autoediting.py",
"snippet": "def load_videos(videos_path):\r\n video_list = []\r\n videos = os.listdir(videos_path)\r\n for vid in videos:\r\n video = VideoFileClip(os.path.join(videos_path,vid))\r\n video_list.append(video)\r\... | import os
import json
from moviepy.editor import CompositeVideoClip
from utils.edition.autoediting import load_videos, load_audio, generate_product, generate_intro, generate_outro
from utils.edition.autotext import title_intro
from moviepy.config import change_settings
| 943 | # ==============================================================================
# AutoTube Script
# Creado por: Domingo Caballero
# Canal de YouTube: https://www.youtube.com/@emprendedomingo?=sub_confirmation=1
# Lista de Correo: https://emprendecondomingo.substack.com/
# =========================================... | # ==============================================================================
# AutoTube Script
# Creado por: Domingo Caballero
# Canal de YouTube: https://www.youtube.com/@emprendedomingo?=sub_confirmation=1
# Lista de Correo: https://emprendecondomingo.substack.com/
# =========================================... | intro = generate_intro(videos, audio_intro)
| 3 | 2023-12-28 16:15:37+00:00 | 2k |
gregorybchris/typogenetics | tests/test_search.py | [
{
"identifier": "Editor",
"path": "typogenetics/search.py",
"snippet": "class Editor:\n PROB_MUTATE = 0.80\n PROB_INSERT = 0.10\n PROB_DELETE = 0.10\n\n @classmethod\n def edit(cls, strand: Strand, rng: Generator) -> Strand:\n edit_type = cls.select_edit_type(rng)\n if edit_... | import numpy as np
from typogenetics.search import Editor, EditType
from typogenetics.typogenetics import Strand | 993 |
class TestSearch:
def test_select_edit_type(self) -> None:
rng = np.random.default_rng(42)
assert Editor.select_edit_type(rng) == EditType.INSERT
def test_mutate(self) -> None:
rng = np.random.default_rng(42)
|
class TestSearch:
def test_select_edit_type(self) -> None:
rng = np.random.default_rng(42)
assert Editor.select_edit_type(rng) == EditType.INSERT
def test_mutate(self) -> None:
rng = np.random.default_rng(42) | strand = Strand.from_str("ACGT") | 2 | 2023-12-28 08:59:06+00:00 | 2k |
chaoren2357/gsplatstudio | gsplatstudio/data/processor/colmapWcam_processor.py | [
{
"identifier": "BaseDataProcessor",
"path": "gsplatstudio/data/processor/base_processor.py",
"snippet": "class BaseDataProcessor(ABC):\n def __init__(self, cfg, logger, source_path) -> None:\n self.cfg = parse_structured(self.config_class, cfg)\n self.logger = logger\n self.sour... | import gsplatstudio
import sqlite3
from gsplatstudio.utils.type_utils import *
from gsplatstudio.data.processor.base_processor import BaseDataProcessor
from pathlib import Path
from gsplatstudio.utils.general_utils import load_json
from gsplatstudio.utils.camera_utils import transform_camera_from_carla_matrix_to_colmap... | 1,346 |
@dataclass
class ColmapWithCamProcessorConfig:
use_gpu: bool = True
camera: str = "OPENCV"
map_ba_global_function_tolerance: float = 0.000001
@gsplatstudio.register("colmap_with_cam-processor")
class ColmapWithCamProcessor(BaseDataProcessor):
def __init__(self, cfg, logger, source_path) -> None:
... |
@dataclass
class ColmapWithCamProcessorConfig:
use_gpu: bool = True
camera: str = "OPENCV"
map_ba_global_function_tolerance: float = 0.000001
@gsplatstudio.register("colmap_with_cam-processor")
class ColmapWithCamProcessor(BaseDataProcessor):
def __init__(self, cfg, logger, source_path) -> None:
... | focal_length = fov_to_focal_length(intrinsics['fov'], intrinsics['width']) | 3 | 2023-12-22 08:27:26+00:00 | 2k |
ddjerqq/beam | src/util.py | [
{
"identifier": "User",
"path": "src/types/user.py",
"snippet": "class User:\n id: int\n username: str\n avatar_url: str"
},
{
"identifier": "Video",
"path": "src/types/video.py",
"snippet": "class Video:\n \"\"\"Tiktok video object\"\"\"\n\n id: str\n \"\"\"Unique iden... | import os
import httpx
from src.types.user import User
from src.types.video import Video | 661 |
def get_env(key: str, default: str = None) -> str:
"""
gets the environment variable with the given key,
or raises an exception if the default is not supplied.
"""
var = os.getenv("APP_ID", default)
if var is not None:
return var
raise Exception(f"Environment variable {key} not... |
def get_env(key: str, default: str = None) -> str:
"""
gets the environment variable with the given key,
or raises an exception if the default is not supplied.
"""
var = os.getenv("APP_ID", default)
if var is not None:
return var
raise Exception(f"Environment variable {key} not... | def video_info_to_webhook_payload(author: User, video: Video) -> dict[str, str]: | 1 | 2023-12-28 23:18:25+00:00 | 2k |
onestepai/api_rag | service.py | [
{
"identifier": "ServiceApiConfig",
"path": "src/config/ServiceApiConfig.py",
"snippet": "class ServiceApiConfig(ServiceApiConfigBase):\n def __init__(self):\n ServiceApiConfigBase.__init__(self,\n url_prefix=DockerConfig.URL_PREFIX + DockerConfig.API_VERSI... | import logging
from src.config.ServiceApiConfig import ServiceApiConfig
from src.config.DockerConfig import DockerConfig
from src.api_rag.ModelHandler import ModelHandler | 1,153 |
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == '__main__':
|
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == '__main__': | config = ServiceApiConfig() | 0 | 2023-12-28 03:13:03+00:00 | 2k |
DerwenAI/textgraphs | textgraphs/graph.py | [
{
"identifier": "Edge",
"path": "textgraphs/elem.py",
"snippet": "class Edge:\n \"\"\"\nA data class representing an edge between two nodes.\n \"\"\"\n src_node: int\n dst_node: int\n kind: RelEnum\n rel: str\n prob: float\n count: int = 1"
},
{
"identifier": "Node",
... | from collections import OrderedDict
from icecream import ic # pylint: disable=E0401
from .elem import Edge, Node, NodeEnum, RelEnum
import json
import typing
import networkx as nx # pylint: disable=E0401
import spacy # pylint: disable=E0401 | 1,287 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This class implements a generic, in-memory graph data structure used
to represent the _lemma graph_.
see copyright/license https://huggingface.co/spaces/DerwenAI/textgraphs/blob/main/README.md
"""
##################################################################... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This class implements a generic, in-memory graph data structure used
to represent the _lemma graph_.
see copyright/license https://huggingface.co/spaces/DerwenAI/textgraphs/blob/main/README.md
"""
##################################################################... | self.edges: typing.Dict[ str, Edge ] = {} | 0 | 2023-12-25 11:42:53+00:00 | 2k |
Noubissie237/StockManagment | StockManagment/App/views.py | [
{
"identifier": "panier_cookie",
"path": "StockManagment/App/utils.py",
"snippet": "def panier_cookie(request):\n articles = []\n\n commande = {\n 'get_panier_total':0,\n 'get_panier_article':0,\n 'produit_physique': True,\n }\n\n nombre_article = commande['get_panier_ar... | from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from .models import *
from django.contrib.auth.decorators import login_required
from datetime import datetime
from .utils import panier_cookie, data_cookie, getDataFromApi
from .forms import LoginForm
from django.contrib.au... | 1,475 |
@login_required(login_url='/login')
def shop(request, *args, **kwargs):
"""Vue des produits"""
produits = Produit.objects.all()
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'produits': pro... |
@login_required(login_url='/login')
def shop(request, *args, **kwargs):
"""Vue des produits"""
produits = Produit.objects.all()
data = data_cookie(request)
articles = data['articles']
commande = data['commande']
nombre_article = data['nombre_article']
context = {
'produits': pro... | cookie_panier = panier_cookie(request) | 0 | 2023-12-29 11:13:34+00:00 | 2k |
kokiez/raydium-convert-SOLorTokens | main.py | [
{
"identifier": "fetch_pool_keys",
"path": "pools.py",
"snippet": "def fetch_pool_keys(mint: str):\r\n amm_info = {}\r\n all_pools = {}\r\n try:\r\n # Using this so it will be faster else no option, we go the slower way.\r\n with open('all_pools.json', 'r') as file:\r\n ... | from solana.rpc.commitment import Commitment
from solana.rpc.api import Client
from solana.transaction import Transaction
from solders.keypair import Keypair
from pools import fetch_pool_keys, make_simulate_pool_info_instruction
from ast import literal_eval
import re
| 1,536 |
LIQUIDITY_FEES_NUMERATOR = 25
LIQUIDITY_FEES_DENOMINATOR = 10000
"""
Required Variables
"""
endpoint = "your_rpc_url"
payer = Keypair.from_base58_string("your_private_key")
token = "ca of your mint/mint address"
solana_client = Client(endpoint, commitment=Commitment("confirmed"), blockhash_cache=T... |
LIQUIDITY_FEES_NUMERATOR = 25
LIQUIDITY_FEES_DENOMINATOR = 10000
"""
Required Variables
"""
endpoint = "your_rpc_url"
payer = Keypair.from_base58_string("your_private_key")
token = "ca of your mint/mint address"
solana_client = Client(endpoint, commitment=Commitment("confirmed"), blockhash_cache=T... | pool_keys = fetch_pool_keys(mint)
| 0 | 2023-12-29 12:35:38+00:00 | 2k |
proger/nanokitchen | blockdiag_linear.py | [
{
"identifier": "StructuredLinear",
"path": "structured_linear.py",
"snippet": "class StructuredLinear(nn.Module):\n\n def __init__(self, in_features, out_features, bias=True, device=None, dtype=None):\n \"\"\"Subclasses should call reset_parameters\n \"\"\"\n factory_kwargs = {'... | import math
import torch
import torch.nn as nn
from einops import rearrange
from structured_linear import StructuredLinear
from blockdiag_multiply import blockdiag_multiply | 1,073 | # Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers
class BlockdiagLinear(StructuredLinear):
def __init__(self, *args, nblocks=4, shuffle=False, **kwargs):
"""shuffle: apply channel_shuffle operation before the matmul as in ShuffleNet
"""
super().__init__(*a... | # Adapted from https://github.com/HazyResearch/fly/tree/master/src/models/layers
class BlockdiagLinear(StructuredLinear):
def __init__(self, *args, nblocks=4, shuffle=False, **kwargs):
"""shuffle: apply channel_shuffle operation before the matmul as in ShuffleNet
"""
super().__init__(*a... | output = blockdiag_multiply(x, self.weight) | 1 | 2023-12-27 12:13:00+00:00 | 2k |
karloskar/homeassistant-goecontroller-mqtt | custom_components/goecontroller_mqtt/switch.py | [
{
"identifier": "SWITCHES",
"path": "custom_components/goecontroller_mqtt/definitions/switch.py",
"snippet": "SWITCHES: tuple[GoEControllerSwitchEntityDescription, ...] = (\n GoEControllerSwitchEntityDescription(\n key=\"tse\",\n name=\"Time server enabled\",\n entity_category=En... | import logging
from homeassistant import config_entries, core
from homeassistant.components import mqtt
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import callback
from .definitions.switch import SWITCHES, GoEControllerSwitchEntityDescription
from .entity import GoEControllerEntity | 776 | """The go-eController (MQTT) switch."""
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Config entry setup."""
async_add_entities(
GoEControllerSwitch(config_entry, descripti... | """The go-eController (MQTT) switch."""
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: core.HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities,
):
"""Config entry setup."""
async_add_entities(
GoEControllerSwitch(config_entry, descripti... | entity_description: GoEControllerSwitchEntityDescription | 1 | 2023-12-22 11:32:11+00:00 | 2k |
T0kyoB0y/PotatoWidgets | PotatoWidgets/Widget/_Common/_BasicProps.py | [
{
"identifier": "Listener",
"path": "PotatoWidgets/Variable/_Listener.py",
"snippet": "class Listener(Variable):\n def __init__(self, callback, initial_value=None):\n super().__init__(initial_value)\n self._callback = callback\n self._thread = None\n self._stop_thread = th... | from ...__Import import *
from ...Variable import Listener, Poll, Variable | 1,380 |
class BasicProps(Gtk.Widget):
def __init__(
self,
halign,
valign,
hexpand,
vexpand,
active,
visible,
classname,
# tooltip,
css,
size=[10, 10],
):
Gtk.Widget.__init__(self)
self.set_hexpand(True if hexpand e... |
class BasicProps(Gtk.Widget):
def __init__(
self,
halign,
valign,
hexpand,
vexpand,
active,
visible,
classname,
# tooltip,
css,
size=[10, 10],
):
Gtk.Widget.__init__(self)
self.set_hexpand(True if hexpand e... | if isinstance(i, (Listener, Variable, Poll)): | 1 | 2023-12-30 01:34:01+00:00 | 2k |
Zerohertz/Streamlit-Quant | lib/visual.py | [
{
"identifier": "_main",
"path": "lib/layout.py",
"snippet": "def _main():\n layout = _default()\n layout.height = 500 * st.session_state[\"scale\"]\n layout.width = 1000\n layout.xaxis = {\n \"type\": \"category\",\n \"gridcolor\": \"black\",\n \"tickangle\": -45,\n ... | import plotly.graph_objs as go
import streamlit as st
import zerohertzLib as zz
from plotly.subplots import make_subplots
from lib.layout import _main, _transaction
from lib.util import _color | 714 |
def candle():
data, xdata = st.session_state["cache"]["data"], st.session_state["cache"]["xdata"]
st.session_state["cache"]["candle"] = go.Candlestick(
x=xdata,
open=data.Open,
high=data.High,
low=data.Low,
close=data.Close,
increasing={"line": {"color": "red"}... |
def candle():
data, xdata = st.session_state["cache"]["data"], st.session_state["cache"]["xdata"]
st.session_state["cache"]["candle"] = go.Candlestick(
x=xdata,
open=data.Open,
high=data.High,
low=data.Low,
close=data.Close,
increasing={"line": {"color": "red"}... | colors = _color(4, 0.5, "Set1") | 2 | 2023-12-26 11:29:06+00:00 | 2k |
acman/py_june | comments/views.py | [
{
"identifier": "Post",
"path": "posts/models.py",
"snippet": "class Post(SlugModel):\n title = models.CharField(max_length=50)\n content = models.TextField(max_length=500, blank=True)\n author = models.ForeignKey(\"users.ForumUser\", on_delete=models.CASCADE)\n category = models.ForeignKey(... | from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.views import View
from posts.models import Post
from .forms import CommentForm
from .models import Comment | 779 |
class CreateCommentView(LoginRequiredMixin, View):
template_name = "comments/comment_form.html"
login_url = "/users/login/"
def get(self, request: HttpRequest, post_slug: str) -> HttpResponse:
post = get_object_or_404(Post, slug=post_slug)
form = CommentForm()
return render(requ... |
class CreateCommentView(LoginRequiredMixin, View):
template_name = "comments/comment_form.html"
login_url = "/users/login/"
def get(self, request: HttpRequest, post_slug: str) -> HttpResponse:
post = get_object_or_404(Post, slug=post_slug)
form = CommentForm()
return render(requ... | comment = get_object_or_404(Comment, pk=comment_pk) | 2 | 2023-12-23 09:36:46+00:00 | 2k |
pkariz/grin-explorer | backend/api/signals/receivers.py | [
{
"identifier": "Block",
"path": "backend/api/models.py",
"snippet": "class Block(TimeStampedModel):\n blockchain = models.ForeignKey(\n Blockchain, related_name='blocks', on_delete=models.CASCADE)\n hash = models.CharField(\n primary_key=True,\n max_length=64,\n valida... | from django.db.models.signals import post_save
from django.dispatch import receiver
from backend.api.models import Block, Reorg
from backend.api.helpers import fix_outputs_and_inputs_from_reorg
import logging | 1,477 |
logger = logging.getLogger(__name__)
@receiver(
post_save,
|
logger = logging.getLogger(__name__)
@receiver(
post_save, | sender=Block, | 0 | 2023-12-24 22:15:11+00:00 | 2k |
CodeWithEmad/num2fa | num2fa/converters/word_converter.py | [
{
"identifier": "DEFAULT_SCIENTIFIC_SEPARATOR",
"path": "num2fa/constants.py",
"snippet": "DEFAULT_SCIENTIFIC_SEPARATOR = \" در ده به توان \""
},
{
"identifier": "WORDS_DECIMAL_SEPARATOR",
"path": "num2fa/constants.py",
"snippet": "WORDS_DECIMAL_SEPARATOR = \" و \""
},
{
"identif... | from decimal import Decimal
from fractions import Fraction
from functools import singledispatch
from typing import Union
from num2fa.constants import (
DEFAULT_SCIENTIFIC_SEPARATOR,
WORDS_DECIMAL_SEPARATOR,
WORDS_FRACTION_SEPARATOR,
WORDS_NEGATIVE,
ZERO,
)
from num2fa.utils import _natural_words, _n... | 1,135 | """Provide functions to convert a number to Persian words."""
def _exp_words(
number: str,
positive: str,
negative: str,
decimal_separator: str,
scientific_separator: str,
) -> str:
# exponent
base, e, exponent = number.partition("e")
if exponent:
return (
_point_... | """Provide functions to convert a number to Persian words."""
def _exp_words(
number: str,
positive: str,
negative: str,
decimal_separator: str,
scientific_separator: str,
) -> str:
# exponent
base, e, exponent = number.partition("e")
if exponent:
return (
_point_... | + _natural_words(numerator) | 5 | 2023-12-30 14:28:57+00:00 | 2k |
the-seeds/cardinal | src/cardinal/core/extractor/base_extractor.py | [
{
"identifier": "Extractor",
"path": "src/cardinal/core/schema/extractor.py",
"snippet": "class Extractor(ABC):\n @abstractmethod\n def load(self, input_files: List[Path], user_id: str, verbose: Optional[bool] = False) -> None:\n r\"\"\"\n Loads the files into database.\n\n Ar... | import os
from multiprocessing import Pool
from pathlib import Path
from typing import TYPE_CHECKING, List, Optional
from tqdm import tqdm
from ..schema import Extractor, Leaf, LeafIndex
from ..splitter import CJKTextSplitter
from ..model import EmbedOpenAI
from ..schema import StringKeyedStorage, VectorStore
... | 780 |
if TYPE_CHECKING:
class BaseExtractor(Extractor):
def __init__(
self, vectorizer: "EmbedOpenAI", storage: "StringKeyedStorage[Leaf]", vectorstore: "VectorStore[LeafIndex]"
) -> None:
self._vectorizer = vectorizer
self._storage = storage
self._vectorstore = vectorstore
... |
if TYPE_CHECKING:
class BaseExtractor(Extractor):
def __init__(
self, vectorizer: "EmbedOpenAI", storage: "StringKeyedStorage[Leaf]", vectorstore: "VectorStore[LeafIndex]"
) -> None:
self._vectorizer = vectorizer
self._storage = storage
self._vectorstore = vectorstore
... | leaf_index = LeafIndex(user_id=user_id) | 2 | 2023-12-26 14:16:40+00:00 | 2k |
datrocity/pond | tests/test_conventions.py | [
{
"identifier": "METADATA_DIRNAME",
"path": "pond/conventions.py",
"snippet": "METADATA_DIRNAME = '_pond'"
},
{
"identifier": "MANIFEST_FILENAME",
"path": "pond/conventions.py",
"snippet": "MANIFEST_FILENAME = 'manifest.yml'"
},
{
"identifier": "version_data_location",
"path"... | from pond.conventions import (
METADATA_DIRNAME,
MANIFEST_FILENAME,
version_data_location,
version_manifest_location,
version_uri,
urijoinpath,
)
from pond.version_name import SimpleVersionName | 744 |
def test_urijoinpath():
joined = urijoinpath('a', 'b/', 'c/')
expected = 'a/b/c'
assert joined == expected
def test_data_location():
|
def test_urijoinpath():
joined = urijoinpath('a', 'b/', 'c/')
expected = 'a/b/c'
assert joined == expected
def test_data_location(): | location = version_data_location('abc/', 'blah.bin') | 2 | 2023-12-24 13:05:58+00:00 | 2k |
Zitronenjoghurt/Colonaut | src/constants/locale_translator.py | [
{
"identifier": "construct_path",
"path": "src/utils/file_operations.py",
"snippet": "def construct_path(relative_path: str) -> str:\n path_parts = relative_path.split(\"/\")\n absolute_path = os.path.join(ROOT_DIR, *path_parts)\n return absolute_path"
},
{
"identifier": "files_in_direc... | from src.utils.file_operations import construct_path, files_in_directory, file_to_dict, str_to_file
from .locales import Locales | 1,010 |
LOCALES_FILE_PATH = construct_path("src/data/locale/{language}/")
OUTPUT_TXT_FILE_PATH = construct_path("locale_{language}.txt")
LANGUAGES = ["en"]
class LocaleTranslator():
_instance = None
|
LOCALES_FILE_PATH = construct_path("src/data/locale/{language}/")
OUTPUT_TXT_FILE_PATH = construct_path("locale_{language}.txt")
LANGUAGES = ["en"]
class LocaleTranslator():
_instance = None | KEYS = Locales | 4 | 2023-12-22 21:24:33+00:00 | 2k |
daojiAnime/aio_retrying | tests/test_condition_error.py | [
{
"identifier": "ConditionError",
"path": "aio_retrying.py",
"snippet": "class ConditionError(Exception):\n pass"
},
{
"identifier": "retry",
"path": "aio_retrying.py",
"snippet": "def retry(\n fn: Callable = None,\n *,\n attempts: int = 0,\n callback: Optional[Callable] =... | import asyncio
import pytest
from aio_retrying import ConditionError, retry | 745 |
async def test_timeout_is_not_none_and_not_async():
@retry(timeout=0.5)
def not_coro():
pass
|
async def test_timeout_is_not_none_and_not_async():
@retry(timeout=0.5)
def not_coro():
pass
| with pytest.raises(ConditionError): | 0 | 2023-12-30 02:48:40+00:00 | 2k |
xIMRANx/secret_postcard | app/handlers/user/file.py | [
{
"identifier": "User",
"path": "app/db/functions.py",
"snippet": "class User(models.User):\n @classmethod\n async def is_registered(cls, telegram_id: int) -> Union[models.User, bool]:\n try:\n return await cls.get(telegram_id=telegram_id)\n except DoesNotExist:\n ... | from aiogram import Router, Bot, F
from aiogram.types import Message
from app.db.functions import User
from app.db.functions import Card
from app.keyboards.inline import get_approve_keyboard
from app.config import Config | 1,167 |
router = Router()
@router.message(F.content_type.in_({"photo", "video", "animation"}))
async def get_postcard(message: Message, bot: Bot, config: Config):
if await Card.check_exists(message.from_user.id):
await message.answer("Вы уже отправили свою открытку!")
return
postcard_type = message... |
router = Router()
@router.message(F.content_type.in_({"photo", "video", "animation"}))
async def get_postcard(message: Message, bot: Bot, config: Config):
if await Card.check_exists(message.from_user.id):
await message.answer("Вы уже отправили свою открытку!")
return
postcard_type = message... | if not await User.is_registered(user_id): | 0 | 2023-12-30 07:57:10+00:00 | 2k |
akkoaya/ArticleSpider | ArticleSpider/spiders/cnblog.py | [
{
"identifier": "CnblogItem",
"path": "ArticleSpider/items.py",
"snippet": "class CnblogItem(scrapy.Item):\n url = scrapy.Field()\n url_object_id = scrapy.Field()\n title = scrapy.Field()\n date = scrapy.Field()\n writer_id = scrapy.Field()\n views_num = scrapy.Field()\n comments_n... | import scrapy
import datetime
import re
from scrapy.http import Request
from urllib import parse
from ..items import CnblogItem
from ..utils.common import get_md5
from scrapy.loader import ItemLoader
from scrapy_redis.spiders import RedisSpider | 1,196 |
class CnblogSpider(scrapy.Spider):
name = "cnblog"
allowed_domains = ["www.cnblogs.com"]
start_urls = ["https://www.cnblogs.com/sitehome/p/1"]
# redis_key = 'cnblog:start_urls'
next_url = "https://www.cnblogs.com/sitehome/p/{0}"
# headers = {
# "User-Agent":"Mozilla/5.0 (Windows NT 10... |
class CnblogSpider(scrapy.Spider):
name = "cnblog"
allowed_domains = ["www.cnblogs.com"]
start_urls = ["https://www.cnblogs.com/sitehome/p/1"]
# redis_key = 'cnblog:start_urls'
next_url = "https://www.cnblogs.com/sitehome/p/{0}"
# headers = {
# "User-Agent":"Mozilla/5.0 (Windows NT 10... | item_loader.add_value("url_object_id", get_md5(response.url)) | 1 | 2023-12-29 15:05:22+00:00 | 2k |
Asa-Nisi-Masa/christmas-tree | christmas_tree/calculations/compute_coords.py | [
{
"identifier": "PATH_SAVE",
"path": "christmas_tree/common/settings.py",
"snippet": "PATH_SAVE = \"coordinates.csv\""
},
{
"identifier": "TOTAL_LEDS",
"path": "christmas_tree/common/settings.py",
"snippet": "TOTAL_LEDS = 500"
}
] | from collections import defaultdict, namedtuple
from pathlib import Path
from typing import Dict, List, Optional
from tqdm import tqdm
from christmas_tree.common.settings import PATH_SAVE, TOTAL_LEDS
import cv2
import numpy as np | 1,251 | contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
centers = []
for contour in contours:
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
centers.append(Point(cX, cY))
... |
### Adjust these three parameters if lots of LEDs cannot be detected
LOWER_THRESHOLD = 135
UPPER_THRESHOLD = 255
MAX_DIST = 40
###
ANGLES = [0, 45, 90, 135, 180, 225, 270, 315]
Point = namedtuple("Point", ["x", "y"])
# get height and width of images from one of the frames
path = Path("frames") / str(ANGLES[0]) / "... | with open(PATH_SAVE, "w") as file: | 0 | 2023-12-30 12:25:19+00:00 | 2k |
YYJeffrey/july_server | app/api/v2/message.py | [
{
"identifier": "auth",
"path": "app/lib/token.py",
"snippet": "def verify_token(token):\ndef generate_token(user_id):"
},
{
"identifier": "db",
"path": "app/model/base.py",
"snippet": "class BaseModel(db.Model):\n def __getitem__(self, key):\n def init_on_load(self):\n def __se... | from flask import g
from app import auth, db
from app.lib.exception import Success, Updated
from app.lib.red_print import RedPrint
from app.model.message import Message
from app.service.message import get_message_list | 1,304 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2023 by Jeffrey.
:license: Apache 2.0, see LICENSE for more details.
"""
api = RedPrint('message')
@api.route('/', methods=['GET'])
@auth.login_required
def get_messages():
"""
获取消息
"""
messages = get_message_list()
return Success(data=messages... | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2023 by Jeffrey.
:license: Apache 2.0, see LICENSE for more details.
"""
api = RedPrint('message')
@api.route('/', methods=['GET'])
@auth.login_required
def get_messages():
"""
获取消息
"""
messages = get_message_list()
return Success(data=messages... | return Updated() | 3 | 2023-12-30 04:08:35+00:00 | 2k |
lchen1019/Image_Cropper | ISAT/widgets/polygon.py | [
{
"identifier": "Object",
"path": "ISAT/annotation.py",
"snippet": "class Object:\n def __init__(self, category:str, group:int, segmentation, area, layer, bbox, iscrowd=0, note=''):\n self.category = category\n self.group = group\n self.segmentation = segmentation\n self.a... | from PyQt5 import QtCore, QtWidgets, QtGui
from ISAT.annotation import Object
from ISAT.configs import STATUSMode, CLICKMode, DRAWMode, CONTOURMode
import typing | 1,085 | # -*- coding: utf-8 -*-
# @Author : LG
class PromptPoint(QtWidgets.QGraphicsPathItem):
def __init__(self, pos, type=0):
super(PromptPoint, self).__init__()
self.color = QtGui.QColor('#0000FF') if type==0 else QtGui.QColor('#00FF00')
self.color.setAlpha(255)
self.painterpath = QtG... | # -*- coding: utf-8 -*-
# @Author : LG
class PromptPoint(QtWidgets.QGraphicsPathItem):
def __init__(self, pos, type=0):
super(PromptPoint, self).__init__()
self.color = QtGui.QColor('#0000FF') if type==0 else QtGui.QColor('#00FF00')
self.color.setAlpha(255)
self.painterpath = QtG... | if self.scene().mode == STATUSMode.CREATE: # CREATE | 1 | 2023-12-24 16:19:16+00:00 | 2k |
aoki-h-jp/crypto-listed-detector | crypto_listed_detector/detector.py | [
{
"identifier": "BinanceFetch",
"path": "crypto_listed_detector/fetchapi/binance.py",
"snippet": "class BinanceFetch:\n _BASE_URL = \"https://fapi.binance.com\"\n\n def __init__(self):\n pass\n\n def get_linear_ticker(self):\n url = self._BASE_URL + \"/fapi/v1/exchangeInfo\"\n ... | import json
from crypto_listed_detector.fetchapi.binance import BinanceFetch
from crypto_listed_detector.fetchapi.bitget import BitgetFetch
from crypto_listed_detector.fetchapi.bybit import BybitFetch
from crypto_listed_detector.fetchapi.gateio import GateioFetch
from crypto_listed_detector.fetchapi.kucoin import Kucoi... | 1,437 | """
crypto-listed-detector
"""
class Detector:
def __init__(self):
"""
Init all fetchers
"""
| """
crypto-listed-detector
"""
class Detector:
def __init__(self):
"""
Init all fetchers
""" | self.bybit = BybitFetch() | 2 | 2023-12-27 10:39:18+00:00 | 2k |
harvestingmoon/StableVisionBot | bot.py | [
{
"identifier": "BackEnd",
"path": "backend.py",
"snippet": "class BackEnd:\n def __init__(self,model_id) -> None:\n self.model = None\n self.curr_picture = None \n self.final_img = None\n self.call = {1:False,2:False}\n self.model_id = (model_id if model_id else \"... | from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update,InlineKeyboardButton,InlineKeyboardMarkup
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
ConversationHandler,
MessageHandler,
CallbackQueryHandler,
filters,
CallbackContext,
)
from backend import... | 1,161 | # Simple telegram bot that takes uses stable diffusion
''' Importing YAML'''
with open("config .yaml", "r") as f:
config = yaml.safe_load(f)
model = config['model']
api_key = config['API_KEY']
''' States for bot'''
ONE,TWO,DOCUMENT,PHOTO = range(4)
START,T2IMG,T2IMG2,IMG2IMG,IMG2IMG2,OUTPUT= range(6)
''' User ... | # Simple telegram bot that takes uses stable diffusion
''' Importing YAML'''
with open("config .yaml", "r") as f:
config = yaml.safe_load(f)
model = config['model']
api_key = config['API_KEY']
''' States for bot'''
ONE,TWO,DOCUMENT,PHOTO = range(4)
START,T2IMG,T2IMG2,IMG2IMG,IMG2IMG2,OUTPUT= range(6)
''' User ... | engine = BackEnd(model) | 0 | 2023-12-22 07:25:26+00:00 | 2k |
khabbazan/Mattermost-Subscriptions | apps/chat/gql/subscriptions.py | [
{
"identifier": "MessageQueryType",
"path": "apps/chat/gql/types.py",
"snippet": "class MessageQueryType(graphene.ObjectType):\n \"\"\"\n GraphQL type representing a message in a chat system.\n \"\"\"\n\n id = graphene.String(description=\"Unique identifier of the message.\")\n\n def reso... | import graphene
from apps.chat.gql.types import MessageQueryType
from helpers.channels_graphql_ws import subscription | 652 |
class OnNewChatMessage(subscription.Subscription):
"""
GraphQL Subscription for new chat messages.
This subscription allows clients to listen for new messages on a specified channel.
"""
channel_identifier = graphene.String()
|
class OnNewChatMessage(subscription.Subscription):
"""
GraphQL Subscription for new chat messages.
This subscription allows clients to listen for new messages on a specified channel.
"""
channel_identifier = graphene.String() | message = graphene.Field(MessageQueryType) | 0 | 2023-12-25 11:40:56+00:00 | 2k |
Hatins/DEOE | models/detection/yolox_extension/models/yolo_pafpn.py | [
{
"identifier": "BaseConv",
"path": "models/detection/yolox/models/network_blocks.py",
"snippet": "class BaseConv(nn.Module):\n \"\"\"A Conv2d -> Batchnorm -> silu/leaky relu block\"\"\"\n\n def __init__(\n self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act=\"silu\"\n... | from typing import Dict, Optional, Tuple
from torch import compile as th_compile
from ...yolox.models.network_blocks import BaseConv, CSPLayer, DWConv
from data.utils.types import BackboneFeatures
import torch as th
import torch.nn as nn | 1,394 | """
Original Yolox PAFPN code with slight modifications
"""
try:
except ImportError:
th_compile = None
class YOLOPAFPN(nn.Module):
"""
Removed the direct dependency on the backbone.
"""
def __init__(
self,
depth: float = 1.0,
in_stages: Tuple[int, ...] = (2,... | """
Original Yolox PAFPN code with slight modifications
"""
try:
except ImportError:
th_compile = None
class YOLOPAFPN(nn.Module):
"""
Removed the direct dependency on the backbone.
"""
def __init__(
self,
depth: float = 1.0,
in_stages: Tuple[int, ...] = (2,... | self.C3_p4 = CSPLayer( | 1 | 2023-12-29 04:04:34+00:00 | 2k |
yeyingdege/ctr-din-pytorch | din/model.py | [
{
"identifier": "EmbeddingLayer",
"path": "din/embedding.py",
"snippet": "class EmbeddingLayer(nn.Module):\n def __init__(self, num_emb, embedding_dim):\n super(EmbeddingLayer, self).__init__()\n\n self.embeddings = nn.Embedding(num_emb, embedding_dim)\n nn.init.xavier_uniform_(s... | import torch
import torch.nn as nn
from torch.nn import functional as F
from .embedding import EmbeddingLayer
from .fc import FCLayer
from .attention import DinAttentionLayer | 1,019 |
class DeepInterestNetwork(nn.Module):
def __init__(self, n_uid, n_mid, n_cat, EMBEDDING_DIM, HIDDEN_DIM=[162,200,80,2]):
super(DeepInterestNetwork, self).__init__()
self.embedding_dim = EMBEDDING_DIM
self.hid_dim = HIDDEN_DIM
# embeddings
self.uid_embeddings = EmbeddingLa... |
class DeepInterestNetwork(nn.Module):
def __init__(self, n_uid, n_mid, n_cat, EMBEDDING_DIM, HIDDEN_DIM=[162,200,80,2]):
super(DeepInterestNetwork, self).__init__()
self.embedding_dim = EMBEDDING_DIM
self.hid_dim = HIDDEN_DIM
# embeddings
self.uid_embeddings = EmbeddingLa... | FCLayer(mlp_input_dim, hidden_size=self.hid_dim[1], bias=True, batch_norm=True, activation='dice'), | 1 | 2023-12-27 05:53:50+00:00 | 2k |
iamlooper/VIC-TG-Bot | app/core/client/filters.py | [
{
"identifier": "Config",
"path": "app/config.py",
"snippet": "class _Config:\n class CMD:\n def __init__(self, func, path, doc):\n def __init__(self):\n def __str__(self):"
},
{
"identifier": "Conversation",
"path": "app/core/client/conversation.py",
"snippet": "class Co... | from pyrogram import filters as _filters
from pyrogram.types import Message
from app import Config
from app.core.client.conversation import Conversation | 867 |
# Overall BOT filters
convo_filter = _filters.create(
lambda _, __, message: (message.chat.id in Conversation.CONVO_DICT.keys())
and (not message.reactions)
)
def cmd_check(message: Message, trigger: str) -> bool:
start_str = message.text.split(maxsplit=1)[0]
cmd = start_str.replace(trigger, "", 1)... |
# Overall BOT filters
convo_filter = _filters.create(
lambda _, __, message: (message.chat.id in Conversation.CONVO_DICT.keys())
and (not message.reactions)
)
def cmd_check(message: Message, trigger: str) -> bool:
start_str = message.text.split(maxsplit=1)[0]
cmd = start_str.replace(trigger, "", 1) | return bool(cmd in Config.CMD_DICT.keys()) | 0 | 2023-12-24 05:00:58+00:00 | 2k |
Enthusiasm23/primkit | src/primkit/utils/LoggerSetup.py | [
{
"identifier": "LOG_LEVEL",
"path": "src/primkit/config.py",
"snippet": "LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO') # 日志级别"
},
{
"identifier": "LOG_FILE",
"path": "src/primkit/config.py",
"snippet": "LOG_FILE = os.environ.get('LOG_FILE', None) # 日志文件路径"
},
{
"identifier":... | import logging
import logging.handlers
from ..config import LOG_LEVEL, LOG_FILE, LOG_FORMAT, \
LOG_FILE_MODE, MAX_LOG_SIZE, BACKUP_COUNT, LOG_STREAM | 741 |
def setup_logging(
level=None,
log_file=None,
format=None,
log_file_mode=None,
max_log_size=None,
backup_count=None,
stream=None
):
"""
Configure logging for the application.
:param level: The logging level, e.g., 'DEBUG', 'INFO', 'WARNING'. Defaults to value from config.py bu... |
def setup_logging(
level=None,
log_file=None,
format=None,
log_file_mode=None,
max_log_size=None,
backup_count=None,
stream=None
):
"""
Configure logging for the application.
:param level: The logging level, e.g., 'DEBUG', 'INFO', 'WARNING'. Defaults to value from config.py bu... | log_file_mode = log_file_mode if log_file_mode is not None else LOG_FILE_MODE | 3 | 2023-12-25 14:12:46+00:00 | 2k |
Wangyuhao06/2022-adhoc | src/env.py | [
{
"identifier": "random_waypoint",
"path": "pymobility/models/mobility.py",
"snippet": "def random_waypoint(*args, **kwargs):\n return iter(RandomWaypoint(*args, **kwargs))"
},
{
"identifier": "Node",
"path": "src/node.py",
"snippet": "class Node(object):\n def __init__(self,id_nod... | import random
import numpy as np
from math import log2, log10
from queue import Queue
from pymobility.models.mobility import random_waypoint
from src.node import Node
from src.packet import Packet
from src.parameter import *
from src.transtask import Trans_task | 1,479 |
class Environment():
#初始化环境
def __init__(self):
#初始数据-最大节点数
self.node_max=NODE_MAX
self.node_space_size=NODE_MAX
self.node_moving_area=MOV_AREA
#初始化二维平面
|
class Environment():
#初始化环境
def __init__(self):
#初始数据-最大节点数
self.node_max=NODE_MAX
self.node_space_size=NODE_MAX
self.node_moving_area=MOV_AREA
#初始化二维平面 | self.geo_area = random_waypoint(self.node_max, dimensions=(MOV_AREA, MOV_AREA), velocity=(10, 15), wt_max=1.0) | 0 | 2023-12-30 09:35:30+00:00 | 2k |
karthicksivakumarp/gui_read_csv | main.py | [
{
"identifier": "read_csv_file",
"path": "read_from_csv/read_csv_file.py",
"snippet": "class read_csv_data:\r\n def __init__(self):\r\n def read_mult_csv_file(self):\r"
},
{
"identifier": "analyze_data",
"path": "data_analysis/analyze_data.py",
"snippet": "class analyze_csv_data:\n... | from read_from_csv import read_csv_file
from data_analysis import analyze_data
from report_generation import generate_report
from tkinter import Tk
from user_interface import gui
| 800 | # Import necessary modules
# Initialize CSV reader instance
read_csv = read_csv_file.read_csv_data()
# Obtain the function/method for reading multiple CSV files
# Note: "read_mult_csv_file" is a function or method defined in the "read_csv_file" module
main_read_csv = read_csv.read_mult_csv_file
# Initialize... | # Import necessary modules
# Initialize CSV reader instance
read_csv = read_csv_file.read_csv_data()
# Obtain the function/method for reading multiple CSV files
# Note: "read_mult_csv_file" is a function or method defined in the "read_csv_file" module
main_read_csv = read_csv.read_mult_csv_file
# Initialize... | gui.UI(root, main_read_csv, analyze_data, report_gen)
| 3 | 2023-12-25 18:49:42+00:00 | 2k |
Slenderman00/Ask-Surf | AskSurf/cli.py | [
{
"identifier": "load_settings",
"path": "AskSurf/settings.py",
"snippet": "def load_settings():\n # check if settings.toml exists\n if not settings_exist():\n create_settings()\n edit_settings()\n return load_settings()\n\n with open(own_dir / \"settings.toml\", \"r\") as ... | import os
import requests
import argparse
import tqdm
import time
import subprocess
import sys
from pathlib import Path
from halo import Halo
from .settings import load_settings, settings_exist, edit_settings | 795 |
settings = {}
own_dir = Path(__file__).parent.absolute()
question_pipe = own_dir / "question_pipe"
response_pipe = own_dir / "response_pipe"
def conditional_decorator(dec, condition):
def decorator(func):
if not condition:
# Return the function unchanged, not decorated.
return fun... |
settings = {}
own_dir = Path(__file__).parent.absolute()
question_pipe = own_dir / "question_pipe"
response_pipe = own_dir / "response_pipe"
def conditional_decorator(dec, condition):
def decorator(func):
if not condition:
# Return the function unchanged, not decorated.
return fun... | edit_settings() | 2 | 2023-12-22 19:43:45+00:00 | 2k |
davidsvy/fractal_video | src/prepare_data/diving48.py | [
{
"identifier": "dataset_stats",
"path": "src/utils/data.py",
"snippet": "def dataset_stats(root, ext):\n n_train = len(find_files(dir=os.path.join(root, 'train'), ext=ext))\n n_val = len(find_files(dir=os.path.join(root, 'val'), ext=ext))\n n_test = len(find_files(dir=os.path.join(root, 'test'... | import json
import os
import shutil
from ..utils.data import dataset_stats
from ..utils.other import run_bash | 685 |
def move_files(path_split, dir_src, dir_tgt, ext):
with open(path_split, 'r') as file:
lut = json.load(file)
for item in lut:
filename = f'{item["vid_name"]}.{ext}'
path_src = os.path.join(dir_src, filename)
label = str(item['label'])
dir_label = o... |
def move_files(path_split, dir_src, dir_tgt, ext):
with open(path_split, 'r') as file:
lut = json.load(file)
for item in lut:
filename = f'{item["vid_name"]}.{ext}'
path_src = os.path.join(dir_src, filename)
label = str(item['label'])
dir_label = o... | dataset_stats(root=root, ext=ext) | 0 | 2023-12-27 19:43:45+00:00 | 2k |
OpenBrickProtocolFoundation/client | main.py | [
{
"identifier": "Event",
"path": "tetrion.py",
"snippet": "class Event(NamedTuple):\n key: Key\n type: EventType\n frame: int"
},
{
"identifier": "EventType",
"path": "tetrion.py",
"snippet": "class EventType(Enum):\n PRESSED = 0\n RELEASED = 1"
},
{
"identifier": ... | import pygame
from tetrion import Event
from tetrion import EventType
from tetrion import Key
from tetrion import Tetrion | 754 |
def main() -> None:
frame = 0
with Tetrion() as tetrion:
pygame.init()
RECT_SIZE = 30
size = (RECT_SIZE * tetrion.width, (RECT_SIZE + 2) * tetrion.height)
screen = pygame.display.set_mode(size)
COLORS = [(0, 0, 0),
(0, 240, 240),
... |
def main() -> None:
frame = 0
with Tetrion() as tetrion:
pygame.init()
RECT_SIZE = 30
size = (RECT_SIZE * tetrion.width, (RECT_SIZE + 2) * tetrion.height)
screen = pygame.display.set_mode(size)
COLORS = [(0, 0, 0),
(0, 240, 240),
... | tetrion.enqueue_event(Event(key=Key.LEFT, type=EventType.PRESSED, frame=frame)) | 2 | 2023-12-30 15:25:05+00:00 | 2k |
Birch-san/natten-fwd-ad | script/demo.py | [
{
"identifier": "NattenBlock",
"path": "src/natten_block.py",
"snippet": "class NattenBlock(Module):\n def __init__(self, d_model: int, d_head: int, kernel_size: int):\n super().__init__()\n self.d_head = d_head\n self.n_heads = d_model // d_head\n self.kernel_size = kernel_size\n self.q... | import torch
import torch.autograd.forward_ad as fwAD
from torch import inference_mode, enable_grad
from torch.backends.cuda import sdp_kernel
from src.natten_block import NattenBlock
from src.hood_attn_block import NeighbourhoodAttnBlock | 775 |
device=torch.device('cuda')
dtype=torch.bfloat16
seed=42
d_model=128
d_head=64
kernel_size=13
torch.manual_seed(seed)
|
device=torch.device('cuda')
dtype=torch.bfloat16
seed=42
d_model=128
d_head=64
kernel_size=13
torch.manual_seed(seed) | natten_block = NattenBlock(d_model, d_head=d_head, kernel_size=kernel_size).to(device=device, dtype=dtype) | 0 | 2023-12-22 22:57:36+00:00 | 2k |
ysyBrenda/Transformer-For-Geochemical-Anomaly-Detection | anomaly_detection.py | [
{
"identifier": "Transformer",
"path": "transformer/Models.py",
"snippet": "class Transformer(nn.Module):\n ''' A sequence to sequence model with attention mechanism. '''\n\n def __init__(\n self, src_pad_idx, trg_pad_idx,\n d_word_vec=38, d_model=38, d_inner=2048,\n ... | import torch
import argparse
import dill as pickle
import numpy as np
import calculate_anomalyscore
import torch.utils.data as Data
import time
from tqdm import tqdm
from transformer.Models import Transformer
from transformer.Translator import Translator | 1,019 | '''
geochemical anomaly detection
1,reconstruct geochemical data with trained model.
2,then, identify geochemical anomaly
Author: ysyBrenda
'''
def load_model(opt, device):
checkpoint = torch.load(opt.model, map_location=device)
model_opt = checkpoint['settings']
| '''
geochemical anomaly detection
1,reconstruct geochemical data with trained model.
2,then, identify geochemical anomaly
Author: ysyBrenda
'''
def load_model(opt, device):
checkpoint = torch.load(opt.model, map_location=device)
model_opt = checkpoint['settings']
| model = Transformer( | 0 | 2023-12-22 13:22:58+00:00 | 2k |
camenduru/MotionCtrl-hf | lvdm/modules/attention.py | [
{
"identifier": "conv_nd",
"path": "lvdm/basics.py",
"snippet": "def conv_nd(dims, *args, **kwargs):\n \"\"\"\n Create a 1D, 2D, or 3D convolution module.\n \"\"\"\n if dims == 1:\n return nn.Conv1d(*args, **kwargs)\n elif dims == 2:\n return nn.Conv2d(*args, **kwargs)\n ... | import math
import torch
import torch.nn.functional as F
import xformers
import xformers.ops
from functools import partial
from inspect import isfunction
from einops import rearrange, repeat
from torch import einsum, nn
from lvdm.basics import conv_nd, normalization, zero_module
from lvdm.common import checkpoi... | 1,032 |
try:
XFORMERS_IS_AVAILBLE = True
except:
XFORMERS_IS_AVAILBLE = False
class RelativePosition(nn.Module):
""" https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
def __init__(self, num_units, max_relative_position):
super().__init__()
... |
try:
XFORMERS_IS_AVAILBLE = True
except:
XFORMERS_IS_AVAILBLE = False
class RelativePosition(nn.Module):
""" https://github.com/evelinehong/Transformer_Relative_Position_PyTorch/blob/master/relative_position.py """
def __init__(self, num_units, max_relative_position):
super().__init__()
... | context_dim = default(context_dim, query_dim) | 4 | 2023-12-27 19:32:03+00:00 | 2k |
vita-epfl/social-transmotion | evaluate_jrdb.py | [
{
"identifier": "batch_process_coords",
"path": "dataset_jrdb.py",
"snippet": "def batch_process_coords(coords, masks, padding_mask, config, modality_selection='traj+2dbox', training=False, multiperson=True):\n joints = coords.to(config[\"DEVICE\"])\n masks = masks.to(config[\"DEVICE\"])\n in_F... | import argparse
import torch
import random
import numpy as np
from progress.bar import Bar
from torch.utils.data import DataLoader
from dataset_jrdb import batch_process_coords, create_dataset, collate_batch
from model_jrdb import create_model
from utils.utils import create_logger | 1,456 |
def inference(model, config, input_joints, padding_mask, out_len=14):
model.eval()
with torch.no_grad():
pred_joints = model(input_joints, padding_mask)
output_joints = pred_joints[:,-out_len:]
return output_joints
def evaluate_ade_fde(model, modality_selection, dataloader, bs, config... |
def inference(model, config, input_joints, padding_mask, out_len=14):
model.eval()
with torch.no_grad():
pred_joints = model(input_joints, padding_mask)
output_joints = pred_joints[:,-out_len:]
return output_joints
def evaluate_ade_fde(model, modality_selection, dataloader, bs, config... | in_joints, in_masks, out_joints, out_masks, padding_mask = batch_process_coords(joints, masks, padding_mask, config, modality_selection) | 0 | 2023-12-25 15:12:40+00:00 | 2k |
facebookresearch/ca_body | ca_body/nn/shadow.py | [
{
"identifier": "tile2d",
"path": "ca_body/nn/blocks.py",
"snippet": "def tile2d(x, size: int):\n \"\"\"Tile a given set of features into a convolutional map.\n\n Args:\n x: float tensor of shape [N, F]\n size: int or a tuple\n\n Returns:\n a feature map [N, F, size[0], siz... | import logging
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import ca_body.nn.layers as la
from typing import Optional, Dict
from ca_body.nn.blocks import tile2d, weights_initializer | 1,068 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# TODO: use shared utils here?
logger = logging.getLogger(__name__)
class ShadowUNet(nn.Module):
def __init__(... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# TODO: use shared utils here?
logger = logging.getLogger(__name__)
class ShadowUNet(nn.Module):
def __init__(... | self.apply(weights_initializer(self.lrelu_slope)) | 1 | 2023-12-27 15:31:35+00:00 | 2k |
0x00wolf/hkrsAI | src/logger.py | [
{
"identifier": "PathFinder",
"path": "src/pathfinder.py",
"snippet": "class PathFinder:\n \"\"\"Class that returns an object with necessary paths for runtime operations\"\"\"\n def __init__(self, cwd: str):\n self.cwd = cwd\n self.config = f'{self.cwd}/config.json'\n self.log... | import os
import re
import json
from typing import Type
from src.pathfinder import PathFinder
from src.conversation import Conversation | 1,302 |
class Logger:
def __init__(self, paths: PathFinder, log_level: int, log_format: str):
"""Logs conversations and saves data at the user's request"""
self.level: int = log_level
self.format: str = log_format
self.paths: Paths = paths
self.number: int = 0
self.file: st... |
class Logger:
def __init__(self, paths: PathFinder, log_level: int, log_format: str):
"""Logs conversations and saves data at the user's request"""
self.level: int = log_level
self.format: str = log_format
self.paths: Paths = paths
self.number: int = 0
self.file: st... | def log(self, conversation: Conversation): | 1 | 2023-12-22 07:04:47+00:00 | 2k |
ccurme/chesster | chesster/app/board_manager.py | [
{
"identifier": "display_board",
"path": "chesster/app/utils.py",
"snippet": "def display_board(board, player_side: chess.Color) -> None:\n \"\"\"Display board.\"\"\"\n board_size = 360\n if player_side == chess.WHITE:\n flipped = False\n else:\n flipped = True\n if board.mo... | import os
import urllib
import chess
from typing import Iterator
from fastapi import WebSocket, WebSocketDisconnect
from langserve import RemoteRunnable
from chesster.app.utils import (
display_board,
get_engine_score,
serialize_board_state_with_last_move,
) | 974 |
LANGSERVE_HOST = os.getenv("LANGSERVE_HOST", "localhost")
LANGSERVE_SECRET = os.getenv("LANGSERVE_SECRET", "secret")
CHAT_HISTORY_LENGTH = 50 # Number of most recent (human, ai) exchanges to retain.
class BoardManager:
def __init__(self):
self.active_websockets: list[WebSocket] = []
self.last... |
LANGSERVE_HOST = os.getenv("LANGSERVE_HOST", "localhost")
LANGSERVE_SECRET = os.getenv("LANGSERVE_SECRET", "secret")
CHAT_HISTORY_LENGTH = 50 # Number of most recent (human, ai) exchanges to retain.
class BoardManager:
def __init__(self):
self.active_websockets: list[WebSocket] = []
self.last... | "board": serialize_board_state_with_last_move( | 2 | 2023-12-24 19:19:31+00:00 | 2k |
zkarpinski/codeinsight-sdk-python | tests/test_client.py | [
{
"identifier": "CodeInsightClient",
"path": "codeinsight_sdk/client.py",
"snippet": "class CodeInsightClient:\n def __init__(self,\n base_url: str,\n api_token: str,\n timeout: int = 60,\n verify_ssl: bool = True\n ):\n ... | import pytest
import logging
import requests_mock
from codeinsight_sdk import CodeInsightClient
from codeinsight_sdk.exceptions import CodeInsightError | 1,265 |
logger = logging.getLogger(__name__)
## CHANGE ME ##
TEST_URL = "https://api.revenera.com"
TEST_API_TOKEN = "your_api_token"
class TestCodeInsightClient:
@pytest.fixture
def client(self):
return CodeInsightClient(TEST_URL, TEST_API_TOKEN)
def test_client(self, client):
assert clie... |
logger = logging.getLogger(__name__)
## CHANGE ME ##
TEST_URL = "https://api.revenera.com"
TEST_API_TOKEN = "your_api_token"
class TestCodeInsightClient:
@pytest.fixture
def client(self):
return CodeInsightClient(TEST_URL, TEST_API_TOKEN)
def test_client(self, client):
assert clie... | with pytest.raises(CodeInsightError): | 1 | 2023-12-29 00:49:12+00:00 | 2k |
chebupelka8/Engine | scripts/loop.py | [
{
"identifier": "Vec2",
"path": "scripts/math.py",
"snippet": "class Vec2:\r\n def __init__(self, x: int | float, y: int | float) -> None:\r\n self.__verify(x, y)\r\n\r\n self.__x = x\r\n self.__y = y\r\n \r\n @staticmethod\r\n def __verify(x, y) -> None:\r\n matc... | import pygame, sys
from pygame.locals import *
from .math import Vec2
from .image import Image
| 951 |
class WindowLoop:
def __init__(self, __size: Vec2, fps: int = 144) -> None:
pygame.init()
self.__display = pygame.display.set_mode((__size.x, __size.y))
pygame.display.set_caption("Engine: v0.1")
|
class WindowLoop:
def __init__(self, __size: Vec2, fps: int = 144) -> None:
pygame.init()
self.__display = pygame.display.set_mode((__size.x, __size.y))
pygame.display.set_caption("Engine: v0.1")
| pygame.display.set_icon(Image("Engine/assets/icon.png").image)
| 1 | 2023-12-25 07:53:49+00:00 | 2k |
lxbme/TSPLifesaver | TSPLifesaver/tools.py | [
{
"identifier": "AbstractPoint",
"path": "TSPLifesaver/abc/abc.py",
"snippet": "class AbstractPoint(ABC, MutableSequence):\n def __delitem__(self, key): ...\n\n def insert(self, index, value): ...\n\n @abstractmethod\n def __init__(self,pos):\n \"\"\"\n Init the Point\n ... | from typing import Iterable, MutableSequence, Type
from random import shuffle
from copy import deepcopy
from TSPLifesaver.abc import AbstractRoute, AbstractPoint
from TSPLifesaver.structure import BasicRoute, PointWithEuclideanDistance
from TSPLifesaver.optimizer import SimulatedAnnealing | 1,502 |
def route_from_sequence(sequence: Iterable[MutableSequence], route: AbstractRoute = BasicRoute([]),
point_class: Type[AbstractPoint] = PointWithEuclideanDistance,
name_offset: int = 1, ) -> AbstractRoute:
"""
:param route: Instances of the AbstractRoute class o... |
def route_from_sequence(sequence: Iterable[MutableSequence], route: AbstractRoute = BasicRoute([]),
point_class: Type[AbstractPoint] = PointWithEuclideanDistance,
name_offset: int = 1, ) -> AbstractRoute:
"""
:param route: Instances of the AbstractRoute class o... | opt = SimulatedAnnealing(route, temperature=temperature, | 4 | 2023-12-26 10:08:09+00:00 | 2k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.