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 |
|---|---|---|---|---|---|---|
"""Logging configuration for myquery."""
import logging
import sys
from typing import Optional
from rich.logging import RichHandler
from rich.console import Console
def setup_logging(level: str = "INFO", debug_mode: bool = False) -> None:
"""
Setup logging configuration with Rich handler.
Args:
... | lemarocain1962/myquery | config/logging.py | .py | 22fd5ad546fc2244 | 7 | 0 |
"""Settings management for myquery using Pydantic."""
from typing import Optional, Literal
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
# OpenAI Configuration
opena... | lemarocain1962/myquery | config/settings.py | .py | 5f68367f4dd447a6 | 7 | 0 |
"""Main agent orchestration for myquery."""
from typing import Optional, List, Dict, Any
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.memory import ConversationBufferMemo... | lemarocain1962/myquery | core/agent.py | .py | 1fa2b49fc2a39397 | 7 | 0 |
"""Data analysis utilities for myquery."""
from typing import List, Dict, Any, Optional
from langchain_openai import ChatOpenAI
from config.logging import get_logger
import json
logger = get_logger(__name__)
class DataAnalyzer:
"""Utility class for analyzing query results."""
def __init__(self, llm: Cha... | lemarocain1962/myquery | core/data_analyzer.py | .py | 449c3e0441cada9e | 7 | 0 |
"""Multi-database connection manager for myquery."""
from typing import Dict, Optional, List, Any
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from config.logging import get_logger
import json
logger = get_logger(__name__)
class MultiDBManager:
"""Manager for multiple database connec... | lemarocain1962/myquery | core/multi_db_manager.py | .py | cd2cc66df19166e4 | 7 | 0 |
"""Query generation utilities for myquery."""
from typing import Optional, Dict, Any
from langchain_openai import ChatOpenAI
from config.logging import get_logger
logger = get_logger(__name__)
class QueryGenerator:
"""Utility class for generating SQL queries."""
def __init__(self, llm: ChatOpenAI):
... | lemarocain1962/myquery | core/query_generator.py | .py | e3190e3543e125f1 | 7 | 0 |
"""Demo script with SQLite database."""
import sqlite3
import os
from core.agent import QueryAgent
def create_demo_database():
"""Create a demo SQLite database with sample data."""
db_path = "demo.db"
# Remove existing database
if os.path.exists(db_path):
os.remove(db_path)
# Cre... | lemarocain1962/myquery | examples/demo_sqlite.py | .py | 1f550232828c742c | 7 | 0 |
"""Complete demo of all myquery features."""
import os
import sqlite3
from core.agent import QueryAgent
def create_demo_databases():
"""Create multiple demo databases."""
# Create sales database
conn = sqlite3.connect("demo_sales.db")
cursor = conn.cursor()
cursor.execute("""
CREATE T... | lemarocain1962/myquery | examples/full_features_demo.py | .py | 8370215e7c67a10c | 7 | 0 |
"""
Smart Visualization & Analysis Demo for myquery
This demo showcases the new auto-visualization feature that automatically
creates charts when users request visualizations in their queries.
Features demonstrated:
- Auto-detection of visualization requests
- Multiple chart types (bar, line, pie, scatter)
- AI-power... | lemarocain1962/myquery | examples/smart_visualization_demo.py | .py | 65481fa4aea1f734 | 7 | 0 |
"""MCP Client for testing and integration."""
from typing import Dict, Any, Optional
import requests
from mcp.protocol import MCPRequest, MCPResponse, MCPActionType
class MCPClient:
"""Client for interacting with MCP server."""
def __init__(self, base_url: str = "http://localhost:7766"):
"""
... | lemarocain1962/myquery | mcp/client.py | .py | 1bded887eab59de1 | 7 | 0 |
"""MCP Protocol implementation for myquery."""
from typing import Dict, Any, Optional, List
from pydantic import BaseModel, Field
from enum import Enum
class MCPActionType(str, Enum):
"""MCP action types."""
CONNECT_DB = "connect_db"
GET_SCHEMA = "get_schema"
GENERATE_QUERY = "generate_query"
EXEC... | lemarocain1962/myquery | mcp/protocol.py | .py | 7a3fbe3ef550334b | 7 | 0 |
"""MCP Server implementation for myquery."""
from typing import Dict, Any, Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
import uuid
import json
from core.agent import QueryAgent
from mcp.protocol import (
MCPRequ... | lemarocain1962/myquery | mcp/server.py | .py | 84b5b93d61ec9fe3 | 7 | 0 |
#!/usr/bin/env python3
"""Build script for creating standalone executables using PyInstaller."""
import os
import sys
import shutil
import argparse
import platform
from pathlib import Path
# Get project root
PROJECT_ROOT = Path(__file__).parent.parent
DIST_DIR = PROJECT_ROOT / "dist"
BUILD_DIR = PROJECT_ROOT / "build... | lemarocain1962/myquery | scripts/build_binary.py | .py | ba55798b53631ff9 | 7 | 0 |
"""Tests for QueryAgent."""
import pytest
from unittest.mock import Mock, patch
from core.agent import QueryAgent
class TestQueryAgent:
"""Tests for QueryAgent."""
@patch('core.agent.ChatOpenAI')
def test_agent_initialization(self, mock_llm):
"""Test agent initialization."""
agent = Q... | lemarocain1962/myquery | tests/test_agent.py | .py | f7b50ea899e8bb5d | 7.5 | 0 |
"""Tests for myquery tools."""
import pytest
from unittest.mock import Mock, patch
from tools import (
ConnectDBTool,
GetSchemaTool,
GenerateQueryTool,
ExecuteQueryTool,
)
class TestConnectDBTool:
"""Tests for ConnectDBTool."""
def test_sqlite_connection(self):
"""Test SQLite conn... | lemarocain1962/myquery | tests/test_tools.py | .py | 0cfc458ca3c48d0f | 7.5 | 0 |
"""Data analysis tool for myquery."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAI
from config.logging import get_logger
import json
logger = get_logger(__name__)
class AnalyzeDataInput(BaseModel):
"""Input sc... | lemarocain1962/myquery | tools/analyze_data_tool.py | .py | c76082d06ffed044 | 7 | 0 |
"""Schema analysis tool for myquery."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAI
from config.logging import get_logger
import json
logger = get_logger(__name__)
class AnalyzeSchemaInput(BaseModel):
"""Inpu... | lemarocain1962/myquery | tools/analyze_schema_tool.py | .py | 34d5e1bb4f6904e4 | 7 | 0 |
"""Database connection tool for myquery."""
from typing import Optional, Type, Dict, Any
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from sqlalchemy import create_engine, text
from sqlalchemy.engine import Engine
from config.logging import get_logger
logger = get_logger(__name__)
class... | lemarocain1962/myquery | tools/connect_db_tool.py | .py | 0995e80d4bee7860 | 7 | 0 |
"""SQL query execution tool for myquery."""
from typing import Optional, Type, List, Dict, Any
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from sqlalchemy import text
from sqlalchemy.engine import Engine
from config.logging import get_logger
import json
logger = get_logger(__name__)
cl... | lemarocain1962/myquery | tools/execute_query_tool.py | .py | 5413e1d8eef3e726 | 7 | 0 |
"""Table formatting tool for myquery."""
from typing import Optional, Type, List, Dict, Any
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from rich.console import Console
from rich.table import Table
from rich import box
from config.logging import get_logger
import json
logger = get_logger... | lemarocain1962/myquery | tools/format_table_tool.py | .py | 035fe491447d193a | 7 | 0 |
"""SQL query generation tool for myquery."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAI
from config.logging import get_logger
import json
import re
logger = get_logger(__name__)
class GenerateQueryInput(BaseMode... | lemarocain1962/myquery | tools/generate_query_tool.py | .py | 038580b9fe1cbdf9 | 7 | 0 |
"""Multi-database query tool for myquery."""
from typing import Optional, Type, List, Dict, Any
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from core.multi_db_manager import MultiDBManager
from config.logging import get_logger
import json
import pandas as pd
logger = get_logger(__name__)... | lemarocain1962/myquery | tools/multi_db_query_tool.py | .py | 7b5a790c9ed7349e | 7 | 0 |
"""Query optimization suggestion tool for myquery."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAI
from config.logging import get_logger
import json
import re
logger = get_logger(__name__)
class QueryOptimizationI... | lemarocain1962/myquery | tools/query_optimization_tool.py | .py | 389e74b28433e585 | 7 | 0 |
"""Data visualization tool for myquery."""
from typing import Optional, Type, List, Dict, Any
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
from config.logging import get_logger
import json
import plotly.graph_objects as go
import plotly.express as px
from pathlib import Path
import tempfil... | lemarocain1962/myquery | tools/visualize_data_tool.py | .py | 9d31711358054492 | 7 | 0 |
"""
Django settings for hauki project.
"""
import logging
import os
import subprocess
import environ
import helusers.defaults
import sentry_sdk
from corsheaders.defaults import default_headers
from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES
from django.core.exceptions import ImproperlyConfigured... | City-of-Helsinki/hauki | hauki/settings.py | .py | 617202aae25e21b2 | 7.3 | 3 |
import datetime
import re
from dateutil.parser import parse
from dateutil.relativedelta import MO, SU, relativedelta
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.models import Q
from django.forms import Field
from django.utils import timezone
from django_filters import Fil... | City-of-Helsinki/hauki | hours/filters.py | .py | 6c1cee891950b3d3 | 7.3 | 3 |
import logging
import os
import re
from collections.abc import Sized
from itertools import zip_longest
from typing import TypeVar
import bleach
import requests
from django import db
from django.db.models import Model
from model_utils.models import SoftDeletableModel
from modeltranslation.translator import translator
... | City-of-Helsinki/hauki | hours/importer/base.py | .py | df297e697bde3009 | 7.3 | 3 |
from django import db
from ..models import DataSource, DatePeriod, Resource, ResourceOrigin
from .base import Importer, register_importer
from .sync import ModelSyncher
@register_importer
class HaukiImporter(Importer):
"""
This barebones importer imports and syncs all opening hours data from an instance
... | City-of-Helsinki/hauki | hours/importer/hauki.py | .py | 6473d39c73007bb2 | 7.3 | 3 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights R... | acejarvis/Shoppresso | backend/chardet/chardistribution.py | .py | df0a164bad8aac6a | 7 | 0 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All R... | acejarvis/Shoppresso | backend/chardet/charsetprober.py | .py | 2929b0244ae3ca9c | 7 | 0 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | acejarvis/Shoppresso | backend/chardet/codingstatemachine.py | .py | 558a7fe9ccb2922e | 7 | 0 |
"""
All of the Enums that are used throughout the chardet package.
:author: Dan Blanchard (dan.blanchard@gmail.com)
"""
class InputState(object):
"""
This enum represents the different states a universal detector can be in.
"""
PURE_ASCII = 0
ESC_ASCII = 1
HIGH_BYTE = 2
class LanguageFilter... | acejarvis/Shoppresso | backend/chardet/enums.py | .py | 0229b075bf5ab357 | 7 | 0 |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | acejarvis/Shoppresso | backend/chardet/escprober.py | .py | 924caa560d58c370 | 7 | 0 |
# Copyright © 2020 Pavel Tisnovsky
#
# 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 wri... | RedHatInsights/insights-results-aggregator-utils | checks/json_check.py | .py | 1bdca0427f5d960b | 7.15 | 1 |
"""Create an issue on github.com using the given parameters."""
# Link to generated documentation for this script:
# <https://redhatinsights.github.io/insights-results-aggregator-utils/packages/issue.html>
import json
from argparse import ArgumentParser
from datetime import datetime
import requests
def current_tim... | RedHatInsights/insights-results-aggregator-utils | ci/issue.py | .py | 0471a0c8a2100f48 | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Red Hat, 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 l... | RedHatInsights/insights-results-aggregator-utils | input/gen_broken_jsons.py | .py | 32d40c6e3fe557f2 | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Red Hat, 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 l... | RedHatInsights/insights-results-aggregator-utils | input/gen_broken_messages.py | .py | fa9433c38c587c97 | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2022 Red Hat, 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 l... | RedHatInsights/insights-results-aggregator-utils | input/gen_messages.py | .py | 9e45d985c0c9079b | 7.15 | 1 |
# Copyright © 2019, 2020 Pavel Tisnovsky
#
# 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 ... | RedHatInsights/insights-results-aggregator-utils | input/random_payload_generator.py | .py | 4eb1b09cae8432a8 | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Red Hat
#
# 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 ... | RedHatInsights/insights-results-aggregator-utils | kubernetes/gen_cert_key.py | .py | 031b788e5ec02a4b | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Red Hat, 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 l... | RedHatInsights/insights-results-aggregator-utils | logs/anonymize_aggregator_log.py | .py | bb93f002451949a3 | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Red Hat, 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 l... | RedHatInsights/insights-results-aggregator-utils | logs/anonymize_ccx_pipeline_log.py | .py | 042aebf6eb37e52c | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Pavel Tisnovsky
#
# 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... | RedHatInsights/insights-results-aggregator-utils | monitoring/go_metrics.py | .py | 866373c351c2db8a | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2020 Pavel Tisnovsky
#
# 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... | RedHatInsights/insights-results-aggregator-utils | s3/upload_timestamps.py | .py | f655457468f5a92c | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright © 2021 Pavel Tisnovsky
#
# 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... | RedHatInsights/insights-results-aggregator-utils | stage_tester/pta.py | .py | 89073785b5c55ecb | 7.65 | 1 |
import asyncio
import os
import re
import aiohttp
import csv
import random
import ssl
import time
from datetime import date, timedelta, datetime, timezone
from pathlib import Path
from pyquery import PyQuery
from dateutil.relativedelta import relativedelta
# --- 設定與常數 ---
headers = {
"User-Agent": "Mozilla/5.0 (Wi... | z-Wind/stockTools | get_extraData_fund.py | .py | e2373b7bbc1f93e2 | 7.15 | 1 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | OpenVoiceOS/ovos-skill-ddg | ovos_skill_ddg/__init__.py | .py | 77d9e79f3f9741fb | 7.3 | 3 |
"""Golden-utterance end-to-end coverage for ovos-skill-ddg (en-US).
The master ovoscope corpus carries no rows for
``ovos-skill-ddg.openvoiceos`` (verified: zero matches in
knowledge/datasets/ovoscope/test_dataset.jsonl), so
``golden_utterances.jsonl`` is derived entirely from this skill's own
``search_duck.intent`` t... | OpenVoiceOS/ovos-skill-ddg | test/end2end/test_golden_utterances.py | .py | 9ee08a4d9684c29e | 7.8 | 3 |
"""FastAPI endpoint dependencies."""
from typing import Annotated
from fastapi import Depends, Path
from starlette.requests import Request
from ..api.models.models import User
from ..conf.conf import DEPLOYMENT_CSC, DEPLOYMENT_NBIS
from ..conf.deployment import deployment_config
from .exceptions import SystemExcepti... | CSCfi/metadata-submitter | metadata_backend/api/dependencies.py | .py | 2fd65f7df5d4e872 | 7.35 | 4 |
"""FastAPI endpoint error handing."""
import traceback
from http import HTTPStatus
from typing import Any
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from pydantic import ValidationError
from starlette import status
from starlette.datastructures import URL
from sta... | CSCfi/metadata-submitter | metadata_backend/api/errors.py | .py | 7515791bf72d381c | 7.35 | 4 |
"""OIDC authentication API handler."""
from fastapi import Query, Request
from fastapi.responses import RedirectResponse
from starlette import status
from ...services.auth_service import AuthServiceHandler
class AuthAPIHandler:
"""OIDC authentication API handler."""
def __init__(self, service_handler: Auth... | CSCfi/metadata-submitter | metadata_backend/api/handlers/auth.py | .py | 241ba5869614fd70 | 7.35 | 4 |
"""Health API handler."""
import asyncio
from ...helpers.logger import LOG
from ...services.service_handler import HealthHandler
from ..models.health import Health, ServiceHealth
from .restapi import RESTAPIHandler
class HealthAPIHandler(RESTAPIHandler):
"""Health API handler."""
@staticmethod
async de... | CSCfi/metadata-submitter | metadata_backend/api/handlers/health.py | .py | 7d7f97ff5c8f6edd | 7.35 | 4 |
"""Key API handler."""
from typing import Annotated
from fastapi import Body, Response, status
from fastapi.responses import PlainTextResponse
from ..dependencies import UserDependency
from ..models.models import ApiKey
from .restapi import RESTAPIHandler
ApiKeyBody = Annotated[ApiKey, Body(description="API key")]
... | CSCfi/metadata-submitter | metadata_backend/api/handlers/key.py | .py | 3aa819754f5996e7 | 7.35 | 4 |
"""REMS API handler."""
from typing import Annotated
from fastapi import Query
from ..models.rems import Organization, OrganizationsMap, RemsLicense, RemsWorkflow
from ..services.rems import RemsOrganisationsService
from .restapi import RESTAPIHandler
RemsLanguageQueryParam = Annotated[str, Query(description="REMS ... | CSCfi/metadata-submitter | metadata_backend/api/handlers/rems.py | .py | 85e87295c5b5c8c1 | 7.35 | 4 |
"""Base class for HTTP API handlers."""
from pydantic import BaseModel, ConfigDict
from ...database.postgres.services.file import FileService
from ...database.postgres.services.object import ObjectService
from ...database.postgres.services.registration import RegistrationService
from ...database.postgres.services.sub... | CSCfi/metadata-submitter | metadata_backend/api/handlers/restapi.py | .py | 7b7a6b7d9cf762f2 | 7.35 | 4 |
"""Submission API handler."""
from datetime import date, datetime, time
from math import ceil
from typing import Annotated, Any
from fastapi import Body, HTTPException, Query, Request, Response, status
from fastapi.responses import JSONResponse
from ...api.dependencies import SubmissionIdOrNamePathParam, SubmissionI... | CSCfi/metadata-submitter | metadata_backend/api/handlers/submission.py | .py | 197a94197b5c0fc0 | 7.35 | 4 |
"""JSON serialisation."""
import json
from datetime import datetime
from typing import Sequence
from pydantic import BaseModel
# Supported by json.JSONEncoder
JSON = dict[str, "JSON"] | Sequence["JSON"] | str | int | float | bool | None
def to_json_dict(model: BaseModel) -> dict[str, JSON]:
"""
Serialize t... | CSCfi/metadata-submitter | metadata_backend/api/json.py | .py | 44a2dfaa87de20db | 7.35 | 4 |
"""Application and request state models."""
from typing import Protocol, cast
from fastapi import Request
from starlette.types import ASGIApp
from ...database.postgres.repository import SessionFactory
from .models import User
class AppState(Protocol):
"""Application state for holding session factory."""
s... | CSCfi/metadata-submitter | metadata_backend/api/models/app.py | .py | f01ced1547fe60ab | 7.35 | 4 |
"""Datacite models."""
from __future__ import annotations
from typing import Iterable, Literal, Optional
from pydantic import Field, model_validator
from pydantic_string_url import AnyUrl
from .base import StrictBaseModel
# https://datacite-metadata-schema.readthedocs.io/en/4.5/properties/
# Same DataCite models ... | CSCfi/metadata-submitter | metadata_backend/api/models/datacite.py | .py | 9652057f217db25a | 7.35 | 4 |
"""Metax models"""
from enum import Enum
from pydantic import (
BaseModel,
ConfigDict,
Field,
field_validator,
model_validator,
)
from pydantic_string_url import AnyUrl
# Metax V3 API: https://metax.fairdata.fi/v3/swagger/
# Metax dataset: https://metax.fairdata.fi/v3/docs/user-guide/datasets-api... | CSCfi/metadata-submitter | metadata_backend/api/models/metax.py | .py | 3b43dfc6c2bb328f | 7.35 | 4 |
"""Other models."""
import enum
from datetime import datetime
from typing import Literal
from pydantic import RootModel
from .base import StrictBaseModel
ChecksumMethodType = Literal["MD5", "SHA256"]
CHECKSUM_METHOD_TYPES = ("MD5", "SHA256")
class ApiKey(StrictBaseModel):
"""An API key."""
key_id: str
... | CSCfi/metadata-submitter | metadata_backend/api/models/models.py | .py | 74bb94d187ee8f45 | 7.35 | 4 |
"""Submission models."""
from __future__ import annotations
import enum
from datetime import datetime
from typing import Optional, Type
from pydantic import ValidationInfo, model_validator
from .base import StrictBaseModel
from .datacite import DataCiteMetadata
class SubmissionWorkflow(enum.Enum):
"""Submissi... | CSCfi/metadata-submitter | metadata_backend/api/models/submission.py | .py | 940237c948fb12aa | 7.35 | 4 |
"""
Read DataCite XML.
"""
from __future__ import annotations
from pathlib import Path
from typing import cast
from lxml.etree import _Element as Element # noqa
from lxml.etree import _ElementTree as ElementTree # noqa
from ...models.datacite import (
Affiliation,
AlternateIdentifier,
Contributor,
... | CSCfi/metadata-submitter | metadata_backend/api/processors/xml/datacite.py | .py | 6e6f070993e11324 | 7.35 | 4 |
"""Xml metadata object processor."""
from typing import Sequence
from lxml.etree import _LogEntry # noqa
class SchemaValidationException(Exception):
"""Exception containing XML Schema validation errors."""
def __init__(self, schema_type: str, errors: Sequence[_LogEntry]) -> None:
"""
Excep... | CSCfi/metadata-submitter | metadata_backend/api/processors/xml/exceptions.py | .py | dc3b1b0278ab954d | 7.35 | 4 |
from pathlib import Path
from lxml import etree
from lxml.etree import _Element as Element # noqa
from .models import XmlIdentifierPath, XmlObjectConfig, XmlObjectPaths, XmlReferencePaths, xml_schema_path
FEGA_XML_SCHEMA_DIR = Path(__file__).parent.parent.parent.parent / "schemas" / "xml" / "fega"
# FEGA
#
# The ... | CSCfi/metadata-submitter | metadata_backend/api/processors/xml/fega.py | .py | 62348ac8d8f7c867 | 7.35 | 4 |
"""Resource data for Metax mapping."""
import asyncio
import json
from enum import Enum
from pathlib import Path
from typing import Any, cast
import httpx
from pydantic import BaseModel, TypeAdapter
from rdflib import Graph, Literal, Namespace
from metadata_backend.helpers.logger import LOG
METAX_RESOURCE_ROOT = Pa... | CSCfi/metadata-submitter | metadata_backend/api/resource/metax.py | .py | 7cb3471cb19d0db3 | 7.35 | 4 |
"""Service for issuing JWT tokens and API keys."""
import hashlib
import hmac
import secrets
import string
from datetime import datetime, timedelta, timezone
from typing import Any
import jwt
from fastapi import HTTPException
from starlette import status
from starlette.datastructures import Headers
from ...conf.jwt ... | CSCfi/metadata-submitter | metadata_backend/api/services/auth.py | .py | 5d6e4845715b4eb9 | 7.35 | 4 |
"""Bigpicture API services."""
from typing import Literal
from pydantic import BaseModel
from ...helpers.logger import LOG
from ..exceptions import SystemException
from ..handlers.restapi import RESTAPIServices
from ..models.models import File
from ..models.submission import SubmissionWorkflow
from ..processors.xml.... | CSCfi/metadata-submitter | metadata_backend/api/services/bigpicture.py | .py | 11de8b50db12022c | 7.35 | 4 |
"""Datacite Service."""
from abc import ABC, abstractmethod
from typing import Any, cast
from pydantic_string_url import AnyUrl
from ..exceptions import UserException
from ..json import to_json_dict
from ..models.datacite import AlternateIdentifier, DataCiteMetadata, Description, Subject, Title
from ..models.models ... | CSCfi/metadata-submitter | metadata_backend/api/services/datacite.py | .py | 1c2becee7cd5f647 | 7.35 | 4 |
"""Ingest service."""
import asyncio
from collections.abc import Awaitable, Callable
from contextlib import suppress
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from ...api.exceptions import ServiceHandlerSystemException
from ...conf.admin import admin_config
from ...database.postgres.reposit... | CSCfi/metadata-submitter | metadata_backend/api/services/ingest.py | .py | 92fe4e442cb5edc2 | 7.35 | 4 |
"""
LSTM Cell & Gradient Flow Simulation from Scratch
Author: Narendra Vadapalli
Series: Neural Architecture Evolution Series (Part 2)
This script demonstrates why Long Short-Term Memory (LSTM) networks were invented:
1. Standard RNN: Hidden state (h_t) suffers from vanishing gradients over long sequences (t=50).
2. L... | narenandu/narenvadapalli_dot_com | contents/blog/0072-why-lstms-were-needed-rnn-amnesia-memory-conveyor-belts-gated-doors/scripts/lstm_cell_sim.py | .py | 9e43d57b4bb3ff30 | 7.15 | 1 |
"""
Scaled Dot-Product & Multi-Head Self-Attention Simulation from Scratch
Author: Narendra Vadapalli
Series: Neural Architecture Evolution Series (Part 3)
This script demonstrates the core mathematical mechanics of the Transformer:
1. Scaled Dot-Product Attention: Attention(Q, K, V) = softmax(Q * K^T / sqrt(d_k)) * V... | narenandu/narenvadapalli_dot_com | contents/blog/0073-transformer-revolution-self-attention-parallelization/scripts/transformer_attention_sim.py | .py | 1d4ca6f07873c514 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Attention Memory Bottleneck Simulation: MHA vs MQA vs GQA vs DeepSeek MLA
Demonstrates:
1. Exact KV Cache memory consumption footprint across sequence lengths (4K to 128K).
2. Pure Python standard library implementation of MHA, MQA, GQA, and DeepSeek MLA projections.
3. Numerical comparison ... | narenandu/narenvadapalli_dot_com | contents/blog/0077-attention-memory-bottleneck-mha-gqa-deepseek-mla/scripts/attention_kv_compression_sim.py | .py | a368b00d7056ca35 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Generative Adversarial Networks (GANs) Minimax Simulation: The Counterfeiter vs. Detective
Demonstrates:
1. Pure Python standard library implementation of a 1D Minimax GAN.
2. Real Data Distribution (Gaussian mu=4.0, std=0.5) vs. Generator Output.
3. Discriminator Loss, Generator Loss, and c... | narenandu/narenvadapalli_dot_com | contents/blog/0078-generative-adversarial-networks-gans-counterfeiter-detective-minimax/scripts/gan_minimax_sim.py | .py | fd6a4df6a8bc8ae4 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Evolutionary Arc of Computer Vision Simulation: 2D Conv vs Depthwise Conv (ConvNeXt) vs 3D Video Conv
Demonstrates:
1. Pure Python standard library implementation of 2D spatial convolution and 3D spatiotemporal video convolution.
2. Parameter count and FLOPs comparison across vision architec... | narenandu/narenvadapalli_dot_com | contents/blog/0079-evolutionary-arc-computer-vision-lenet-resnet-convnext-3d-video/scripts/vision_evolution_sim.py | .py | 46dfae8af97585b4 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Qwen 3.8 Sparse MoE Routing & API Cost Economics Simulator
Demonstrates:
1. Pure Python standard library implementation of Top-K MoE Expert Gating Router (Top-8 out of 512 Experts).
2. Active vs. Total Parameter scaling calculation (32B Active out of 512B Total).
3. API Token Cost Comparison... | narenandu/narenvadapalli_dot_com | contents/blog/0080-analyzing-alibabas-qwen-3-8-flagship-moe-model/scripts/qwen38_moe_routing_sim.py | .py | 77782f8aed1ae941 | 7.15 | 1 |
# scripts/world_model_simulation.py
import dataclasses
from typing import List, Tuple
@dataclasses.dataclass
class Vector3D:
x: float
y: float
z: float
@dataclasses.dataclass
class WorldState:
"""Represents ground-truth 3D physical environment state."""
timestamp: float
object_positions: dict[... | narenandu/narenvadapalli_dot_com | scripts/world_model_simulation.py | .py | 36e84541f33d198e | 7.15 | 1 |
"""Environment object class."""
import json
import logging
import os
from pathlib import Path
from typing import Self
from ._system_info import SystemInfo
LOGGER = logging.getLogger(__name__)
class Environment:
"""Object to simplify getting information about the runtime environment."""
root_dir: Path
... | finleyfamily/f-lib | f_lib/_environment.py | .py | d51c21f2bfa13f02 | 7.15 | 1 |
"""Operating system information."""
from __future__ import annotations
import os
import platform
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, cast, final
from platformdirs.unix import Unix
from platformdirs.windows import Windows
if TYPE_CHECKING:
im... | finleyfamily/f-lib | f_lib/_os_info.py | .py | 10cf415ebc663d55 | 7.15 | 1 |
"""System information."""
from __future__ import annotations
import platform
import sys
from functools import cached_property
from typing import ClassVar, Literal, cast, final
from ._os_info import OsInfo
class UnknownPlatformArchitectureError(Exception):
"""Raised when the platform architecture can't be deter... | finleyfamily/f-lib | f_lib/_system_info.py | .py | 8b5c571bc8369334 | 7.15 | 1 |
"""Abstract base class for archive extractors."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import ClassVar, Literal
from .exceptions import ArchiveTypeError
class ArchiveExtractor(ABC):
"""Abstract base class for archive extractors."""
SUF... | finleyfamily/f-lib | f_lib/archive_extractor/_archive_extractor.py | .py | dd83752579954d67 | 7.15 | 1 |
"""Extractor for ``.tar`` archives."""
from __future__ import annotations
import tarfile
from typing import TYPE_CHECKING, ClassVar
from ._archive_extractor import ArchiveExtractor
from .exceptions import Pep706Error
if TYPE_CHECKING:
from pathlib import Path
class TarExtractor(ArchiveExtractor):
"""Extra... | finleyfamily/f-lib | f_lib/archive_extractor/_tar_extractor.py | .py | 296a5f95075c74ec | 7.15 | 1 |
"""Extractor for ``.zip`` archives."""
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from zipfile import ZipFile
from ._archive_extractor import ArchiveExtractor
if TYPE_CHECKING:
from pathlib import Path
class ZipExtractor(ArchiveExtractor):
"""Extractor for ``.zip`` archi... | finleyfamily/f-lib | f_lib/archive_extractor/_zip_extractor.py | .py | fe9532e3ac425753 | 7.15 | 1 |
"""Archive extractor exceptions."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from collections.abc import Sequence
from pathlib import Path
class ArchiveTypeError(Exception):
"""Raised when the supplied archive is not of a supported type."""
archive... | finleyfamily/f-lib | f_lib/archive_extractor/exceptions.py | .py | 2882ee97295238ee | 7.15 | 1 |
"""Custom console :class:`~rich.logging.RichHandler`."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from rich.logging import RichHandler
from rich.markup import escape
from rich.text import Text
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
from dat... | finleyfamily/f-lib | f_lib/logging/_console_handler.py | .py | 85cce67ed1544e7f | 7.15 | 1 |
"""Custom :class:`~rich.highlighter.Highlighter`."""
from __future__ import annotations
from functools import cached_property
from typing import TYPE_CHECKING, ClassVar, TypedDict
from rich.highlighter import Highlighter, ReprHighlighter
if TYPE_CHECKING:
from rich.text import Text
class HighlightTypedDict(Ty... | finleyfamily/f-lib | f_lib/logging/_extendable_highlighter.py | .py | fee46ff9715633ae | 7.15 | 1 |
"""Adapted from https://github.com/pycontribs/enrich/blob/v1.2.7/src/enrich/logging.py."""
from __future__ import annotations
from typing import TYPE_CHECKING
from rich.text import Text, TextType
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
from datetime import datetime
from rich.co... | finleyfamily/f-lib | f_lib/logging/_fluid_log_render.py | .py | 7e3c55b71283ccc1 | 7.15 | 1 |
"""Custom logger."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast
from pydantic import BaseModel, ConfigDict
from ._log_level import LogLevel
if TYPE_CHECKING:
from collections.abc import Mapping
from types import TracebackType
_SysExcInfoT... | finleyfamily/f-lib | f_lib/logging/_logger.py | .py | 6e04ea79776a70bf | 7.15 | 1 |
"""Logging configuration model."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic_settings import BaseSettings, PyprojectTomlConfigSettingsSource
from pydantic_settings import SettingsConfigDict as BaseSettingsConfigDict
from ._console_logging_settings import ConsoleLoggingSetting... | finleyfamily/f-lib | f_lib/logging/settings/_logging_settings.py | .py | cfb9e29ce8df1474 | 7.15 | 1 |
"""Logging utilities."""
from __future__ import annotations
import logging
import sys
from typing import TYPE_CHECKING, TextIO, TypeVar
from rich.logging import RichHandler
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
LoggerTypeVar = TypeVar("LoggerTypeVar", bound=logging.Logger)... | finleyfamily/f-lib | f_lib/logging/utils.py | .py | 4cb0a3b841939b1b | 7.15 | 1 |
"""CLI interface mixin."""
from __future__ import annotations
import logging
import shutil
import subprocess
from typing import IO, TYPE_CHECKING, ClassVar, Literal, cast, overload
from ..constants import ANSI_ESCAPE_PATTERN
from ..utils import convert_kwargs_to_shell_list, convert_list_to_shell_str
if TYPE_CHECKIN... | finleyfamily/f-lib | f_lib/mixins/_cli_interface.py | .py | cfe43d201abd8a83 | 7.15 | 1 |
"""Delete cached property mixin."""
from __future__ import annotations
from contextlib import suppress
class DelCachedPropMixin:
"""Mixin to handle safely clearing the value of :func:`functools.cached_property`."""
def _del_cached_property(self, *names: str) -> None:
"""Delete the cached value of a... | finleyfamily/f-lib | f_lib/mixins/_del_cached_prop.py | .py | 630c43daecca6126 | 7.15 | 1 |
"""Utilities."""
from __future__ import annotations
import platform
import shlex
import subprocess
from typing import TYPE_CHECKING, Any, cast
from ._file_hash import FileHash
if TYPE_CHECKING:
import pathlib
from collections.abc import Iterable
def convert_kwargs_to_shell_list(
**kwargs: bool | Itera... | finleyfamily/f-lib | f_lib/utils/__init__.py | .py | 1757baa3cb7326ab | 7.15 | 1 |
"""Calculate the hash of files."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar
if TYPE_CHECKING:
import hashlib
from collections.abc import Iterable
from _typeshed import StrPath
class FileHash:
"""Wrapper for hashlib to easily calculate f... | finleyfamily/f-lib | f_lib/utils/_file_hash.py | .py | 4e123d9c498820d0 | 7.15 | 1 |
"""Pytest configuration, fixtures, and plugins."""
from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from collections.abc import Iterator
TEST_DIR = Path(__file__).parent
@pytest.fixture
def cd_tmp_path(tmp_path: Path) -> It... | finleyfamily/f-lib | tests/conftest.py | .py | 19c7e3fed8b38306 | 7.65 | 1 |
"""Test f_lib.archive_extractor._archive_extractor."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from f_lib.archive_extractor._archive_extractor import ArchiveExtractor
from f_lib.archive_extractor.exceptions import ArchiveTypeError
if TYPE_CHECKING:
from pathlib import ... | finleyfamily/f-lib | tests/unit/archive_extractor/test__archive_extractor.py | .py | 7a1695a542e77fd0 | 7.65 | 1 |
"""Test f_lib.archive_extractor.exceptions."""
from __future__ import annotations
import pickle
from typing import TYPE_CHECKING
from f_lib.archive_extractor.exceptions import ArchiveTypeError
if TYPE_CHECKING:
from pathlib import Path
class TestArchiveTypeError:
"""Test ArchiveTypeError."""
def test... | finleyfamily/f-lib | tests/unit/archive_extractor/test__exceptions.py | .py | c9d192493354ae52 | 7.65 | 1 |
"""Test f_lib.archive_extractor._tar_extractor."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, Mock
import pytest
from f_lib.archive_extractor._tar_extractor import TarExtractor
from f_lib.archive_extractor.exceptions import ArchiveTypeError, Pep706Error
... | finleyfamily/f-lib | tests/unit/archive_extractor/test__tar_extractor.py | .py | 0318d80996498c15 | 7.65 | 1 |
"""Test f_lib.archive_extractor._zip_extractor."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, Mock
import pytest
from f_lib.archive_extractor._zip_extractor import ZipExtractor
from f_lib.archive_extractor.exceptions import ArchiveTypeError
if TYPE_CHEC... | finleyfamily/f-lib | tests/unit/archive_extractor/test__zip_extractor.py | .py | 6af92bb1438f3aea | 7.65 | 1 |
"""Test f_lib.logging._console_handler."""
from __future__ import annotations
import io
import logging
import re
from typing import TYPE_CHECKING, Protocol
from unittest.mock import Mock
import pytest
from rich.console import Console
from f_lib.logging._console_handler import ConsoleHandler
from f_lib.logging._flui... | finleyfamily/f-lib | tests/unit/logging/test__console_handler.py | .py | 3e394cee25cf884e | 7.65 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.