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
"""Serve the newest independent audit run to the admin page. The audit itself is `scripts/audit-library.py`, which shares no code with this package on purpose: its whole claim is that it checks the library without reusing the pipeline's readers, models or assumptions. Reading the JSON it already wrote does not touch t...
junyang168/smart-answer
backend/api/library_audit.py
.py
6728f4dc9f0cd96d
7
0
import os import json from typing import Dict, Any, Optional from openai import OpenAI from dotenv import load_dotenv # Load environment variables once when the module is imported load_dotenv() _client = None DEFAULT_OPENAI_GENERATION_MODEL = os.getenv( "OPENAI_GENERATION_MODEL", "gpt-5.6-sol", ) def get_ope...
junyang168/smart-answer
backend/api/openai_client.py
.py
7ef4dcac7ff613a1
7
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 5 23:37:31 2024 @author: omari """ import numpy as np import pylab as plt import pandas as pd def eular(X,fun,Y0=0,**kw): A=[Y0] for i in range(0,len(X)-1): dx=X[i+1]-X[i] A.append(A[-1]+dx*fun(X[i],A[-1],**kw)) return ...
mmomari072/Labeeb
archive/coupling_omari_test/coupling_iteration_0/mcnp/case_0/mcnp_dfun1.py
.py
717d6ad063579813
7.65
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 5 23:37:31 2024 @author: omari """ import numpy as np import pylab as plt import pandas as pd def eular(X,fun,Y0=0,**kw): A=[Y0] for i in range(0,len(X)-1): dx=X[i+1]-X[i] A.append(A[-1]+dx*fun(X[i],A[-1],**kw)) return ...
mmomari072/Labeeb
archive/coupling_omari_test/coupling_iteration_1/mcnp/case_0/mcnp_dfun1.py
.py
47e6b17ce788c91b
7.65
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 5 23:37:31 2024 @author: omari """ import numpy as np import pylab as plt import pandas as pd def eular(X,fun,Y0=0,**kw): A=[Y0] for i in range(0,len(X)-1): dx=X[i+1]-X[i] A.append(A[-1]+dx*fun(X[i],A[-1],**kw)) return ...
mmomari072/Labeeb
archive/coupling_omari_test/coupling_iteration_2/mcnp/case_0/mcnp_dfun1.py
.py
7613dc3534472f8b
7.65
1
""" Case module to define case configuration, directory structure, input processing, simulation runs, and parsing outputs. """ import logging import os from typing import Any, Dict, List, Optional, Union import pandas as pd from .coupled_unit import CoupledUnit from .database import Attribute, Database from .excepti...
mmomari072/Labeeb
src/labeeb/case.py
.py
e2051c6f41b4fcde
7.15
1
""" Shared convergence-driven execution contract for Case and Coupler. Design note (resolves the row-driven vs. convergence-driven ambiguity): `run_to_convergence` never reads `len(database)` or any row/scenario count. Row/scenario looping stays exclusively in each subclass's own `launch()`. `run_to_convergence` only ...
mmomari072/Labeeb
src/labeeb/coupled_unit.py
.py
e7c856752dabfd71
7.15
1
""" Coupler module to couple multiple cases (e.g., MCNP and RELAP5 simulations) in an iterative loop, utilizing database parameters and user-defined coupling functions. """ import copy import logging import os from typing import Any, Callable, Dict, List, Optional, Union from .case import Case from .coupled_unit impo...
mmomari072/Labeeb
src/labeeb/coupler.py
.py
b8ea3a7fc56f3b28
7.15
1
""" Sampling methods for sensitivity analysis, uncertainty analysis, and parameter sweeps. Includes Grid Sweep (Full Factorial Design) and Discrete Probability Samplers. """ import itertools import logging import random from typing import Any, Dict, List, Optional, Union import numpy as np from .exceptions import Sa...
mmomari072/Labeeb
src/labeeb/sampler.py
.py
87246548f9fe3ca6
7.15
1
""" File I/O utilities for searching, replacing placeholders, and processing text files. Used heavily for managing code input decks (e.g. MCNP, RELAP5 inputs). """ import logging import os from copy import deepcopy from typing import Any, Callable, Dict, List, Optional, Union logger = logging.getLogger(__name__) cl...
mmomari072/Labeeb
src/labeeb/utils/file_io.py
.py
16fbdf8743cb3251
7.15
1
""" Timer and Progress Bar utilities to track and display execution times. """ import sys import time from typing import Any, List, Optional, Tuple class Timer: """ A simple timer class to measure elapsed time. """ def __init__(self, name: Optional[str] = None): self.name: Optional[str] = na...
mmomari072/Labeeb
src/labeeb/utils/progress.py
.py
90e48e7e72d02c23
7.15
1
from typing import Callable import reflex as rx from website_frontend.model.featured import Featured def _animation_style(direction: str, speed: str) -> dict: animation_direction = "forwards" if direction == "left" else "reverse" if speed == "fast": duration = "20s" elif speed == "normal": ...
deivisaherreraj/link-in-bio
website_frontend/website_frontend/components/ui/auto_scrolling_carousel.py
.py
1e355c78f1cccd11
7.15
1
"""Create a throwaway repo from this template, verify it, then optionally clean it up. Azure DevOps counterpart to integration_test_github.py -- see that file for the shared shape (create/verify/cleanup, --cleanup/--ci flags). Diverges in a few real ways: - No Settings App equivalent here, so nothing to poll for asyn...
natescherer/postmodern-repo-copiertemplate
scripts/integration_test_azdo.py
.py
aa682f586b6c23fe
7.8
3
"""Create a throwaway repo from this template, verify it, then optionally clean it up. Shared by `mise run integration-test-gh` (a human's own gh/GCM session, repo left in place by default so it can be inspected) and test-integration_test.yml (INTEGRATION_TEST_PAT, always passes --cleanup) -- not templated itself; bot...
natescherer/postmodern-repo-copiertemplate
scripts/integration_test_github.py
.py
635503dc8884945b
7.8
3
"""Create a throwaway repo from this template, verify it, then optionally clean it up. Azure DevOps counterpart to integration_test_github.py -- see that file for the shared shape (create/verify/cleanup, --cleanup/--ci flags). Diverges in a few real ways: - No Settings App equivalent here, so nothing to poll for asyn...
natescherer/postmodern-repo-copiertemplate
template/{% if is_template %}scripts{% endif %}/integration_test_azdo.py
.py
54d2ba4b0dd9a5b4
7.8
3
"""Create a throwaway repo from this template, verify it, then optionally clean it up. Shared by `mise run integration-test-gh` (a human's own gh/GCM session, repo left in place by default so it can be inspected) and test-integration_test.yml (INTEGRATION_TEST_PAT, always passes --cleanup) -- not templated itself; bot...
natescherer/postmodern-repo-copiertemplate
template/{% if is_template %}scripts{% endif %}/integration_test_github.py
.py
435d23395fc2e74f
7.8
3
"""Shared fixtures and helpers for rendering this template against real Copier. Generic by design: nothing here hardcodes this repo's specific doc set or question values -- see answer_matrix.py for the repo-specific piece, which a child template should edit alongside its own copier.yml changes. """ import io import s...
natescherer/postmodern-repo-copiertemplate
template/{% if is_template %}tests{% endif %}/conftest.py
.py
ed6979699f110346
7.8
3
"""Checks answer_matrix.py's own completeness against copier.yml's real question set. Generic by design: parses whatever copier.yml actually defines, rather than hardcoding this repo's specific question names -- see answer_matrix.py for the repo-specific answer data these checks audit, including COVERAGE_EXEMPT_QUESTI...
natescherer/postmodern-repo-copiertemplate
template/{% if is_template %}tests{% endif %}/test_answer_matrix_coverage.py
.py
2eb5614b0657cc2a
7.8
3
"""Checks content/config consistency in the rendered template, not the rendering itself. Generic by design: every check here operates on whatever actually got rendered, rather than hardcoding this repo's specific doc set -- see answer_matrix.py for the repo-specific piece, which a child template should edit alongside ...
natescherer/postmodern-repo-copiertemplate
template/{% if is_template %}tests{% endif %}/test_content.py
.py
2e5e9693a2dc19c3
7.8
3
"""Renders this template across a boundary answer matrix and structurally validates it. Generic by design: every check here operates on whatever actually got rendered (globbing for file types, checking for known top-level files) rather than hardcoding this repo's specific doc set or question values -- see answer_matri...
natescherer/postmodern-repo-copiertemplate
template/{% if is_template %}tests{% endif %}/test_render.py
.py
ec4200371029e797
7.8
3
"""Renders this template across a boundary answer matrix and structurally validates it. Generic by design: every check here operates on whatever actually got rendered (globbing for file types, checking for known top-level files) rather than hardcoding this repo's specific doc set or question values -- see answer_matri...
natescherer/postmodern-repo-copiertemplate
tests/test_render.py
.py
9488f9f45110c24e
7.8
3
# (c) 2025 Jonathan Brandt # Licensed under the MIT License. See LICENSE file in the project root. # Cache objects in persistent store import json import os from threading import Lock from pathlib import Path from birddog.log import get_logger, LogService _logger = get_logger() _cache_lock = Lock() # could be overk...
jbrandt130/birddog
birddog/cache.py
.py
5efcac5bef17c1d8
7
0
# (c) 2025 Jonathan Brandt # Licensed under the MIT License. See LICENSE file in the project root. import re import string import os from io import BytesIO import glob from pathlib import Path from copy import copy from datetime import datetime from html import unescape from openpyxl import load_workbook from openpy...
jbrandt130/birddog
birddog/excel.py
.py
9e5d44947b815205
7
0
import math import re import pandas as pd from rapidfuzz import distance def normalize_name(text: str) -> str: """Removes all spaces, hyphens, and non-alphanumeric punctuation.""" # Matches anything that is NOT a letter or a number and removes it return re.sub(r"[^a-zA-Z0-9]", "", text.lower()) def rea...
jbrandt130/birddog
research/triage/locations/read_all_locations.py
.py
8be5811bbb6cc861
7
0
import unittest from unittest.mock import patch, MagicMock from contextlib import contextmanager import threading import time import requests as _real_requests # for exception classes import birddog.fetch as reqmod from birddog.fetch import fetch_url # ------------------ TEST HELPERS ------------------ class Resp...
jbrandt130/birddog
test/test_fetch.py
.py
88338ad72ee86697
7.5
0
import os import time import uuid import unittest import tempfile import botocore from birddog.store import ( # String queues SQLiteStringQueue, DynamoDBStringQueue, # Key-value stores SQLiteKeyValueStore, DynamoDBKeyValueStore, ) # ------------------ STORE UNIT TESTS ------------------ cl...
jbrandt130/birddog
test/test_store.py
.py
c235b43dfeb77889
7.5
0
import os import random import threading import time import unittest from birddog.task import ( TaskManager, ) # ------------------ UTILITY UNIT TESTS ------------------ task_register = { "a": {"length": 5, "complete": False}, "b": {"length": 25, "complete": False}, "c": {"length": 9, "complete":...
jbrandt130/birddog
test/test_task.py
.py
fb70f7a8cf24d140
7.5
0
# # # import unittest import asyncio import threading from birddog.translate import ( translation, translate_structure, get_translation_items, TranslationDisabledError, ) from birddog.wiki import mw_read_page from birddog.utility import is_english # ------------------ TRANSLATE UNIT TESTS -------...
jbrandt130/birddog
test/test_translate.py
.py
545431dcfe0cbcd1
7.5
0
#!/usr/bin/env python3 """ Sync course facts from Canvas into course_data/schedule.json. INSTRUCTOR-SIDE ONLY. This script needs a Canvas API token; the Streamlit app does not, and must never be given one. A Canvas personal access token inherits every permission of the user who created it -- rosters, grades, submissio...
lawnhero/isom352
scripts/sync_canvas.py
.py
2d58edb8b9015a0c
7
0
"""Tier A rendering: the facts block the tutor reads on every facts question. Pure functions, `now` passed explicitly, so the term can be simulated at any point without touching the real course_data files. """ from datetime import datetime, timezone from utils import course_context as cc NOW = datetime(2026, 9, 1, ...
lawnhero/isom352
tests/test_course_context.py
.py
b26d61dafa7cc5eb
7.5
0
"""ModelWithFallback must fall back on STREAMING failures, not only invoke(). Every tutoring chain streams. BaseChatModel.stream is a generator function, so `primary.stream(...)` cannot raise at call time -- the request is sent on the first next(). A try/except around the call alone never catches anything, which is ho...
lawnhero/isom352
tests/test_llm_fallback.py
.py
f2f89553eeeff7b7
7.5
0
"""The held practice question: written by app.py, read by three tools.""" from utils import practice def test_lifecycle_counts_hints_and_attempts(): session = practice.start("Q: compute the mean", "Descriptive statistics", "harder") assert practice.is_active(session) assert session["difficulty"] == "hard...
lawnhero/isom352
tests/test_practice_session.py
.py
cc24127b345298e4
7.5
0
"""Date words from the student's sentence -> exact Chroma filters. The router copies "july 30" through verbatim; everything calendar-shaped happens here, in Python, against the course's own date span.""" import pytest from utils.retrieval import ( build_document_filter, content_overlap, parse_course_date...
lawnhero/isom352
tests/test_retrieval_dates.py
.py
d198861c297898d8
7.5
0
""" Turn chat-input attachments into something the tutor can actually read. Text files (txt/csv/tsv/md/json) and PDFs are decoded and inlined into the student's query. Screenshots are decoded, downscaled, and handed back separately as base64 data URLs for the vision builds of the tutoring chains (see `chains_lcel._wit...
lawnhero/isom352
utils/attachments.py
.py
c5fc96c3c25705fe
7
0
from dotenv import load_dotenv from langchain_deepseek import ChatDeepSeek from langchain_openai import ChatOpenAI from langchain_core.language_models import BaseChatModel from pydantic import Field load_dotenv() # Create a couple of Global Variables TEMPERATURE = 0.1 MAX_TOKENS = 1024 class ModelWithFallback(BaseC...
lawnhero/isom352
utils/llm_models.py
.py
6c23a2cb9c7ed54d
7
0
"""The practice question currently on the student's screen. WHY THIS EXISTS `check_attempt` used to grade against `topic` plus whatever survived in `{chat_history}` -- which `format_chat_history` trims to the last 8 messages, i.e. four turns. Question -> hint -> clarify -> attempt is exactly four turn...
lawnhero/isom352
utils/practice.py
.py
f4d88d57190648ff
7
0
"""The router: one model call that picks tools, then the tools run in order. A turn is two model phases with Python in between: student text -> router (tool calling) -> each tool PREPARES a chain payload on its ToolStep and returns a receipt -> app.py streams the prepared chains, one section per too...
lawnhero/isom352
utils/router.py
.py
80060870674def1f
7
0
import streamlit as st from datetime import datetime from utils.course_context import get_course_banner # Recent-message window is an internal tuning knob, not a student control. # Keep in sync with chains_lcel.DEFAULT_MEMORY_WINDOW. DEFAULT_MEMORY_WINDOW = 8 # One switch, not three modes. The old segmented control ...
lawnhero/isom352
utils/sidebar.py
.py
cf5ec04855468416
7
0
import os import certifi import uuid import chromadb from chromadb import Settings from langchain_chroma import Chroma from langchain_openai import OpenAIEmbeddings import streamlit as st from pymongo.mongo_client import MongoClient from pymongo.server_api import ServerApi from datetime import datetime from dotenv impo...
lawnhero/isom352
utils/utils.py
.py
4fa647e0a1a810b3
7
0
from lib.base import BaseApp from lib.mqtt import MQTTSwitch class AllLights(BaseApp): """ Virtual MQTT switch that toggles all (non-bedroom) lights on/off. """ def initialize(self): super().initialize() self.mqtt = self.get_plugin_api("MQTT") self.lights = [] self.sw...
ProjectInitiative/hass
appdaemon/apps/all_lights.py
.py
5a73eabcbb6606b1
7
0
""" AutomationManager — MQTT bridge for HA automations. Exposes Home Assistant automations as controllable MQTT switches. Supports binding to existing entities for two-way sync. Note: The register_automation API is available for other apps to call programmatically. On its own, this app initializes with no entities. "...
ProjectInitiative/hass
appdaemon/apps/automation_manager.py
.py
ecaf8a3607827da7
7
0
from lib.base import BaseApp class DoorBellNotification(BaseApp): """Sends a notification when the front door visitor button is pressed.""" def initialize(self): super().initialize() self.sensor = self.required_arg("sensor") if not self.sensor: return self.last_rin...
ProjectInitiative/hass
appdaemon/apps/doorbell_notification.py
.py
216da62ccb91f011
7
0
from lib.base import BaseApp class GarageAndLightsAutomation(BaseApp): """ Opens garage + lights on arrival (phone home + in car) and closes on departure (phone away + in car). """ def initialize(self): super().initialize() self.users = self.required_arg("users") if not se...
ProjectInitiative/hass
appdaemon/apps/garage_automation.py
.py
12edd45301323ba0
7
0
import appdaemon.plugins.hass.hassapi as hass from copy import deepcopy from lib.notify import deep_merge class GlobalNotify(hass.Hass): """ Central notification router that sends messages to device groups. Backend for lib.notify.Notifier. Apps should use self.notifier (from BaseApp) rather than cal...
ProjectInitiative/hass
appdaemon/apps/global_notify.py
.py
33ad548ab91ca7e5
7
0
""" lib.base — BaseApp, the common base class for all AppDaemon apps. Provides: - Arg helpers: self.arg(name, default) and self.required_arg(name). - Lazy, cached service accessors: self.notifier, self.garage_utils. - Consistent startup logging (call super().initialize() first). All apps should extend Bas...
ProjectInitiative/hass
appdaemon/apps/lib/base.py
.py
277b19b28b66bdf8
7
0
"""Small, clock-injectable double-event detector.""" from __future__ import annotations from time import monotonic from typing import Hashable class DoubleClickDetector: """Detect two matching actions for a key within a configured time window.""" def __init__(self, window: float = 0.75, clock=monotonic): ...
ProjectInitiative/hass
appdaemon/apps/lib/double_click.py
.py
4f684e8eada0720e
7
0
"""Capability and state helpers for linked virtual lights. This module is deliberately independent of AppDaemon so the safety rules for fan-out commands can be unit tested without a Home Assistant installation. """ from __future__ import annotations from typing import Any UNAVAILABLE_STATES = {"unavailable", "unkn...
ProjectInitiative/hass
appdaemon/apps/lib/light_groups.py
.py
3de6eecb1210d0ac
7
0
""" lib.lights — light state restoration helpers. Moved from the legacy utils.py module during the overhaul. Used by meeting_indicator.py to restore lights to their previous state after a meeting indicator toggles them. """ def restore_light_state(app, light_state): """ Restore a light to a previously-saved...
ProjectInitiative/hass
appdaemon/apps/lib/lights.py
.py
049785af60b494b2
7
0
""" lib.mqtt — consolidated MQTT discovery entity helpers. Provides a single MQTTDiscoveryEntity base class and subclasses (MQTTSwitch, MQTTLight, MQTTNumber, MQTTSensor) that standardize how AppDaemon apps expose virtual entities via Home Assistant MQTT Discovery. Previously, MQTT discovery was hand-rolled three dif...
ProjectInitiative/hass
appdaemon/apps/lib/mqtt.py
.py
89a13538cb99ea55
7
0
""" lib.notify — uniform notification wrapper around the global_notify backend. Provides a single entry point (Notifier) that all apps use to send notifications. Normalizes the previously inconsistent calling conventions: - group is always keyword-only - group defaults to the backend's configured default_notif...
ProjectInitiative/hass
appdaemon/apps/lib/notify.py
.py
575dae7983bbfa38
7
0
""" lib.state_manager — desired-state store + anti-thrash reconciler. Designed for outage recovery: when a power flicker makes devices forget their state (brightness, color, on/off), this restores them to their last known *desired* state — not a history log, but the intended state. Key design choices: - In-memory...
ProjectInitiative/hass
appdaemon/apps/lib/state_manager.py
.py
ab8195738d915a06
7
0
"""Pure helpers for linked virtual switch groups.""" from __future__ import annotations import json from typing import Any from lib.light_groups import UNAVAILABLE_STATES def aggregate_switch_state(states: list[dict[str, Any]]) -> str: """Return ON when any available member is on, otherwise OFF.""" return ...
ProjectInitiative/hass
appdaemon/apps/lib/switch_groups.py
.py
e618534e916d828c
7
0
#!/usr/bin/env python3 """ Unit tests for lib/state_manager.py — run without AppDaemon/HASS. cd /home/kylepzak/development/hass python -m pytest appdaemon/apps/lib/test_state_manager.py -v Or without pytest: python appdaemon/apps/lib/test_state_manager.py """ import sys import os import tempfile from dat...
ProjectInitiative/hass
appdaemon/apps/lib/test_state_manager.py
.py
55d4eafdc03ad258
7.5
0
#!/usr/bin/env python3 """ Unit tests for lib/time_utils.py — run without AppDaemon/HASS. cd /home/kylepzak/development/hass python -m pytest appdaemon/apps/lib/test_time_utils.py -v Or without pytest: python appdaemon/apps/lib/test_time_utils.py """ import sys import os from datetime import datetime, ti...
ProjectInitiative/hass
appdaemon/apps/lib/test_time_utils.py
.py
2abaeb8888f059d7
7.5
0
"""Expose configurable groups of HA lights as virtual MQTT lights. This is the entity-level counterpart to ``simple_state_linker``. The linker only mirrors on/off state; this app presents one normal Home Assistant light for a manually configured, area-based, or label-based set of lights and fans commands (brightness/...
ProjectInitiative/hass
appdaemon/apps/linked_lights.py
.py
9d1383d292d1274c
7
0
from enum import Enum from lib.base import BaseApp from lib.lights import restore_light_state class MeetingStatus(Enum): NO_MEETING = 1 OBSERVER_ONLY = 2 VOICE_ONLY = 3 CAMERA_ON = 4 class MeetingIndicator(BaseApp): """ Zigbee button press → light indicator system. Presses on a Zigbee ...
ProjectInitiative/hass
appdaemon/apps/meeting_indicator.py
.py
d2229c1390e4612e
7
0
from typing import Set, Tuple, List from area_handler import APP_NAME as AREA_HANDLER_APP_NAME, EVENT_AREAS_UPDATED from lib.base import BaseApp class SimpleStateLinker(BaseApp): """ Synchronizes the state of entities within defined groups with a grace period to prevent race conditions and command loops....
ProjectInitiative/hass
appdaemon/apps/simple_state_linker.py
.py
d48bd51e413553af
7
0
""" StateManager — outage recovery via desired-state reconciliation. Maintains an in-memory store of the *desired* state (state + attributes like brightness/color) for opted-in entities, and restores them after a power flicker or availability blip. Anti-thrash: caps attempts, cooldowns, and notifies on give-up. Why n...
ProjectInitiative/hass
appdaemon/apps/state_manager.py
.py
dbbb865d2db9eec1
7
0
#!/usr/bin/env python3 """ Quick test script to fetch and display your Republic Services pickup schedule. No external dependencies — uses only Python stdlib (urllib.request, json). Usage: python3 test_rs_schedule.py # uses address from args python3 test_rs_schedule.py "8957 Park Meadows Dr,...
ProjectInitiative/hass
appdaemon/apps/test_rs_schedule.py
.py
fa2ecff206d7292c
7.5
0
from lib.base import BaseApp class TestButtonNotification(BaseApp): """Sends a notification when the test button (Zigbee action sensor) is pressed.""" def initialize(self): super().initialize() self.sensor = self.required_arg("sensor") if not self.sensor: return se...
ProjectInitiative/hass
appdaemon/apps/testbutton_notification.py
.py
37952ae6f71316a2
7.5
0
from datetime import datetime, time, timezone, timedelta from zoneinfo import ZoneInfo import uuid from lib.base import BaseApp class AdvancedTimer(BaseApp): def initialize(self): """Initialize the Advanced Timer app.""" super().initialize() self.timers = {} self.state_listeners ...
ProjectInitiative/hass
appdaemon/apps/timer.py
.py
aea50dc42920b0ac
7
0
#!/usr/bin/env python3 """ Auto-generate AppDaemon app documentation from source code. Run from repo root: python docs/generate_docs.py Or: cd /home/kylepzak/development/hass && python docs/generate_docs.py Reads: - appdaemon/apps/*.py (source code) - appdaemon/apps/apps.yaml (config) Writes: - docs/ind...
ProjectInitiative/hass
docs/generate_docs.py
.py
895ef3b1afdcfadf
7
0
""" Example: Using the Enhanced Stage Control System This example demonstrates how to use the MovementController and EnhancedStageControlView for complete stage control. Run with: python -m examples.stage_control_example """ import logging import sys from pathlib import Path # Add parent directory to path sys.p...
uw-loci/Flamingo_Control
examples/stage_control_example.py
.py
afd197d5e21179c4
7.24
2
import os import shutil from queue import Queue from threading import Event, Thread from PyQt5.QtWidgets import QFileDialog, QMessageBox import py2flamingo.functions.microscope_connect as mc from py2flamingo.utils.file_handlers import text_to_dict, workflow_to_dict from .global_objects import ( command_data_queu...
uw-loci/Flamingo_Control
src/py2flamingo/FlamingoConnect.py
.py
884d625d18cd306b
7.24
2
""" Command-Line Interface - Argument Parsing and Entry Point This module provides the command-line interface for the Flamingo microscope control application. It handles: - Command-line argument parsing - Argument validation - Application initialization with CLI parameters - Error handling for invalid arguments Usage...
uw-loci/Flamingo_Control
src/py2flamingo/cli.py
.py
8ccbd1568e0d44a5
7.24
2
""" Position Controller Adapter for Motion Tracking. This adapter wraps the PositionController to add Qt signal support for motion tracking without modifying the original controller class. It intercepts move commands and emits signals when motion starts/stops, allowing the status indicator service to track stage moti...
uw-loci/Flamingo_Control
src/py2flamingo/controllers/position_controller_adapter.py
.py
773e09f7894d42a6
7.24
2
# controllers/sample_controller.py """ Controller for sample location and management operations. This controller handles all business logic related to finding, tracking, and managing samples within the microscope field of view. """ import logging from threading import Thread from typing import Callable, Optional, Tup...
uw-loci/Flamingo_Control
src/py2flamingo/controllers/sample_controller.py
.py
88a0f6025a93104a
7.24
2
# src/py2flamingo/controllers/settings_controller.py """ Controller for microscope settings management. This controller handles settings-related operations including setting home position and managing configuration. """ import logging import os import time from pathlib import Path from typing import Optional from py...
uw-loci/Flamingo_Control
src/py2flamingo/controllers/settings_controller.py
.py
7d5058ee51854616
7.24
2
# controllers/snapshot_controller.py import logging from ..models.microscope import Position from ..models.workflow import IlluminationSettings, WorkflowModel, WorkflowType from ..services.communication import ConnectionManager from ..services.workflow_service import WorkflowService class SnapshotController: def...
uw-loci/Flamingo_Control
src/py2flamingo/controllers/snapshot_controller.py
.py
05f3e30535004ed2
7.24
2
""" Command Codes for Flamingo Microscope TCP Protocol. This module defines all command codes used to communicate with the Flamingo microscope control system. Commands are organized by subsystem for clarity. Command codes are based on the server-side CommandCodes.h implementation and verified against actual log files...
uw-loci/Flamingo_Control
src/py2flamingo/core/command_codes.py
.py
fd685f8b965a3ea3
7.24
2
""" Error formatting and logging utilities for Flamingo Control. Provides consistent error formatting across the application for both user display and technical logging. """ import json import logging from datetime import datetime from pathlib import Path from typing import Any, Dict, Optional, Union from py2flaming...
uw-loci/Flamingo_Control
src/py2flamingo/core/error_formatting.py
.py
47e9d29fe6f7eace
7.24
2
""" Unified error handling framework for Flamingo Control. This module defines the standard error hierarchy and provides consistent error handling across the application. Error Code Ranges: - 1000-1999: Connection errors - 2000-2999: Command errors - 3000-3999: Hardware errors - 4000-4999: Data/File errors - 5000-599...
uw-loci/Flamingo_Control
src/py2flamingo/core/errors.py
.py
4397e024ca0d6d02
7.24
2
# src/py2flamingo/core/events.py """ Event manager for application-wide events. This module replaces the global event objects with a managed approach. """ import logging from threading import Event from typing import Dict, Optional class EventManager: """ Manages threading events for synchronization. T...
uw-loci/Flamingo_Control
src/py2flamingo/core/events.py
.py
9183244605ffd48a
7.24
2
# src/py2flamingo/core/queue_manager.py """ Queue manager for inter-thread communication. This module replaces the global queue objects with a managed approach. """ import logging from queue import Empty, Queue from typing import Any, Dict, Optional class QueueManager: """ Manages queues for inter-thread co...
uw-loci/Flamingo_Control
src/py2flamingo/core/queue_manager.py
.py
e7143394a95602ce
7.24
2
#!/usr/bin/env python3 # src/py2flamingo/minimal_gui.py """ Minimal GUI for Flamingo microscope control. Allows basic workflow file sending over TCP. """ import logging import sys from pathlib import Path from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import QFont from PyQt5.QtWidgets import ( QApplication,...
uw-loci/Flamingo_Control
src/py2flamingo/minimal_gui.py
.py
d6c4cc5ddf1f3006
7.24
2
# src/py2flamingo/models/acquisition_timing.py """ Data models for acquisition timing and adaptive time estimation. These models track actual acquisition durations vs estimated durations to learn correction factors for more accurate predictions. """ from dataclasses import asdict, dataclass, field from datetime impo...
uw-loci/Flamingo_Control
src/py2flamingo/models/acquisition_timing.py
.py
c8554db833cfd654
7.24
2
"""Base model classes for Flamingo Control domain models. This module provides foundational classes for all domain models in the application, including base functionality for serialization, validation, and metadata tracking. """ import json import uuid from abc import ABC, abstractmethod from dataclasses import asdic...
uw-loci/Flamingo_Control
src/py2flamingo/models/base.py
.py
8999324ecc54b704
7.24
2
#!/usr/bin/env python3 """Validate same-document Markdown anchor links in README and case studies.""" from __future__ import annotations import re from pathlib import Path ROOT = Path(__file__).resolve().parents[1] LINK = re.compile(r"\[[^\]]+\]\(#([^)]+)\)") HTML_ID = re.compile(r"<(?:a|[A-Za-z0-9]+)[^>]+(?:id|name)=...
afadlih/afadlih
scripts/validate_markdown_anchors.py
.py
9cf03f1e8d93b12d
7.15
1
# -*- coding: utf-8 -*- ### Linkaform Modules / Archivo de Módulo ### ''' Este archivo proporciona las funcionalidades modulares de LinkaForm. Con estas funcionalidades, podrás utilizar la plataforma LinkaForm de manera modular, como un Backend as a Service (BaaS). Licencia BSD Copyright (c) 2024 Infosync / LinkaForm...
linkaform/addons
lkf_addons/addons/_template/app.py
.py
db669632c36e6832
7.15
1
# -*- coding: utf-8 -*- ### Linkaform Modules / Archivo de Módulo ### ''' Este archivo proporciona las funcionalidades modulares de LinkaForm. Con estas funcionalidades, podrás utilizar la plataforma LinkaForm de manera modular, como un Backend as a Service (BaaS). Licencia BSD Copyright (c) 2024 Infosync / LinkaFor...
linkaform/addons
lkf_addons/addons/activo_fijo/app.py
.py
3954a21cb9ef7e9c
7.15
1
# -*- coding: utf-8 -*- ### Linkaform Modules / Archivo de Módulo ### ''' Este archivo define el modelo de datos del módulo Accesos. Contiene los IDs de formularios, catálogos y campos (fields) usados por la clase Accesos. Separado de app.py para mantener la configuración de datos desacoplada de la lógica de negocio. ...
linkaform/addons
lkf_addons/addons/base/model.py
.py
e6d29704b2872c53
7.15
1
# -*- coding: utf-8 -*- ### Linkaform Modules / Archivo de Módulo ### ''' Este archivo proporciona las funcionalidades modulares de LinkaForm. Con estas funcionalidades, podrás utilizar la plataforma LinkaForm de manera modular, como un Backend as a Service (BaaS). Licencia BSD Copyright (c) 2024 Infosync / LinkaForm...
linkaform/addons
lkf_addons/addons/contratistas/app.py
.py
0425e595cbef9a28
7.15
1
# -*- coding: utf-8 -*- ### Linkaform Modules / Archivo de Módulo ### ''' Este archivo proporciona las funcionalidades modulares de LinkaForm. Con estas funcionalidades, podrás utilizar la plataforma LinkaForm de manera modular, como un Backend as a Service (BaaS). Licencia BSD Copyright (c) 2024 Infosync / LinkaForm...
linkaform/addons
lkf_addons/addons/custom/app.py
.py
448c00f0b86e9d0f
7.15
1
from __future__ import annotations from collections.abc import Mapping, Sequence from pathlib import Path import polars as pl from ..data_collection.stimulus import Stimulus from ..utils.logging import get_logger from .io import write_answers from .parser import construct_question_id, parse_question_order def _nor...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/answers/collect.py
.py
4d5714794cd5a022
7.3
3
import warnings import polars as pl def parse_answers_from_logfile( logfile: pl.DataFrame, stimuli_trial_mapping: dict[str, str] | None = None ) -> pl.DataFrame: """Parse comprehension question answers from experiment logfile. Parameters ---------- logfile : pl.DataFrame DataFrame from E...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/answers/experiment_log_parser.py
.py
f1683b68a611cd4e
7.3
3
from __future__ import annotations import re from pathlib import Path import polars as pl def parse_question_order(csv_path: Path) -> pl.DataFrame: """Parse the question order CSV for a session. The CSV is expected to have at least the following columns: - question_order_version - local_question_1,...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/answers/parser.py
.py
7eaf11b81f29a190
7.3
3
from dataclasses import asdict, dataclass, field from pathlib import Path from typing import TypeVar import polars as pl from ..config import settings from ..data_collection.stimulus import LabConfig, Stimulus from ..data_collection.trial import Trial from ..models import Sid from ..utils.logging import get_logger l...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/data_collection/session.py
.py
6d685edb3666765f
7.3
3
"""Event detection functions.""" from ..config import settings from ..events.properties import compute_event_properties def detect_fixations( gaze, method: str = "ivt", minimum_duration: int = 100, velocity_threshold: float = 20.0, ) -> None: """ This function applies a fixation detection met...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/events/detect.py
.py
91b94b4eee86072d
7.3
3
"""Functions for loading and processing gaze data from various formats.""" import json import logging import re from pathlib import Path import polars as pl import pymovements as pm import yaml from pymovements import transforms from pymovements.events import Events from ..config import settings from ..data_collecti...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/io/load.py
.py
87a9a0c59c65925d
7.3
3
"""Functions for saving data.""" import contextlib import json import polars as pl import pymovements as pm from ..models.sid import Sid def save_raw_data(sid: Sid, data: pm.Gaze) -> None: """ Saves raw gaze data with calculated position and velocity in separate csv files per trial. Parameters ---...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/io/save.py
.py
f1c69130405be809
7.3
3
import polars as pl from ...config import settings # --------------------------- # Basic fixation-based counts # --------------------------- def compute_total_fixation_count(fix: pl.DataFrame) -> pl.DataFrame: """ Total Fixation Count (TFC): Total number of fixations on the word. """ return ( ...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/metrics/reading/reading_measures.py
.py
4de5864e6d7124de
7.3
3
import re from dataclasses import dataclass, field from pathlib import Path __all__ = ["Sid"] @dataclass class Sid: pid: str = field(init=False) lang: str = field(init=False) country: str = field(init=False) lab: str = field(init=False) session: str = field(init=False) session_id: int = field...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/models/sid.py
.py
606d52c474b9a1a9
7.3
3
import argparse import re import sys from pathlib import Path # Paths to files and the regex to find the version string in each FILES_TO_UPDATE = { "pyproject.toml": (r'(version\s*=\s*")([^"]+)(")', r"\1{version}\3"), "CITATION.cff": (r"(^version:\s*)(.*)", r"\1{version}"), "docs/conf.py": (r'(release\s*=\...
MultiplEYE-COST/multipleye-preprocessing
preprocessing/scripts/sync_version.py
.py
34c746bc970fd081
7.3
3
"""Capture the live software/resource versions of the conversion images. The maxit-ccd and py-wwpdb_utils_nmr images are updated in place to deliver upstream bug fixes, so the footer must reflect the versions currently deployed on the service (not a setup-time snapshot). This flow reads the version env vars baked into...
yokochi47/bmrb-extract
prefect/flows/core/versions.py
.py
28290da6cde1c208
7
0
""" Conversion workspace path scheme, keyed by conversion_id / run_number. Layout (flat by conversion_id), kept separate from the git-managed upload archive so conversions never contaminate it: <base>/<conversion_id>/ cache/ NmrDpUtility cache, SHARED across all runs of this conversion <run_num...
yokochi47/bmrb-extract
prefect/flows/core/workspace.py
.py
2dce99df976be08f
7
0
import discord from discord import app_commands from discord.ext import commands import Brand from Brand import MINT # Display metadata per cog, keyed on the cog class name. Keeping this explicit rather than # deriving it from class names means categories can have proper names and a blurb explaining # what they're fo...
tetooooooooooooooooooooooooooo/danito
src/Cogs/help.py
.py
b9d3df20cc1af02c
7
0
"""One shared cache for the per-guild settings document, and the indexes it relies on. Four cogs read the same document out of `servers`. Each used to keep its own TTL cache of it, so a single message carrying both an attachment and a role mention cost two identical database reads, and every cog had its own invalidati...
tetooooooooooooooooooooooooooo/danito
src/GuildConfig.py
.py
704715b161463cb9
7
0
"""Per-role command permissions: the catalogue of what can be governed, and the one function that decides whether a member may run a command. This is the engine. It touches no Discord objects on purpose, so every rule in it can be tested with plain values. The bot wires it in through the command tree's global check (s...
tetooooooooooooooooooooooooooo/danito
src/Permissions.py
.py
2290cbd1c19a4b04
7
0
"""Shared rules for handing a role to somebody. Autorole and the role buttons need the same answer to one question: can the bot actually give this role out. Getting it wrong produces the most common complaint a role bot gets, which is silence. Discord replies 403 with nothing useful in it, so the reason has to be work...
tetooooooooooooooooooooooooooo/danito
src/RoleTools.py
.py
a3f90e5b9442be75
7
0
"""GuildConfig: shared caching, read-count reduction, invalidation, stale fallback, indexes.""" import pathlib as _pathlib # Resolved from this file so the suite runs from a clone, on any machine, from any cwd. ROOT = _pathlib.Path(__file__).resolve().parents[1] SRC_DIR = str(ROOT / "src") WEB_DIR = str(ROOT / "web") i...
tetooooooooooooooooooooooooooo/danito
tests/test_config.py
.py
692f00fd6c7fa45d
7.5
0