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 |
|---|---|---|---|---|---|---|
"""Convert arXiv/ar5iv HTML (LaTeXML output) to clean markdown via pandoc.
The raw page is chrome-heavy (banners, nav buttons, base64 icons), so conversion
extracts the ``<article>`` element, cleans it, and converts with raw HTML
disabled so LaTeXML's styling markup is dropped instead of passed through.
"""
import re... | will-rice/tts-papers | scripts/_convert/html_to_md.py | .py | 83f0dcee58264878 | 7.24 | 2 |
"""Generate the papers/README.md corpus index.
Per-year pages are intentionally not generated: the front README carries a
rolling 30-day window, and full-year browsing is served by GitHub's own file
listing for each ``papers/<year>/`` directory, which the top index links to.
"""
from __future__ import annotations
fr... | will-rice/tts-papers | scripts/_convert/indexes.py | .py | 34ac4552fafe2fca | 7.24 | 2 |
"""Convert extracted LaTeX source to markdown via pandoc."""
from __future__ import annotations
import logging
import subprocess
from dataclasses import dataclass
from pathlib import Path
PANDOC_TIMEOUT_SECONDS = 300
@dataclass
class LatexConversionResult:
"""Outcome of a single pandoc invocation."""
body... | will-rice/tts-papers | scripts/_convert/latex_to_md.py | .py | 11e1a1894d0d1dca | 7.24 | 2 |
"""Write per-paper markdown files with YAML frontmatter."""
from __future__ import annotations
import unicodedata
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
import yaml
@dataclass
class PaperRecord:
"""Everything needed to render a per-paper markdo... | will-rice/tts-papers | scripts/_convert/output.py | .py | 68cfea04f0029ee4 | 7.24 | 2 |
"""Convert a PDF to markdown via marker-pdf.
Conversion is run in an isolated subprocess (``_pdf_worker``) so that native
crashes in pdfium/torch — e.g. a glibc ``malloc_consolidate`` SIGABRT — do
not propagate to the parent process and kill the entire conversion run.
"""
from __future__ import annotations
import js... | will-rice/tts-papers | scripts/_convert/pdf_to_md.py | .py | 45411d39d2cca895 | 7.24 | 2 |
"""LLM-driven remediation pass for low-quality conversions."""
from __future__ import annotations
import base64
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol
# Heuristic thresholds
MIN_WORDS_PER_PAGE_RATIO = 0.5
MIN_WORDS_PER_PAGE = 200
LOW_CITATION_RESO... | will-rice/tts-papers | scripts/_convert/remediation.py | .py | 50f95407b52a13f5 | 7.24 | 2 |
"""Fetch and cache paper source from arXiv (LaTeX preferred) or Semantic Scholar (PDF)."""
from __future__ import annotations
import enum
import json
import logging
import tarfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime... | will-rice/tts-papers | scripts/_convert/sources.py | .py | aa0ece150aab1a61 | 7.24 | 2 |
"""Convert all papers in papers.csv to markdown.
Usage:
uv run python scripts/convert_papers.py
uv run python scripts/convert_papers.py --regenerate-all
uv run python scripts/convert_papers.py --only 2008.10010
uv run python scripts/convert_papers.py --skip-llm
"""
from __future__ import annotations
... | will-rice/tts-papers | scripts/convert_papers.py | .py | 3c70b69a85188776 | 7.24 | 2 |
"""Shared pytest fixtures."""
from __future__ import annotations
from pathlib import Path
import pytest
FIXTURES = Path(__file__).parent / "fixtures"
@pytest.fixture
def fixtures_dir() -> Path:
return FIXTURES
@pytest.fixture
def tmp_papers_dir(tmp_path: Path) -> Path:
"""Empty papers/ directory rooted ... | will-rice/tts-papers | tests/conftest.py | .py | 1af28bb8ff3894e1 | 7.24 | 2 |
"""Tests for scripts/_convert/formatting.py."""
from __future__ import annotations
from pathlib import Path
import pytest
from scripts._convert.formatting import _PRETTIER, format_markdown
pytestmark = pytest.mark.skipif(
not _PRETTIER.exists(), reason="prettier not installed (run `npm ci`)"
)
def test_forma... | will-rice/tts-papers | tests/test_formatting.py | .py | efd897ae2d0f744e | 7.74 | 2 |
"""Tests for scripts/_convert/indexes.py."""
from __future__ import annotations
from scripts._convert.indexes import IndexEntry, render_top_index
def _entry(arxiv_id: str, year: str) -> IndexEntry:
return IndexEntry(arxiv_id=arxiv_id, submitted=f"{year}-06-15")
def test_top_index_groups_by_year() -> None:
... | will-rice/tts-papers | tests/test_indexes.py | .py | aa851320b14c5eac | 7.74 | 2 |
#!/usr/bin/env python3
"""
Create a formatted comment for Redmine about translated blog posts.
This script reads the translated_posts.json file and creates a formatted comment
that can be used with redmine-activity-reporter.
"""
import json
import sys
import argparse
import os
def create_redmine_comment(posts_dict:... | groupdocs/groupdocs-blog-workflows | tools/blog-post-translator/create_redmine_comment.py | .py | 320b5465e34809e3 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Create a simplified time entry comment with just URLs from translated posts.
This script reads the translated_posts.json file and creates a simplified comment
containing only the blog post URLs for time logging.
"""
import json
import sys
import argparse
def extract_urls_from_posts(posts_... | groupdocs/groupdocs-blog-workflows | tools/blog-post-translator/create_simplified_time_comment.py | .py | 872130525a95a6d6 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Create a GitHub issue for translated blog posts.
This script reads the translated_posts.json file and creates a GitHub issue
in the blog repository listing all translated posts and their languages.
"""
import json
import os
import sys
import argparse
import urllib.request
import urllib.erro... | groupdocs/groupdocs-blog-workflows | tools/blog-post-translator/create_translation_issue.py | .py | 1923d42ea9a78cd9 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Log historical translation work from GitHub issues to Redmine.
This script reads all GitHub issues from the blog repository where the title
contains "Automated Translation", extracts the translation information from
the issue body, and logs the work to Redmine using the issue creation date.
... | groupdocs/groupdocs-blog-workflows | tools/blog-post-translator/log_historical_translations.py | .py | f3adf1af1d618290 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Create a formatted comment for Redmine about missing translations scan.
This script reads the translations_scan_report.json file and creates a formatted comment
that can be used with redmine-activity-reporter.
"""
import json
import sys
import argparse
import os
def create_redmine_comment... | groupdocs/groupdocs-blog-workflows | tools/missing-translations-scanner/create_redmine_comment.py | .py | a7330dced2560cdf | 7.24 | 2 |
#!/usr/bin/env python3
"""
Create a simplified time entry comment from translation scan report.
This script reads the translations_scan_report.json file and creates a simplified comment
containing just a summary for time logging.
"""
import json
import sys
import argparse
def create_simplified_time_comment(report: ... | groupdocs/groupdocs-blog-workflows | tools/missing-translations-scanner/create_simplified_time_comment.py | .py | 76ed053ac54c9519 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Generate a markdown report from the JSON translation scan report.
This script reads the JSON report generated by scan_missing_translations.py
and creates a concise markdown summary suitable for inclusion in README.md.
"""
import json
import argparse
import sys
from pathlib import Path
from ... | groupdocs/groupdocs-blog-workflows | tools/missing-translations-scanner/generate_markdown_report.py | .py | 829cdbfc25a00996 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Update README.md with translation status report.
This script reads a markdown status report and updates the README.md file,
replacing the content under the "## Translation status" section.
"""
import argparse
import sys
import re
from pathlib import Path
def read_file(file_path: str) -> s... | groupdocs/groupdocs-blog-workflows | tools/missing-translations-scanner/update_readme.py | .py | 13c435d816e8cbe6 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Create a formatted comment for Redmine about release post draft creation.
This script reads the generated draft index.md file and creates a formatted comment
that can be used with redmine-activity-reporter.
"""
import sys
import argparse
import os
import re
try:
import yaml
except Impo... | groupdocs/groupdocs-blog-workflows | tools/public-release-post-draft/create_redmine_comment.py | .py | 1dc45c210b783c95 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Create a simplified time entry comment for release post draft.
This script reads the generated draft index.md file and creates a simplified comment
containing just the post URL for time logging.
"""
import sys
import argparse
try:
import yaml
except ImportError:
# Try pyyaml as alt... | groupdocs/groupdocs-blog-workflows | tools/public-release-post-draft/create_simplified_time_comment.py | .py | d63c6a855006b9d0 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Redmine Activity Reporter
Logs time and adds comments to Redmine issues using the REST API.
Compatible with Redmine 3.4.6
"""
import os
import sys
import json
import argparse
from datetime import datetime
from typing import Optional
import requests
class RedmineActivityReporter:
"""Cla... | groupdocs/groupdocs-blog-workflows | tools/redmine-activity-reporter/redmine_activity_reporter.py | .py | c5dd8c1b64dde3bc | 7.24 | 2 |
#!/usr/bin/env python3
"""
Update default values in create-release-post-draft.yml workflow file.
This script updates the version and title default values based on the current date.
"""
import re
import sys
from datetime import datetime
from pathlib import Path
def get_current_version_and_title():
"""Calculate c... | groupdocs/groupdocs-blog-workflows | tools/update-workflow-defaults/update_defaults.py | .py | 95bbcfc92c86e586 | 7.24 | 2 |
"""
Some overwritten biopython functions
"""
from Bio.GenBank.Scanner import EmblScanner
from Bio.SeqRecord import SeqRecord
from Bio.SeqFeature import SeqFeature
# Included here to make sure EmblScanner._feed_seq_length is overwritten
from Bio import SeqIO
import re
# We override this method to allow no space betwee... | pombase/genome_changelog | custom_biopython.py | .py | f36c1928780781d3 | 7.24 | 2 |
"""
Get a list of revisions where the genome sequence changed
"""
import os
from genome_functions import genome_sequences_are_different
import glob
import argparse
import pandas
class Formatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
pass
parser = argparse.ArgumentParser(desc... | pombase/genome_changelog | get_revisions_where_genome_sequence_changes.py | .py | 641dc43d480f19ee | 7.24 | 2 |
"""
Create a new file where only unique remove coordinates are shown. Comments and db_xref are combined comma separated.
PMID:xxxxxxxx values are removed
"""
import pandas
data = pandas.concat([
pandas.read_csv(f, delimiter='\t', na_filter=False, dtype=str) for f in ['results/all_coordinate_changes_file_comments_... | pombase/genome_changelog | make_all_previous_coords_file.py | .py | 665fad291281520f | 7.24 | 2 |
"""
Calculate the differences between genome versions, relies on the folder structure defined in the readme.
"""
import os
from genome_functions import genome_dict_diff, build_seqfeature_dict,read_pombe_genome, genome_sequences_are_different, make_synonym_dict
from formatting_functions import write_diff_to_files
import... | pombase/genome_changelog | pombe_svn_diff.py | .py | 49c577b086b7b42c | 7.24 | 2 |
import unittest
import pandas
import glob
import re
from Bio import SeqIO
import os
import subprocess
class PipelineTest(unittest.TestCase):
def test_gene_summary(self):
"""
Check that the info in genome_changes_summary.tsv is correct
"""
chromosomes = ['chromosome1','chromosome2',... | pombase/genome_changelog | test_pipeline_results.py | .py | 9146387695ded89f | 7.74 | 2 |
#!/usr/bin/env python3
# WARNING: This file is autogenerated - changes will be overwritten when regenerated by https://github.com/pulumi/ci-mgmt
"""Mirror the repo's mise toolchain into a global drop-in, so it resolves anywhere.
mise shims resolve a version from the *caller's* working directory. Anything that
runs out... | pulumi/pulumi-kubernetes-coredns | .openinspect/mise_global_fallback.py | .py | f8605dd8cbea9ea6 | 7.74 | 2 |
#!/usr/bin/env python3
# WARNING: This file is autogenerated - changes will be overwritten when regenerated by https://github.com/pulumi/ci-mgmt
"""
Runs once on fresh OpenInspect sandbox boot.
Boot sequence:
1. Install mise, trust the repo config, and install repo tools.
2. Run generated and repo-local setup hook... | pulumi/pulumi-kubernetes-coredns | .openinspect/setup.py | .py | 0ba9fb9408bae704 | 7.74 | 2 |
#!/usr/bin/env python3
# WARNING: This file is autogenerated - changes will be overwritten when regenerated by https://github.com/pulumi/ci-mgmt
"""Runs on every sandbox start, for whatever this session needs to be true now.
Sibling of setup.py, which bakes the image; this reconciles the running
session against the ch... | pulumi/pulumi-kubernetes-coredns | .openinspect/start.py | .py | 0f9bd36ac75380ea | 7.74 | 2 |
# -*- coding: utf-8 -*-
#
# (C) Copyright 2022 Karellen, Inc. (https://www.karellen.co/)
#
# 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
#
#... | karellen/wheel-axle-runtime | src/main/python/wheel_axle/runtime/_common.py | .py | 594bc7d8e82d0f20 | 7.15 | 1 |
# -*- coding: utf-8 -*-
#
# (C) Copyright 2022 Karellen, Inc. (https://www.karellen.co/)
#
# 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
#
#... | karellen/wheel-axle-runtime | src/main/python/wheel_axle/runtime/_wheel.py | .py | 4beda04cb951c642 | 7.15 | 1 |
"""
Copyright start
MIT License
Copyright (c) 2026 Fortinet Inc
Copyright end
"""
from connectors.core.connector import Connector
from connectors.core.connector import get_logger, ConnectorError
from .operations import _check_health, operations
logger = get_logger('github')
class GitHub(Connector):
def execute(... | fortinet-fortisoar/connector-github | github/connector.py | .py | 7e4613ddda79be7c | 7 | 0 |
import json
import subprocess
import sys
import time
import os
import click
import textwrap
def wait_for_port(host, port, timeout_secs, sleep_interval=2):
"""
Loops checking for a port using Netcat via subprocess.
"""
max_attempts = timeout_secs // sleep_interval
count = 0
# We use -w 1 for ... | Enucatl/puppet-control-repo | docker/vault/scripts/wake_on_lan.py | .py | 29a05c6c7efecd09 | 7.15 | 1 |
#!/usr/bin/env python3
"""Generate WireGuard client configuration from router settings."""
import click
import yaml
from pathlib import Path
def load_router_config():
config_path = Path(__file__).parent / "host_vars" / "router.yml"
with open(config_path) as f:
return yaml.safe_load(f)
def get_clien... | Enucatl/puppet-control-repo | provisioning/generate_wg_client_conf.py | .py | 30ac1fdf37d3e8cf | 7.15 | 1 |
import numpy as np
class IBM:
"""Adding a constant horizontal velocity to the particle tracking"""
def __init__(self, config):
# Can not initialize here, as grid is not available
# Azimuthal direction, 0 = N, 90 = E, 180 = S, 270 = W
self.direction = 180 # [clockwise degree from Nor... | pnsaevik/ladim | examples/gosouth/gosouth_ibm.py | .py | e2f591292af93e2e | 7.3 | 3 |
import copy
import numpy as np
from netCDF4 import Dataset
from ladim.gridforce import ROMS
from ladim.sample import sample2D
class Grid(object):
def __init__(self, config):
# Make a virtual grid, subgrid of original
i0, i1 = 80, 175
j0, j1 = 30, 110
self._i0 = i0
self._j... | pnsaevik/ladim | examples/nested/nested_gridforce.py | .py | 6f075e4cf2963020 | 7.3 | 3 |
"""
AssistantAgent 版本的路由示例(无回退)
需求:参考 langchain/chap02.py,实现路由 -> 委派逻辑,但仅使用
`autogen_agentchat.AssistantAgent`。如果环境未安装 `autogen-agentchat`
或无法构造 AssistantAgent,将直接抛出 ImportError/TypeError 以提示安装或调整。
运行示例:
```bash
export LLM_MODEL=deepseek-r1:8b
python3 autogen/chap02.py
```
"""
import os
import asyncio
from typing im... | feixiao/ai | AgenticDesignPatterns/autogen/chap02.py | .py | fdce9a48f0a443d1 | 7.35 | 4 |
"""
Planning + writing via autogen-agentchat (qwen3:8b by default).
We use RoundRobinGroupChat with a TextMentionTermination keyword. Planner
creates bullet points, writer produces the summary and appends the stop word.
"""
import asyncio
import os
from typing import Iterable, List, Tuple
from autogen_agentchat.agen... | feixiao/ai | AgenticDesignPatterns/autogen/chap06.py | .py | 84ad34d59fe0e999 | 7.35 | 4 |
from typing import Optional
import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough, ... | feixiao/ai | AgenticDesignPatterns/langchain/chap02.py | .py | 2b3e50bac9357421 | 7.35 | 4 |
import os
import asyncio
from typing import Optional
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import Runnable, RunnableParallel, RunnablePassthrough
de... | feixiao/ai | AgenticDesignPatterns/langchain/chap04.py | .py | e1ff0d31b4a93a6a | 7.35 | 4 |
"""
说明
----
本示例演示:在“模型不支持原生工具调用(function/tool calling)”的情况下,
如何使用“轻量 ReAct 决策 -> 可选调用 Python 工具 -> 汇总回答”的流程来完成工具增强。
适配背景:
- 例如 Ollama 的 deepseek-r1:14b 模型(registry.ollama.ai/library/deepseek-r1:14b)当前不支持 tools。
- 我们不直接依赖 langchain 的 Agents(如 AgentExecutor、create_tool_calling_agent 等),
而是通过两个 Prompt 链手动决定是否调用工具,并汇总最终... | feixiao/ai | AgenticDesignPatterns/langchain/chap05.py | .py | 00b9657fdacafd0e | 7.35 | 4 |
import os
from typing import Optional
from langchain_core.tools import tool # 定义/注册可被 LC 使用的 Python 工具
from langchain_core.prompts import PromptTemplate
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables import RunnableSequence
from langchain_core.runnables.history import... | feixiao/ai | AgenticDesignPatterns/langchain/chap08_01.py | .py | d182b426b9f631dd | 7.35 | 4 |
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
# If you want to run a snippet of code before or after the crew starts,
# you can use the @before_kickoff and @after_kickoff decorator... | feixiao/ai | crewai/hello_crew/src/hello_crew/crew.py | .py | b3ded58fb2bb7298 | 7.35 | 4 |
from crewai.tools import BaseTool
from typing import Type
from pydantic import BaseModel, Field
class MyCustomToolInput(BaseModel):
"""Input schema for MyCustomTool."""
argument: str = Field(..., description="Description of the argument.")
class MyCustomTool(BaseTool):
name: str = "Name of my tool"
d... | feixiao/ai | crewai/hello_crew/src/hello_crew/tools/custom_tool.py | .py | d7c5b7086613ba1b | 7.35 | 4 |
"""最简 FunctionCallAgent 示例"""
from hello_agents.agents import FunctionCallAgent
from hello_agents.core.llm import HelloAgentsLLM
from hello_agents.tools.registry import ToolRegistry
def get_horoscope(sign: str) -> str:
sample_data = {
"白羊座": "保持耐心,合作能带来额外好运。",
"金牛座": "适合整理计划,财务上保持谨慎。",
"双... | feixiao/ai | helloagent/chap00.py | .py | fbb74ecfaa177bb9 | 7.35 | 4 |
from maya.api import OpenMaya as om
from rl_vp.math_utils import vector_math as vm
def getObservation(drivers_mtx, agent_mtx, restVector):
"""standalone get observation since is ti will be usead for the enviroment
and the node
Args:
drivers_mtx ([type]): [description]
agent_mtx ([type]): ... | lopezmauro/RL_Maya | rl_vp/enviroment/observation.py | .py | 9dc2ae2a491cd094 | 7.35 | 4 |
import numpy as np
def initializeCentroids(points, k):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:k]
def closestCentroid(points, centroids):
"""returns an array containing the index to the nearest centroid for each po... | lopezmauro/RL_Maya | rl_vp/math_utils/k_means.py | .py | 945db9713b4e2463 | 7.35 | 4 |
import numpy as np
def magnitude(x):
return np.linalg.norm(x)
def normalize(x):
return np.array(x) / magnitude(x)
def pointToLineDistance(start, end, point):
""" segment line AB, point P, where each one is an array([x, y]) """
A = np.array(start)
B = np.array(end)
P = np.array(point)
i... | lopezmauro/RL_Maya | rl_vp/math_utils/vector_math.py | .py | ab8393aa1b29d433 | 7.35 | 4 |
from .mUtils import mNode
import numpy as np
def getFacesVertices(mesh):
"""Returns the index of the vertex that conform each face
Args:
meshFn (UsdGeom.Mesh): USD mesh prim
Returns:
list of list: vertex indices for each face ex: [[1,2,3,4],[2,3,5,6],...]
"""
meshNode = mNode.MNode... | lopezmauro/RL_Maya | rl_vp/maya_utils/meshes.py | .py | 6c7914d2e04e9974 | 7.35 | 4 |
import logging
import copy
from . import meshes
from .mUtils import mNode
from maya import cmds
_logger = logging.getLogger(__name__)
def getDeformersFromMesh(sourceMesh, nodeType="skinCluster"):
history = cmds.listHistory(str(sourceMesh), pruneDagObjects=True) or list()
deformers = [a for a in history if 'ge... | lopezmauro/RL_Maya | rl_vp/maya_utils/skinCluster.py | .py | a9a8752941f71d06 | 7.35 | 4 |
from pathlib import Path
global config_file
pkg_path = Path(__file__).parent.absolute()
config_file = pkg_path / '.config'
def check_config():
'''
Check that configuration file exists, and if not, create a blank one.
Having a blank file exist eases throwing any FileNotFoundError's, but
if the config ... | ArgoCanada/provor-auto-param-update | provorpy/configure.py | .py | fdd8cf4ba2da8efc | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""bearer_token.py
Validation of Auth0-issued user access tokens forwarded as `Authorization: Bearer` by
first-party services acting on a user's behalf - e.g. catalog-api promoting a staged cover to
live during edit-session finalize. Server-to-se... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/bearer_token.py | .py | 09bf4ee6c6981a8c | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""
"""
from functools import wraps
from urllib.parse import urlencode
from sweetrpg_assets_web.application import constants
from sweetrpg_assets_web import __version__
from flask import Blueprint, request, session, jsonify, current_app, make_res... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/blueprints/__init__.py | .py | 2983b2e7eb254c97 | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""
config.py
- settings for the flask application object
"""
import os
import redis
import random
import hashlib
from sweetrpg_assets_web.application import constants
def _env_bool(name: str, default: bool) -> bool:
"""Parse a boolean env... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/config.py | .py | 7c106a53c05414bf | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""
i18n
- Localization support: Flask-Babel setup and per-request locale resolution,
per the `web-frontend-localization` spec (sweetrpg/platform's
openspec/changes/full-localization-web-apps).
"""
from flask import request
from flask_babel impor... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/i18n.py | .py | de741aafb15e46d1 | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""main.py
Creates a Flask app instance and registers various services and middleware.
"""
from flask import Flask, session, g
from flask_cors import CORS
from flask_session import Session
from dotenv import load_dotenv, find_dotenv
from sweetrp... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/main.py | .py | 303a973e4aa8a5c4 | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""reclaim.py
Periodic reclaim of orphaned cover-staged/sample-staged assets (durable-volume-editing task
2.4). A staged asset can legitimately outlive its edit session (a submitter's finalize hands
the reference to a pending submission), so an a... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/reclaim.py | .py | 2aede5f20de8a27f | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""shared_session.py
Read-only access to the suite-wide login session `auth-web` writes under the `sweetrpg_session`
cookie (see docs/frontend-conventions.md's "Shared session schema" in sweetrpg/platform, and
catalog-web's SessionUserAccess.swif... | sweetrpg/assets-web | src/sweetrpg_assets_web/application/shared_session.py | .py | 52e281813efb4934 | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""conftest.py
Shared fixtures for the test suite.
"""
import datetime
import json
import os
import pytest
import redis as redis_lib
SHARED_SESSION_DB = 10
@pytest.fixture
def app(tmp_path, monkeypatch):
monkeypatch.setenv("REDIS_HOST", "... | sweetrpg/assets-web | tests/conftest.py | .py | 7e36689a2aa5cc4e | 7.5 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""
Tests for the maintenance-mode redirect behavior.
"""
from urllib.parse import parse_qs, urlparse
from sweetrpg_admin_api_client import MaintenanceMode
def test_active_mode_redirects_to_shared_maintenance_page(app, client):
app.admin_c... | sweetrpg/assets-web | tests/test_maintenance.py | .py | 17ecdbbb1530f299 | 7.5 | 0 |
"""create members
Revision ID: 0002
Revises: 0001
"""
from alembic import op
import sqlalchemy as sa
revision = "0002"
down_revision = "0001"
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"members",
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("name",... | diegopacheco/python-playground | Alembic-migrations/migrations/versions/0002_create_members.py | .py | 120c00753d2026fe | 7 | 0 |
from decimal import DivisionByZero
import logging
import pybreaker
class Listener(pybreaker.CircuitBreakerListener):
"Listener used by circuit breakers that execute database operations."
def before_call(self, cb, func, *args, **kwargs):
"Called before the circuit breaker `cb` calls `func`."
#lo... | diegopacheco/python-playground | PyBreaker-Fun/src/main.py | .py | 9b21f207dd167dc5 | 7 | 0 |
#!/usr/bin/env python3
import unittest
import os
import shutil
import subprocess
precommit = __import__("pre-commit")
def run_command(command):
"Run a shell command and ensure it didn't error"
r = subprocess.run(command, stdout=subprocess.PIPE, encoding='utf-8',
shell=True)
r.chec... | The-OpenROAD-Project/security | git/hooks/test.py | .py | 34a475889fba4b9d | 7.85 | 4 |
'''
Tests for the main.py
'''
from importlib import import_module
from dataclasses import dataclass
# from inspect import cleandoc
# from json import loads
import unittest
import sys
import os
try:
prime = import_module('main')
# works when running as
# python -m unittest discover
except ImportError as err... | JamesLi-dev/JamesLi-dev | tests/test_main.py | .py | e4da9982e392f1a2 | 7.74 | 2 |
"""Unit tests for hn_feeds.
Run from the repo root with:
python -m unittest discover -s app -p '*_test.py'
"""
import logging
import pickle
import unittest
from unittest import mock
import feedparser
import hn_feeds
import requests
from feedgen.entry import FeedEntry
# A minimal RSS document, as returned by the f... | nova77/hackernews_rss | app/hn_feeds_test.py | .py | 57ed64f870afda31 | 7.5 | 0 |
"""Convert between base case and PSS/E rawx format."""
import hashlib
import json
from pathlib import Path
from typing import Any
from uuid import UUID
import pandas as pd
from rawxio.data_model import (
PARAMETER_SETS,
DataSetType,
get_pk_fields,
get_required_fields,
has_primary_key,
)
def get... | statnett/rawxio | src/rawxio/rawx.py | .py | 4b7633d90a119b99 | 7 | 0 |
"""This module contains a set of utility functions included for convenience."""
import pandas as pd
def shift_array_indices(
df: pd.DataFrame, amount: int, cols: set[str] | None = None
) -> pd.DataFrame:
cols = cols or {"ibus", "jbus", "kbus"}
columns = list(cols.intersection(df.columns))
if not cols... | statnett/rawxio | src/rawxio/utils.py | .py | 3ab7555b532077fc | 7 | 0 |
# 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
# distrib... | NeCTAR-RC/python-warreclient | warreclient/osc/plugin.py | .py | 0545ba7daa61ccfc | 7 | 0 |
# 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
# distrib... | NeCTAR-RC/python-warreclient | warreclient/osc/v1/limits.py | .py | 78619ad7c92733f6 | 7 | 0 |
# 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
# distrib... | NeCTAR-RC/python-warreclient | warreclient/v1/client.py | .py | 5129bcaf9b3c424e | 7 | 0 |
# 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
# distrib... | NeCTAR-RC/python-warreclient | warreclient/v1/limits.py | .py | 561c92f3876e543d | 7 | 0 |
import argparse
import json
import logging
import os
import time
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Dict, List, Set, Tuple, TypedDict, Union
from github import Github
logger = logging.getLogger(__name__)
@dataclass
class Arg... | wlamason/github-stars | github_stars.py | .py | 548b73413c3c79f8 | 7.35 | 4 |
import numpy as np
import pandas as pd
import xarray as xr
from .utils import read_dataset_csv
def load_file(name):
"""Return a requested data file."""
return read_dataset_csv("alter2018", name)
def data():
# Get axes
subjects = load_file("meta-subjects")["subject"].to_list()
detections = load_... | meyer-lab/tensordata | tensordata/alter.py | .py | 6f630e1154161928 | 7.15 | 1 |
import numpy as np
import pandas as pd
from .utils import PACKAGE_DIR, read_dataset_csv
DATASET_DIR = "jones2017"
RA_DATAFRAME_PATH = PACKAGE_DIR / DATASET_DIR / "RA_DataFrame.csv"
donorDict = {
"1869": "RA",
"1931": "RA",
"2159": "RA",
"2586": "N",
"2645": "N",
"2708": "RA",
"2759": "N",... | meyer-lab/tensordata | tensordata/jones.py | .py | 64f74f62e059888f | 7.15 | 1 |
import numpy as np
import xarray as xr
from .kaplonek import MGH4D, SpaceX4D
from .zohar import data as Zohar
def checkMissingess(cube):
return 1 - np.sum(np.isfinite(cube)) / np.prod(cube.shape)
def normalizeSubj(cube):
cube -= np.nanmean(cube, axis=0)
cube = cube / np.nanstd(cube, axis=0)
return ... | meyer-lab/tensordata | tensordata/serology.py | .py | 2ea7b5f271779f9a | 7.15 | 1 |
"""Shared helpers for loading and reshaping the packaged datasets."""
from pathlib import Path
import pandas as pd
import xarray as xr
PACKAGE_DIR = Path(__file__).parent
def read_dataset_csv(dataset_dir: str, name: str, **kwargs) -> pd.DataFrame:
"""Read a CSV file out of one of the packaged dataset directori... | meyer-lab/tensordata | tensordata/utils.py | .py | ae59c0ec9cf0d5fb | 7.15 | 1 |
#!/usr/bin/env python3
"""Patch vLLM ModelOpt NVFP4 loading for Deckard/Gemma NVFP4_AWQ checkpoints.
The Gemma 4 31B Deckard AWQ_FULL checkpoint was produced with ModelOpt 0.42.x.
It uses quant_algo="NVFP4_AWQ" and stores optional per-linear
`pre_quant_scale` tensors. Older vLLM ModelOpt loaders reject that quant_algo... | Nihal-puliyakkady/Gemma-4-31B-Uncensored-NVFP4-DFlash | patches/patch_modelopt_nvfp4_awq.py | .py | 13c8f16903293fb9 | 7.15 | 1 |
from enum import Enum, unique
from typing import TypeAlias
__all__ = ["DecorationModel", "DeviceModel", "Model", "PartModel"]
@unique
class PartModel(Enum):
Tile10x10 = 9
Tile20x20 = 11
TileA30x30 = 13
TileB30x30 = 16
Tile10x90 = 10
Tile20x90 = 12
TileA30x90 = 14
TileB30x90 = 17
T... | DigitalDetective47/koro | src/koro/stage/model.py | .py | 6719ae29c79e9dd0 | 7.15 | 1 |
"""AppleScript execution, validation, and escaping utilities for Apple Mail."""
import re
import subprocess
import time
from pathlib import Path
def validate_id(value: str, label: str = "id") -> str:
"""Validate that an id is numeric to prevent AppleScript injection."""
if not re.match(r"^\d+$", value.strip(... | ridzkyyyyy/apple-mail | scripts/lib/applescript.py | .py | cbe89cb2d982e4a4 | 7 | 0 |
"""Account-level operations using batch JXA."""
import json
from ..jxa import run_jxa_with_core, JXAError, enrich_with_content
def list_accounts():
"""Get all logged in mail accounts (~0.15 s)."""
try:
return run_jxa_with_core("JSON.stringify(MailCore.listAccounts());")
except (JXAError, TimeoutE... | ridzkyyyyy/apple-mail | scripts/lib/ops/accounts.py | .py | bd0aac5c28bc0509 | 7 | 0 |
"""Email retrieval using JXA direct ID lookup, with cache-on-read.
read_full_email splits into two phases so a slow msg.content() call
(large HTML, inline images, Exchange sync stall) never blocks the
metadata that is always fast:
Phase 1 - metadata: subject, sender, dates, recipients, attachments (~0.5 s)
Phase ... | ridzkyyyyy/apple-mail | scripts/lib/ops/read.py | .py | 1ea162ef3abae6e0 | 7 | 0 |
"""Email search using FTS5 index and JXA."""
import json
from ..search_index import SearchIndexManager
from ..jxa import run_jxa_with_core, JXAError
def search_emails(query: str, scope: str = "all", account_email: str = None, limit: int = 20) -> list[dict]:
"""Search emails by content, subject, or sender.
s... | ridzkyyyyy/apple-mail | scripts/lib/ops/search.py | .py | ddf19665499a594d | 7 | 0 |
"""Direct disk reading of Apple Mail .emlx files for FTS5 indexing.
Requires Full Disk Access for Terminal.
Mail.app storage structure:
~/Library/Mail/V10/
+-- [Account-UUID]/
| +-- [Mailbox].mbox/
| +-- .../.../Messages/
| +-- 12345.emlx
| +-- 12346.emlx
+-- Ma... | ridzkyyyyy/apple-mail | scripts/lib/search_index/disk.py | .py | 81cedc63aa8ae872 | 7 | 0 |
"""Batch processing with parallel workers.
Supports:
- Plain text input (one item per line, # comments skipped)
- NDJSON input (one JSON object per line)
- JSON array input
- Parallel workers with bounded concurrency
- NDJSON output with index correlation
- Fail-fast on fatal errors (auth, forbidden)
"""
... | Administrative-Assistance/flarecrawl | src/flarecrawl/batch.py | .py | bc5e55ea0f5d0a33 | 7.3 | 3 |
"""Simple file-based response cache for Flarecrawl.
Caches API responses keyed on (endpoint, url, body_hash) with configurable TTL.
Cache is stored in the platform config directory under a 'cache' subdirectory.
"""
from __future__ import annotations
import hashlib
import json
import time
from pathlib import Path
fr... | Administrative-Assistance/flarecrawl | src/flarecrawl/cache.py | .py | 86960260ec89036c | 7.3 | 3 |
"""Flarecrawl configuration and credential storage."""
import json
import os
import platform
import tempfile
from pathlib import Path
APP_NAME = "flarecrawl"
def get_env_int(key: str, default: int) -> int:
"""Get integer from environment variable with fallback."""
val = os.environ.get(key, "").strip()
i... | Administrative-Assistance/flarecrawl | src/flarecrawl/config.py | .py | c3bc2edb27e6b03a | 7.3 | 3 |
"""Test fixtures for Flarecrawl."""
import pytest
@pytest.fixture
def mock_credentials(monkeypatch):
"""Set fake credentials via env vars."""
monkeypatch.setenv("FLARECRAWL_ACCOUNT_ID", "test-account-id")
monkeypatch.setenv("FLARECRAWL_API_TOKEN", "test-api-token")
@pytest.fixture
def no_credentials(mo... | Administrative-Assistance/flarecrawl | tests/conftest.py | .py | 5e7a88af218fe042 | 7.8 | 3 |
"""Tests for batch processing module."""
import asyncio
import json
import pytest
from flarecrawl.batch import parse_batch_file, process_batch
class TestParseBatchFile:
"""Test auto-detection and parsing of batch input files."""
def test_plain_text(self, tmp_path):
f = tmp_path / "urls.txt"
... | Administrative-Assistance/flarecrawl | tests/test_batch.py | .py | 705bc2e3877715db | 7.8 | 3 |
"""Tests for the cache module."""
import json
import time
import pytest
from flarecrawl.cache import _cache_key, clear, get, put
class TestCacheKey:
"""Test cache key generation."""
def test_deterministic(self):
key1 = _cache_key("markdown", {"url": "https://example.com"})
key2 = _cache_ke... | Administrative-Assistance/flarecrawl | tests/test_cache.py | .py | b6f727a3e2079518 | 7.8 | 3 |
"""Client tests for Flarecrawl."""
from flarecrawl.client import Client
class TestBodyBuilder:
"""Test the body builder converts flat kwargs to nested API JSON."""
def test_basic_url(self):
body = Client._build_body(url="https://example.com")
assert body == {"url": "https://example.com"}
... | Administrative-Assistance/flarecrawl | tests/test_client.py | .py | 34a4ebbb38127695 | 7.8 | 3 |
"""
Generiert PWA-Icons aus src/web/static/logo.png.
Produziert eine Mobile-optimierte Variante (dunkler Hintergrund + Glow + Prism zentriert)
in verschiedenen Größen für Web-Manifest, Apple Touch Icon und Notification Badge.
Ausführen:
source venv/bin/activate
python scripts/generate_pwa_icons.py
"""
from _... | waterbruh/Velora | scripts/generate_pwa_icons.py | .py | 750bdefdf280cce3 | 7.15 | 1 |
"""
Chat-Verlauf für Telegram-Gespräche.
Speichert die letzten Nachrichten damit Claude Kontext hat.
"""
import json
import logging
from datetime import datetime
from pathlib import Path
logger = logging.getLogger(__name__)
MEMORY_DIR = Path(__file__).parent.parent.parent / "memory"
HISTORY_FILE = MEMORY_DIR / "chat... | waterbruh/Velora | src/analysis/chat_history.py | .py | 6a50ff53f623f805 | 7.15 | 1 |
"""
Claude Code CLI Wrapper.
Ruft Claude im non-interactive Modus auf.
"""
import fcntl
import json
import logging
import os
import re
import shutil
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
class ClaudeCLIError(RuntimeError):
"""Claude CLI-Aufruf fehlgeschlagen (exit code,... | waterbruh/Velora | src/analysis/claude.py | .py | 146ad644aa641edf | 7.15 | 1 |
"""
Memory-System für den Vermögensberater.
Speichert vergangene Analysen, Empfehlungen und deren Outcomes.
Verhindert Wiederholungen und ermöglicht Lernen.
"""
import json
import logging
from datetime import datetime
from pathlib import Path
logger = logging.getLogger(__name__)
MEMORY_DIR = Path(__file__).parent.pa... | waterbruh/Velora | src/analysis/memory.py | .py | 74a1d9f2bfa4696c | 7.15 | 1 |
"""
System-Prompt und Daten-Formatting für den Vermögensberater.
"""
import json
from datetime import datetime
SYSTEM_PROMPT_TEMPLATE = """Du bist ein erfahrener, unabhängiger Vermögensberater (CFA Level III, 15 Jahre Erfahrung Multi-Asset).
WICHTIGE REGELN:
1. DATEN-INTEGRITÄT:
- Du erfindest NIEMALS Zahlen, K... | waterbruh/Velora | src/analysis/prompt.py | .py | fbacecf5aac94d5a | 7.15 | 1 |
"""Claude Code CLI Subprocess mit stream-json Parsing.
Startet die CLI im Non-Interactive-Modus (--print), lässt sie NDJSON emittieren,
und yielded parsed Events (text-deltas, tool-calls, tool-results, done).
Session-Persistenz via --session-id / --resume, sodass Folge-Messages die
History nicht erneut im Prompt trans... | waterbruh/Velora | src/chat/claude_stream.py | .py | 84907e1153c20e0d | 7.15 | 1 |
"""
Zentraler Settings-Loader mit ENV-Override.
Alle Module importieren von hier statt eigene _load_settings-Funktionen zu haben.
ENV-Variablen haben Vorrang vor config/settings.json — wichtig für Secrets auf
Production (RockPi via systemd EnvironmentFile), damit settings.json nur
Defaults/Struktur enthält und Tokens/... | waterbruh/Velora | src/config_loader.py | .py | c45a6555faa7e51f | 7.15 | 1 |
"""Sichere Portfolio-IO: File-Lock + atomic write + rotating Backups.
Verhindert Race-Conditions bei parallelen Trade-Loggings (Web-UI, Telegram,
Chat) und stellt sicher, dass portfolio.json nie durch halbfertige Writes
korrumpiert wird.
Jede Mutation durchläuft `with portfolio_write_lock() as portfolio:` — Block:
1.... | waterbruh/Velora | src/delivery/portfolio_io.py | .py | 0393e027b55a6c00 | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.