text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
import unittest
from unittest.mock import Mock, patch
from decimal import Decimal
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient
from coinbase_advanced_trader.models import Order, OrderSide, OrderType
from coinbase_advanced_trader.services.order_service import OrderService
from coinbase_a... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/tests/test_enhanced_rest_client.py | .py | 4e3d8daf6298ca81 | 7.5 | 0 |
import unittest
from unittest.mock import Mock, patch
from decimal import Decimal
from coinbase_advanced_trader.services.fear_and_greed_strategy import FearAndGreedStrategy
from coinbase_advanced_trader.models import Order, OrderSide, OrderType
from coinbase_advanced_trader.services.order_service import OrderService
f... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/tests/test_fear_and_greed_strategy.py | .py | eb430e932245eb23 | 7.5 | 0 |
import unittest
from unittest.mock import Mock
from coinbase_advanced_trader.services.funds_service import FundsService
class TestFundsService(unittest.TestCase):
def setUp(self):
self.rest_client = Mock()
self.funds_service = FundsService(self.rest_client)
def test_deposit_fiat(self):
... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/tests/test_funds_service.py | .py | 4c0a765275007d1b | 7.5 | 0 |
import unittest
from decimal import Decimal
from coinbase_advanced_trader.models.order import Order, OrderSide, OrderType
class TestOrderModel(unittest.TestCase):
"""Test cases for the Order model."""
def test_order_creation(self):
"""Test the creation of an Order instance."""
order = Order(... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/tests/test_order_model.py | .py | bd036429a83118f9 | 7.5 | 0 |
import unittest
from coinbase_advanced_trader.trading_config import FearAndGreedConfig
class TestTradingConfig(unittest.TestCase):
"""Test cases for the TradingConfig class."""
def setUp(self):
"""Set up the test environment before each test method."""
self.config = FearAndGreedConfig()
... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/tests/test_trading_config.py | .py | 131f47690d716a64 | 7.5 | 0 |
"""Trading configuration module for Coinbase Advanced Trader."""
from typing import List, Dict, Any
from coinbase_advanced_trader.config import config_manager
from coinbase_advanced_trader.logger import logger
BUY_PRICE_MULTIPLIER = config_manager.get('BUY_PRICE_MULTIPLIER')
SELL_PRICE_MULTIPLIER = config_manager.get... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/trading_config.py | .py | 56c5c9788ad8c635 | 7 | 0 |
import uuid
from decimal import Decimal, ROUND_HALF_UP
def calculate_base_size(
fiat_amount: Decimal,
spot_price: Decimal,
base_increment: Decimal
) -> Decimal:
"""
Calculate the base size for an order.
Args:
fiat_amount (Decimal): The amount in fiat currency.
spot_price (Deci... | rrvstt/Recurring-ETH-Buy-Coinbase | coinbase_advanced_trader/utils/helpers.py | .py | 43e83125d7c1a981 | 7 | 0 |
"""
Daily ETH Buy Script
Places a $10 USDC buy order for ETH at 0.998 of market price (maker fee) daily.
"""
import os
import schedule
import time
from datetime import datetime
from dotenv import load_dotenv
from coinbase_advanced_trader.enhanced_rest_client import EnhancedRESTClient
from coinbase_advanced_trader.logg... | rrvstt/Recurring-ETH-Buy-Coinbase | daily_eth_buy.py | .py | f68f5784631a529f | 7 | 0 |
from typing import Any, Dict, List
from loguru import logger
from config import load_config
from langchain_openai import ChatOpenAI
from langchain_google_genai.chat_models import ChatGoogleGenerativeAI
from langchain_anthropic import ChatAnthropic
class HybridAIClient:
"""
OpenAI, Gemini, Claude-3 すべてをLangCha... | tawada/discord-AI-bot | ai_client.py | .py | 2b5ecab4ee9bf64d | 7.15 | 1 |
import os
from collections import deque
import discord
from loguru import logger
from ai_client import load_ai_client
from config import load_config
from message_handler import process_message, send_messages
from message_history import History
intents = discord.Intents.default()
intents.message_content = True
client... | tawada/discord-AI-bot | discord_client.py | .py | 7e593d288d472f80 | 7.15 | 1 |
import re
url_pattern_raw = (
r"https?://" # http:// or https://
r"(?:[a-zA-Z0-9$-_@.&+]|[!*()\']|%[0-9a-fA-F]{2})+"
)
url_pattern = re.compile(url_pattern_raw)
brackets_pattern = re.compile(r"\(.*?\)|(.*?)", flags=re.DOTALL)
def contains_url(text_including_url: str) -> bool:
"""Uses regex to... | tawada/discord-AI-bot | functions.py | .py | b9df325601e16980 | 7.15 | 1 |
import asyncio
import datetime
import os
from typing import Any, Dict, List
import discord
from loguru import logger
import functions
import summarizer
from message_history import GPTMessage, History
from search_handler import is_search_needed, search_and_summarize
async def get_reply_message(
message: discord.... | tawada/discord-AI-bot | message_handler.py | .py | fe64f69b5279fcd1 | 7.15 | 1 |
from typing import Any, Dict, List
import json
from duckduckgo_search import DDGS
from loguru import logger
# 検索に関する定数
MAX_SEARCH_RESULTS = 10
MAX_TEXT_LENGTH = 4096
SEARCH_KEYWORDS = ["教えて", "とは", "何", "どうやって", "方法"]
def search_and_summarize(user_question: str, ai_client: Any, text_model: str) -> str:
"""DuckDu... | tawada/discord-AI-bot | search_handler.py | .py | 1b6a3b169a41b8a1 | 7.15 | 1 |
import requests
from bs4 import BeautifulSoup
from loguru import logger
from typing import Dict, Any, List, Optional
import functions
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
import os
# グローバル変数の代わりに定数として定義
DEFAULT_TEXT_... | tawada/discord-AI-bot | summarizer.py | .py | d98654d1ad481de2 | 7.15 | 1 |
import dataclasses
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import discord_client
from message_history import GPTMessage, History
from search_handler import search_and_summarize
from ai_client import HybridAIClient
from config import load_config
def make_openai_like_response(content="テスト応答",... | tawada/discord-AI-bot | tests/test_discord_client.py | .py | 596524011b864c69 | 7.65 | 1 |
"""
Tests for the configuration module
"""
import pytest
import os
import tempfile
from sliver_tor_bridge.config import BridgeConfig, load_config
class TestBridgeConfig:
"""Tests for BridgeConfig class"""
def test_default_config(self):
"""Test default configuration values"""
config = Bri... | srvishal/sliver-tor-bridge | tests/test_config.py | .py | 39f28bf07e41ab48 | 7.65 | 1 |
"""
Tests for the proxy module
"""
import pytest
from unittest.mock import patch, MagicMock
from sliver_tor_bridge.proxy import SliverProxy, create_proxy
class TestSliverProxy:
"""Tests for SliverProxy class"""
def test_initialization(self):
"""Test proxy initialization"""
proxy = Sliver... | srvishal/sliver-tor-bridge | tests/test_proxy.py | .py | 3f15cb9e8fd5c216 | 7.65 | 1 |
"""Helpers for dealing with raw bytes, displaying them, etc."""
def format_byte_as_hex(b: int) -> str:
"""Format a byte as a 2-character hex string.
Example: 1 -> "[0x01]"
"""
hex_part = f"{b:x}"
return f"[0x{hex_part.upper().zfill(2)}]"
def bytes_to_nice_str(byte_obj: bytes, *, show_end_of_lin... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/bytes.py | .py | cf3fe1b577d7bb56 | 7.3 | 3 |
"""Tools for parsing JSON strings from blobs of text."""
from collections.abc import Iterator
from dataclasses import dataclass
import orjson
@dataclass(kw_only=True)
class ParsedJson:
"""A parsed JSON object."""
data: dict | list
start_idx: int
end_idx: int
original_str: str
def extract_json... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/json_parser.py | .py | 6ade68df6c59be21 | 7.3 | 3 |
"""Utility functions for working with paths in the repository."""
from pathlib import Path
import git
BUNDLED_DATA_FOLDER_PATH = Path(__file__).parent / "bundled_data"
def clone_firmware_repo(repo_parent_path: Path) -> tuple[Path, git.Repo]:
"""Clone the CTS-SAT-1-OBC-Firmware repository."""
repo = git.Rep... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/paths.py | .py | c601e42f2239e088 | 7.3 | 3 |
"""A set of tools to read the list of telecommands from the `telecommand_definitions.c` file."""
import json
import re
import sys
from pathlib import Path
from cts1_ground_support.paths import read_text_file
from cts1_ground_support.telecommand_types import TelecommandDefinition
def remove_c_comments(text: str) -> ... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/telecommand_array_parser.py | .py | 74080958b15f0e75 | 7.3 | 3 |
"""Types related to storing telecommand definitions."""
import dataclasses
from dataclasses import dataclass
@dataclass(kw_only=True)
class TelecommandDefinition:
"""Stores a telecommand definition. from the `telecommand_definitions.c` file."""
name: str
tcmd_func: str
description: str | None = None... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/telecommand_types.py | .py | 73f47687ce25729a | 7.3 | 3 |
"""A singleton class to store the app's state. Also, the instance of that class."""
import time
from dataclasses import dataclass, field
from sortedcontainers import SortedDict
from cts1_ground_support.telecommand_types import TelecommandDefinition
from cts1_ground_support.terminal_app.app_types import UART_PORT_NAM... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/terminal_app/app_store.py | .py | 202a07f73c339ccd | 7.3 | 3 |
"""Type definitions for the app."""
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Literal
import pytz
from cts1_ground_support.bytes import bytes_to_nice_str
from cts1_ground_support.json_parser import auto_format_json_in_blob
UART_PORT_NAME_DISCONNECTED = "di... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/terminal_app/app_types.py | .py | ce5f9cb69d19f37b | 7.3 | 3 |
"""Serial thread for handling receiving UART communication."""
import threading
import time
import serial
from loguru import logger
from cts1_ground_support.terminal_app.app_config import MAX_RX_TX_LOG_ENTRIES, UART_BAUD_RATE
from cts1_ground_support.terminal_app.app_store import app_store
from cts1_ground_support.t... | CalgaryToSpace/CTS-SAT-1-Ground-Support | cts1_ground_support/terminal_app/serial_thread.py | .py | 4f63751faf3faac7 | 7.3 | 3 |
"""Unit tests for the `telecommand_array_parser.py` module."""
import tempfile
from pathlib import Path
import pytest
from cts1_ground_support.paths import clone_firmware_repo
from cts1_ground_support.telecommand_array_parser import (
extract_c_function_docstring,
extract_telecommand_arg_list,
parse_tele... | CalgaryToSpace/CTS-SAT-1-Ground-Support | tests/test_telecommand_array_parser.py | .py | 27136efa4c2b917d | 7.8 | 3 |
from typing import TypedDict, List, Dict, Callable
class Task(TypedDict):
title: str
done: bool
priority: int
tasks: List[Task] = []
def print_menu() -> None:
"""Display the main menu options."""
print("\n--- Daily Task Manager (oT-oT) ---")
print("1 - Add new task")
print("2 - Show all ... | Vykemopi/cli-todo-list | lTCT.py | .py | 42b1c51caf26794b | 7 | 0 |
"""
Evidence collection and validation for sklearn-diagnose.
This module handles:
- Validating that estimators are fitted
- Ensuring read-only behavior
- Collecting predictions from estimators
- Validating dataset integrity
- Preventing accidental data leakage between train/val
"""
import hashlib
import warnings
from... | ironpawa/sklearn-diagnose | sklearn_diagnose/core/evidence.py | .py | 0f278867f9ee3e08 | 7.15 | 1 |
"""
Hypothesis generation rules for sklearn-diagnose (reference implementation).
This module provides rule-based hypothesis generation that can be used as:
- A reference implementation for understanding detection logic
- A fallback when LLM is unavailable
- Validation/comparison against LLM-generated hypotheses
Note:... | ironpawa/sklearn-diagnose | sklearn_diagnose/core/hypotheses.py | .py | fd452004bff2bef3 | 7.15 | 1 |
"""
Type definitions and data structures for sklearn-diagnose.
This module defines the core data structures used throughout the library
for representing evidence, hypotheses, and diagnosis reports.
"""
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, ... | ironpawa/sklearn-diagnose | sklearn_diagnose/core/schemas.py | .py | 89c7aedc88a8dc22 | 7.15 | 1 |
"""
Deterministic signal extraction for sklearn-diagnose.
This module computes quantitative statistics from the evidence.
All computations are deterministic and reproducible.
Signal extractors are organized by category:
- Performance signals (train/val scores, gaps)
- CV signals (mean, std, fold analysis)
- Residual ... | ironpawa/sklearn-diagnose | sklearn_diagnose/core/signals.py | .py | 5dee34bbe61f9fa2 | 7.15 | 1 |
"""
Pytest configuration and fixtures for sklearn-diagnose tests.
This module contains:
- MockLLMClient: A mock LLM client for testing without API calls
- Fixtures for setting up the mock client
"""
from typing import Any, Dict, List
import pytest
from sklearn_diagnose.llm.client import LLMClient, _set_global_clien... | ironpawa/sklearn-diagnose | tests/conftest.py | .py | ece2301d82a1cfaf | 7.65 | 1 |
from enum import StrEnum
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings
class Action(StrEnum):
APPLY = "apply"
DESTROY = "destroy"
class EnvVar:
ACTION = "ACTION"
DRY_RUN = "DRY_RUN"
LOG_LEVEL = "LOG_LEVEL"
INPUT_FILE = "INPUT_FILE"
BACKEND_TF_FIL... | app-sre/external-resources-io | external_resources_io/config.py | .py | 59cb659d8fcbdae1 | 7 | 0 |
import logging
import logging.config
from external_resources_io.config import Config
class DryRunFilter(logging.Filter):
"""Adds a DRY_RUN prefix"""
def __init__(self, *, dry_run: bool) -> None:
super().__init__()
if dry_run:
self.prefix = "DRY_RUN - "
else:
s... | app-sre/external-resources-io | external_resources_io/log.py | .py | 2db2bc133969dcdc | 7 | 0 |
# ruff: file-ignore[any-type]
import json
from collections.abc import Sequence
from pathlib import Path
from types import UnionType
from typing import TYPE_CHECKING, Any, Literal, Union, get_args, get_origin
from pydantic import BaseModel
from pydantic_core import PydanticUndefined
from external_resources_io.config i... | app-sre/external-resources-io | external_resources_io/terraform/generators.py | .py | adda71b4f1575a1e | 7 | 0 |
"""Shared helper for calling the gh CLI. Stdlib only -- no external deps."""
import json
import subprocess
import sys
import re
def _run(args, *, check=True, capture=True):
"""Run a subprocess, return CompletedProcess."""
result = subprocess.run(
args,
capture_output=capture,
text=Tru... | jsco2t/dotfiles | .agents/skills/comp-goreviewomatic/_gh.py | .py | 3e9a1aa22327debc | 7 | 0 |
#!/usr/bin/env python3
"""Discover a PR from a URL, number, or the current branch.
Usage:
pr_discover.py # discover from current branch
pr_discover.py 123 # by number
pr_discover.py '#123' # by number (with hash)
pr_discover.py https://git... | jsco2t/dotfiles | .agents/skills/comp-goreviewomatic/pr_discover.py | .py | d3a0648768ae26ad | 7 | 0 |
#!/usr/bin/env python3
"""Scan open PRs in the current repo and identify candidates for code review.
Usage:
pr_scan.py
Uses the current repo (determined from git remote). Scans all open PRs and
identifies those that meet ALL of the following criteria:
1. NOT in draft state
2. No human reviews (bot reviews... | jsco2t/dotfiles | .agents/skills/comp-goreviewomatic/pr_scan.py | .py | 6caaf9171ab4cbe2 | 7 | 0 |
"""Shared helper for calling the gh CLI. Stdlib only — no external deps."""
import json
import subprocess
import sys
import re
def _run(args, *, check=True, capture=True):
"""Run a subprocess, return CompletedProcess."""
result = subprocess.run(
args,
capture_output=capture,
text=True... | jsco2t/dotfiles | .agents/skills/copilot-fixer/_gh.py | .py | 0588b16c6dad053f | 7 | 0 |
#!/usr/bin/env python3
"""Get CI check status for a GitHub PR, with optional failure log retrieval.
Usage:
pr_checks.py PR_NUMBER
pr_checks.py PR_NUMBER --failing-only
pr_checks.py PR_NUMBER --failing-only --logs
Outputs JSON:
{"checks": [...], "summary": {"total": N, "pass": N, "fail": N, "pending": ... | jsco2t/dotfiles | .agents/skills/copilot-fixer/pr_checks.py | .py | ff2023aed69e9f9b | 7 | 0 |
#!/usr/bin/env python3
"""Scan open PRs in the current repo and identify those that contain only documentation changes.
Usage:
pr_scan.py
Uses the current repo (determined from git remote). Scans all open PRs and
identifies those where every changed file has a documentation extension
(.md, .mdx, .rst, .adoc, .asc... | jsco2t/dotfiles | .agents/skills/doc-reviewomatic/pr_scan.py | .py | 8c9d281c44f7b193 | 7 | 0 |
#!/usr/bin/env python3
# A few notes about this utility:
#
# 1. I am not a python expert: any of the following should not be taken as example code.
# 2. This is clearly over-kill.
# 3. So why did I do it?
# a. It seemed fun
# b. I like TUI's
# c. I needed an excuse to play with python more
#
# ... | jsco2t/dotfiles | .bin/dot-update.py | .py | d64a4fe76df2fd8f | 7 | 0 |
#!/usr/bin/env python3
"""Convert between epoch timestamps and human-readable dates.
Usage:
epoch # print current epoch
epoch 1680000000 # epoch -> human-readable (local + UTC)
epoch 1680000000000 # handles millisecond epochs too
epoch 2024-01-15 # date string -> epoch
... | jsco2t/dotfiles | .bin/shell_utils/epoch.py | .py | 2701569f5294162d | 7 | 0 |
import os
import glob
import time
import json
import psutil
import multiprocessing
from datetime import datetime
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor
# pydre imports (src/project.py)
from pydre.project import Project
# Helper: Resource Monitor
class ResourceMonitor:
def __i... | Ed1P/pydre-parallelism-benchmark | benchmarks/runner.py | .py | 4b9fe1018ec690c7 | 7 | 0 |
#!/usr/bin/env python3
"""
Kindle to Obsidian - Extract Kindle highlights and notes to Obsidian markdown files.
A GUI application for syncing your Kindle highlights to your Obsidian vault.
Usage:
python kindle_to_obsidian.py # Launch GUI
python kindle_to_obsidian.py --cli # Run in CLI mode (for automa... | Solatglas/kindle-to-obsidian | kindle_to_obsidian.py | .py | 4a5af43cb9985ad0 | 7.24 | 2 |
"""
Command-line interface for Kindle to Obsidian.
For automation and non-GUI usage.
"""
import argparse
import sys
from .config.settings import Settings
from .core.writer import sync_highlights
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Ext... | Solatglas/kindle-to-obsidian | src/cli.py | .py | 8d8a7ab236489448 | 7.24 | 2 |
"""
Settings management for Kindle to Obsidian.
Handles loading, saving, and providing defaults for all configuration options.
"""
import os
import platform
from pathlib import Path
from typing import Any, Dict, Optional
import yaml
def get_config_path() -> Path:
"""Get the path to the config file (next to the... | Solatglas/kindle-to-obsidian | src/config/settings.py | .py | 0af7ec25bd05e5ab | 7.24 | 2 |
"""
Clippings file parser for Kindle to Obsidian.
Parses My Clippings.txt and returns structured data.
"""
import hashlib
import re
from collections import defaultdict
from datetime import datetime
from typing import Any, Dict, List, Optional
from dateutil.parser import parse as parse_date
# Clipping boundary marke... | Solatglas/kindle-to-obsidian | src/core/parser.py | .py | 7932b7b61481f946 | 7.24 | 2 |
"""
Markdown file writer for Kindle to Obsidian.
Writes highlights and notes to Obsidian-compatible markdown files.
"""
import os
import re
import unicodedata
from typing import Any, Callable, Dict, List, Optional, Tuple
from .parser import link_notes_to_highlights
def sanitize_filename(filename: str, max_length: ... | Solatglas/kindle-to-obsidian | src/core/writer.py | .py | ad6d9d657caa6717 | 7.24 | 2 |
"""
Main application window for Kindle to Obsidian GUI.
Assembles all UI frames into the main window with scrollable content.
"""
import tkinter as tk
from tkinter import ttk
from ..config.settings import Settings
from .paths_frame import PathsFrame
from .formatting_frame import FormattingFrame
from .sync_frame impo... | Solatglas/kindle-to-obsidian | src/ui/app.py | .py | 64bb97516f8ca852 | 7.24 | 2 |
"""
Formatting options frame for Kindle to Obsidian GUI.
Provides controls for customizing output format.
"""
import tkinter as tk
from tkinter import ttk
from typing import Callable, Optional
from ..config.settings import Settings
class FormattingFrame(ttk.LabelFrame):
"""Frame for formatting and output optio... | Solatglas/kindle-to-obsidian | src/ui/formatting_frame.py | .py | 85b5c5a295755439 | 7.24 | 2 |
"""
Paths selection frame for Kindle to Obsidian GUI.
Provides file/folder selection with preview information.
"""
import os
import tkinter as tk
from tkinter import filedialog, ttk
from typing import Callable, Optional
from ..config.settings import Settings
class PathsFrame(ttk.LabelFrame):
"""Frame for selec... | Solatglas/kindle-to-obsidian | src/ui/paths_frame.py | .py | a47ffde30fdd1dab | 7.24 | 2 |
"""
Sync frame for Kindle to Obsidian GUI.
Provides sync button and log output display.
"""
import os
import threading
import tkinter as tk
from tkinter import ttk, messagebox
from typing import Callable, Optional
from ..config.settings import Settings
from ..core.writer import sync_highlights
class SyncFrame(ttk.... | Solatglas/kindle-to-obsidian | src/ui/sync_frame.py | .py | f2d2533f0bc0e84e | 7.24 | 2 |
"""
Real-time price monitoring using WebSocket connections.
Demonstrates subscribing to live market data and handling price updates.
"""
import asyncio
import json
import os
import signal
from dotenv import load_dotenv
import websockets
from hyperliquid.info import Info
load_dotenv()
WS_URL = os.getenv("HYPERLIQUID_... | ronaldslins2/hyperliquid-trading-bot | learning_examples/01_websockets/realtime_prices.py | .py | bd639184ff7d0d0f | 7.15 | 1 |
"""
Test script for placing different types of limit orders on spot market.
Tests scenarios 1-9: GTC, IOC, ALO limit orders and time-limited orders.
Available scenarios (1-9):
=== LIMIT ORDERS ===
1. GTC Limit Buy 2. IOC Limit Buy 3. ALO Limit Buy
4. GTC Limit Sell 5. IOC Limit Sell 6. ALO Li... | ronaldslins2/hyperliquid-trading-bot | learning_examples/06_copy_trading/order_scenarios/place_orders_limit.py | .py | 96995517a2a45c8c | 7.15 | 1 |
"""
Monitor all order activity from a leader wallet using WebSocket.
Shows real-time order placements, cancellations, and fills.
"""
import asyncio
import json
import os
import signal
from dotenv import load_dotenv
import websockets
load_dotenv()
WS_URL = os.getenv("HYPERLIQUID_TESTNET_PUBLIC_WS_URL")
LEADER_ADDRESS... | ronaldslins2/hyperliquid-trading-bot | learning_examples/06_copy_trading/print_parsed_user_events.py | .py | 8a5864a2237f5284 | 7.15 | 1 |
"""
Simple raw message printer for ALL WebSocket messages.
Shows unprocessed JSON messages from the API including positions, fills, and orders.
"""
import asyncio
import json
import os
import signal
from dotenv import load_dotenv
import websockets
load_dotenv()
WS_URL = os.getenv("HYPERLIQUID_TESTNET_PUBLIC_WS_URL")... | ronaldslins2/hyperliquid-trading-bot | learning_examples/06_copy_trading/print_raw_websocket_messages.py | .py | ba3b6b4b54325534 | 7.15 | 1 |
"""
Hyperliquid Endpoint Router
Smart routing system for Hyperliquid API endpoints with automatic fallback.
Supports multiple providers (public, Chainstack) with method-specific routing.
"""
import os
import asyncio
import time
import logging
from typing import Dict, List, Optional, Tuple, Callable, Any
from dataclas... | ronaldslins2/hyperliquid-trading-bot | src/core/endpoint_router.py | .py | 8c27458ce05ca022 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Enhanced Transparent Configuration System
All assumptions are explicit and user-configurable.
No magic numbers hidden from users.
"""
from dataclasses import dataclass, field
from typing import Dict, Any, Optional, Literal, Union
from enum import Enum
import yaml
from pathlib import Path
... | ronaldslins2/hyperliquid-trading-bot | src/core/enhanced_config.py | .py | a78436f6881b2103 | 7.15 | 1 |
"""
Private Key Manager
Unified, secure private key management with support for:
- Different keys for testnet vs mainnet
- Per-bot instance key configuration
- File-based and environment-based keys
- Fallback strategies
"""
import os
from pathlib import Path
from typing import Optional, Dict, Any
import logging
cla... | ronaldslins2/hyperliquid-trading-bot | src/core/key_manager.py | .py | d165b392ddce9b2e | 7.15 | 1 |
"""
Strategy Interface
Simple interface for implementing trading strategies.
Newbies can add new strategies by implementing this interface.
"""
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Any
from dataclasses import dataclass
from enum import Enum
class SignalType(Enum):
"""Trad... | ronaldslins2/hyperliquid-trading-bot | src/interfaces/strategy.py | .py | a3d378c5994b0102 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Grid Trading Bot Runner
Clean, simple entry point for running grid trading strategies.
No confusing naming - just "run_bot.py".
"""
import asyncio
import argparse
import sys
import os
import signal
from pathlib import Path
import yaml
from typing import Optional
# Load .env file if it exis... | ronaldslins2/hyperliquid-trading-bot | src/run_bot.py | .py | b4b7db496260b7db | 7.15 | 1 |
"""
Basic Grid Trading Strategy
Simple grid strategy that places buy and sell orders at regular intervals.
This is the main business logic for grid trading.
"""
import time
from typing import List, Dict, Optional, Any
from dataclasses import dataclass
from enum import Enum
from interfaces.strategy import (
Tradi... | ronaldslins2/hyperliquid-trading-bot | src/strategies/grid/basic_grid.py | .py | 97ccc298aba69b65 | 7.15 | 1 |
from typing import Any, Callable, Dict, List, Optional
from dataclasses import dataclass
from enum import Enum
class EventType(Enum):
"""Event types for the trading framework"""
ORDER_FILLED = "order_filled"
ORDER_CANCELLED = "order_cancelled"
ORDER_PLACED = "order_placed"
POSITION_OPENED = "posi... | ronaldslins2/hyperliquid-trading-bot | src/utils/events.py | .py | c6cae56ecc0e52c4 | 7.15 | 1 |
# Helper functions for Python-based XMP and Exif extraction
#
# Author: Peter Jakubowski
# Date: 12/8/2024
# Description: Python class that transforms XMP and Exif metadata into a
# standardized Python dataclass data structure from a Pillow (PIL) source image.
#
import logging
from datetime import datetime
import date... | peterjakubowski/Pillow-Metadata | src/pillow_metadata/helpers.py | .py | dda2a533c17fb98b | 7 | 0 |
# Class for Python-based XMP and Exif extraction
#
# Author: Peter Jakubowski
# Date: 12/8/2024
# Description: Python class that transforms XMP and Exif metadata into a
# standardized Python dataclass data structure from a Pillow (PIL) source image.
#
import logging
from dataclasses import dataclass, InitVar, field
fr... | peterjakubowski/Pillow-Metadata | src/pillow_metadata/metadata.py | .py | a91ff653e3055be2 | 7 | 0 |
from typing import List, Optional
import pydantic
import numpy as np
# Global list mapping each dihedral transform id to its inverse.
# Index corresponds to the original tid, and the value is its inverse.
DIHEDRAL_INVERSE = [0, 3, 2, 1, 4, 5, 6, 7]
class PuzzleDatasetMetadata(pydantic.BaseModel):
pad_id: int
... | BoowwiieePH/HRM | dataset/common.py | .py | f2b1f917726e0835 | 7 | 0 |
from typing import Tuple
import torch
from torch import nn
import torch.nn.functional as F
try:
from flash_attn_interface import flash_attn_func # type: ignore[import]
except ImportError:
# Fallback to FlashAttention 2
from flash_attn import flash_attn_func # type: ignore[import]
from models.common imp... | BoowwiieePH/HRM | models/layers.py | .py | 43a990635a8e9b04 | 7 | 0 |
"""Tests for NestedLearningOptimizer."""
import pytest
import numpy as np
import tensorflow as tf
from nested_learning_optimizer import NestedLearningOptimizer
class TestNestedLearningOptimizer:
"""Test cases for the optimizer."""
def test_basic_instantiation(self):
"""Test optimizer can be inst... | ChrisPinedaSanhueza/nested-learning-optimizer | tests/test_optimizer.py | .py | 51fd1d89d62e5ffc | 7.65 | 1 |
"""
mirror_tantra_protocol.py
Engine for routing interaction modes using the Mirror Tantra JSON.
Intended usage:
- Load mirror_tantra.json as the canonical ritual schema.
- Use MirrorTantraEngine to:
- Look up protocol metadata (mantras, seals, reflection questions).
- Decide which “mode” a given interaction ... | shreyanshbh/-mirror-tantra | mirror_tantra.py | .py | 9aa16c5236cee066 | 7 | 0 |
import json
from typing import List, Tuple
from .models import ContractProfile, RiskFinding
def print_text_report(results: List[Tuple[ContractProfile, List[RiskFinding], dict]]) -> None:
"""Print a human-readable CLI report."""
for profile, findings, score in results:
print(f"Contract: {prof... | Jessej123-hash/Solidity-Economic-Risk-Scanner | se_risk_scanner/reporting.py | .py | 5dce1b7a6eb16ad0 | 7.15 | 1 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class DINOLoss(nn.Module):
def __init__(self, out_dim, ncrops, warmup_teacher_temp, teacher_temp, warmup_teacher_temp_epochs, nepochs, student_temp=0.1, center_momentum=0.9):
super().__init__()
self.student_temp =... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino/dino_loss.py | .py | 26719f642f697757 | 7.15 | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino/eval_linear.py | .py | 747e8a8861d65fc6 | 7.15 | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino/eval_video_segmentation.py | .py | f17eb52954b89e3b | 7.15 | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino/run_with_submitit.py | .py | fb14a2c6e90702f7 | 7.15 | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino/vision_transformer.py | .py | b1f998d5f49ab436 | 7.15 | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino/visualize_attention.py | .py | f908e5c1857ef36d | 7.15 | 1 |
# transforms_dino.py
from torchvision import transforms
from PIL import Image
import numpy as np
class DinoTransform:
"""
Generate multi-crop augmentations for DINO.
Two global crops and several local crops.
Usage:
transform = DinoTransform()
crops = transform(pil_img)
"""
def ... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | dino_pretrain/transforms_dino.py | .py | 848e86e557db15e9 | 7.15 | 1 |
import os
import numpy as np
import torch
from torch.utils.data import Dataset
from PIL import Image
from pathlib import Path
class SimpleImageDataset(Dataset):
"""
Dataset for loading images from a folder (PNG, JPG, TIF).
"""
def __init__(self, root_dir, transform=None):
self.root_dir = Path(r... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | pannuke_inference_dist/dataset.py | .py | bd7f410c45c57249 | 7.15 | 1 |
import os
import sys
import argparse
import torch
import numpy as np
import cv2
from torch.utils.data import DataLoader
from tqdm import tqdm
import albumentations as A
from albumentations.pytorch import ToTensorV2
# Import local modules
from model import TransUNet
from dataset import SimpleImageDataset, PanNukeDatase... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | pannuke_inference_dist/inference.py | .py | 412aba5470075edb | 7.15 | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as T
from timm.models.vision_transformer import vit_small_patch8_224 as ViT
from timm.models.vision_transformer import PatchEmbed
class TransUNet(nn.Module):
"""
TransUNet with variable input size support.
- Vi... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | pannuke_inference_dist/model.py | .py | 662d499ad06dc5f0 | 7.15 | 1 |
# File: preprocess/patch_exporter.py
import os
import sys
# 確保能找到 src 資料夾
CURRENT_DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(os.path.join(CURRENT_DIR, '..', 'src')))
sys.path.insert(0, os.path.abspath(os.path.join(CURRENT_DIR, '..', 'src', 'dataset')))
import numpy as np
from dataset.pannuke_d... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | preprocess/patch_exporter.py | .py | e1d6e00907d6e4aa | 7.15 | 1 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as T
from timm.models.vision_transformer import vit_small_patch8_224 as ViT
from timm.models.vision_transformer import PatchEmbed
class TransUNet(nn.Module):
"""
TransUNet 可變輸入尺寸版本
- ViT-Small/8 backbone (embed... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | segmentor/transunet.py | .py | 815c3876d90b44a6 | 7.15 | 1 |
"""
視覺化預測結果:將預測遮罩以透明顏色疊加在原始影像上
使用方式:python visualize_predictions.py --split train --num_samples 10
"""
import os
import sys
import argparse
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
import random
# 專案路徑設定
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os... | ianochieng25/PanNuke-cell-core-region-identification-with-DINO | visualize_predictions.py | .py | 9db7967d364cf2a7 | 7.15 | 1 |
# pylint: disable=W0621
"""Asynchronous Python client providing Open Data information of Arnhem."""
from __future__ import annotations
import asyncio
from arnhem import ODPArnhem
async def main() -> None:
"""Show example on using the ODP Arnhem API client."""
async with ODPArnhem() as client:
locat... | klaasnicolaas/python-arnhem | examples/parking.py | .py | 131759516fe73c2d | 7.15 | 1 |
"""Asynchronous Python client providing Open Data information of Arnhem."""
from __future__ import annotations
import asyncio
import socket
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Self
from aiohttp import ClientError, ClientSession
from aiohttp.hdrs import METH_GET
fr... | klaasnicolaas/python-arnhem | src/arnhem/arnhem.py | .py | 184ab6a7a9d07cb0 | 7.15 | 1 |
"""Models for Open Data Platform of Arnhem."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
@dataclass
class ParkingSpot:
"""Object representing a parking spot."""
spot_id: int
parking_type: str
street: str
traffic_sign: str
neighborhood: str
... | klaasnicolaas/python-arnhem | src/arnhem/models.py | .py | 9bc7a8c8db5f4313 | 7.15 | 1 |
# author: hebetian
import requests
import logging
base_url = 'https://weibo.com'
base_path = '/ajax/side/hotSearch'
base_headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, *... | hebe-tian/weibo | get_hot_band.py | .py | 3164b48a6e1ec395 | 7 | 0 |
#!/usr/bin/env python3
"""
cwe.py — fetch the MITRE CWE catalog and write it as a TSV.
Source: https://cwe.mitre.org/data/csv/2000.csv.zip
Output: data/cwe.tsv (tab-separated, all MITRE columns preserved)
We preserve every column from the upstream CSV — mitigations, related
weaknesses, observed examples, applicable p... | x-cmd/cve | .x-cmd/cwe.py | .py | 5eee0ae562c92c4f | 7.15 | 1 |
#!/usr/bin/env python3
"""
report.py — build cve.report.tsv (year-by-year stats) and a markdown
table for the README.
Reads every data/cve-YYYY.tsv and computes:
year, count, scored_count, avg_score, max_score
Writes (under report/, sibling of data/):
cve.report.tsv — machine-readable, one row per year (a... | x-cmd/cve | .x-cmd/report.py | .py | 5d623e77f8aa09c0 | 7.15 | 1 |
#!/usr/bin/env python3
"""
tsv.py — Build and incrementally maintain per-year TSV indexes of cvelistV5.
Output layout (under --out, defaulting to this directory):
cve-YYYY.tsv one TSV per year, sorted by cve id
index.tsv manifest: year\trows\tfile (the simplest index)
cve.tsv.state.json per-f... | x-cmd/cve | .x-cmd/tsv.py | .py | aa40343faca8c7fd | 7.15 | 1 |
from django.db import models
from django.utils import timezone
from markdownx.models import MarkdownxField
from markdownx.utils import markdownify
# Create your models here.
class Changelog(models.Model):
"""Deprecated in-app changelog; GitHub releases are the canonical release record."""
title = models.CharFi... | surp-hovhannes/bahk | app_management/models.py | .py | 03019ecf298192fe | 7.3 | 3 |
"""Tests for app management models."""
from datetime import date
from django.test import TestCase
from app_management.models import Changelog
class ChangelogModelTests(TestCase):
"""Tests for app changelog entries."""
def test_preserves_explicit_release_date(self):
"""Historical or planned release... | surp-hovhannes/bahk | app_management/tests.py | .py | 373f45a0e6c4ac16 | 7.8 | 3 |
"""Reusable, storage-safe media rendering for Django admin pages."""
from collections.abc import Iterable
from typing import Any
from django.utils.html import format_html
_MEDIA_EXCEPTIONS = (AttributeError, OSError, ValueError)
_THUMBNAIL_SIZES = {
"small": (56, 56),
"content": (84, 56),
"portrait": (4... | surp-hovhannes/bahk | bahk/admin_media.py | .py | a27c28dfa2c27d29 | 7.3 | 3 |
"""Fast & Pray's branded, permission-aware Django admin site."""
from collections.abc import Iterable
from django.contrib.admin import AdminSite
from django.template.response import TemplateResponse
from django.urls import reverse
class FastAndPrayAdminSite(AdminSite):
"""Provide a branded shell and task-orient... | surp-hovhannes/bahk | bahk/admin_site.py | .py | df51a7ecb3a8c175 | 7.3 | 3 |
""" URL configuration for bahk project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='web_hom... | surp-hovhannes/bahk | bahk/urls.py | .py | e47bd26c135e9907 | 7.3 | 3 |
#!/usr/bin/env python
"""Standalone script to clean up test media files."""
import os
from pathlib import Path
def _is_allowed_test_media_dir(media_dir):
"""Return true only for the real project-local test_media directory."""
candidate = Path(media_dir)
if not candidate.is_absolute():
candidate = ... | surp-hovhannes/bahk | cleanup_test_media.py | .py | fc8cc73f086a01cb | 7.8 | 3 |
"""
Analytics query optimization module.
Provides high-performance analytics data aggregation to replace N+1 query patterns.
"""
from django.db.models import Count, Case, When
from django.utils import timezone
from datetime import timedelta
from .models import Event, EventType
class AnalyticsQueryOptimizer:
"""
... | surp-hovhannes/bahk | events/analytics_optimizer.py | .py | 41bfd1b4b0ca0dfa | 7.3 | 3 |
"""
Management command to award retroactive milestones to existing users.
"""
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.db import models
from django.utils import timezone
from events.models import UserMilestone
from hub.models import Fast
from notifi... | surp-hovhannes/bahk | events/management/commands/award_retroactive_milestones.py | .py | 1016a73b7690ac7e | 7.3 | 3 |
"""
Management command to clean up old activity feed items based on retention policies.
"""
from django.core.management.base import BaseCommand
from events.models import UserActivityFeed
from django.utils import timezone
from datetime import timedelta
from django.db.models import Count
class Command(BaseCommand):
... | surp-hovhannes/bahk | events/management/commands/cleanup_activity_feeds.py | .py | 3d32d585f6f87b29 | 7.3 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.