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 |
|---|---|---|---|---|---|---|
"""RushTI DAG domain model.
This module defines the Directed Acyclic Graph used for task execution
scheduling and its supporting types:
- CircularDependencyError: Raised when cycle detection finds a loop
- TaskStatus: Enum tracking per-task execution state
- DAG: The core execution graph with dependency-aware scheduli... | cubewise-code/rushti | src/rushti/dag.py | .py | b2fbc34b365f9e2d | 7.56 | 12 |
"""Exclusive mode module for RushTI.
This module provides exclusive execution mode functionality to ensure
only one RushTI instance runs at a time across all clients in shared
TM1 environments.
Session identification uses TM1 session context fields:
- Normal mode: RushTI{workflow}
- Exclusive mode: RushTIX{workflow}
... | cubewise-code/rushti | src/rushti/exclusive.py | .py | 7066048f73c7d45a | 7.56 | 12 |
"""Execution logging module for RushTI.
This module provides structured logging for task execution results
using Python's standard logging framework.
"""
import json
import logging
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field
from datetime import datetime
from typing import Any... | cubewise-code/rushti | src/rushti/logging.py | .py | 3962c7750af51fca | 7.56 | 12 |
"""Logging configuration helpers for the RushTI CLI.
Owns the pre-processing of the logging config file (resolving relative
file-handler paths against the application directory so log files don't
get written into ``C:\\windows\\system32`` when invoked from TM1's
``ExecuteCommand``), the ``--log-level`` argparse helper... | cubewise-code/rushti | src/rushti/logging_setup.py | .py | 6e5b2bb86911b275 | 7.56 | 12 |
"""Task runtime optimization module for RushTI.
Provides runtime estimation and task ordering for optimized parallel execution.
Uses EWMA (Exponentially Weighted Moving Average) based on historical execution data.
Supported scheduling algorithms:
- ``longest_first``: Sort ready tasks by estimated runtime descending (... | cubewise-code/rushti | src/rushti/optimizer.py | .py | 835cae499c572658 | 7.56 | 12 |
"""Settings module for RushTI configuration.
This module provides configuration management through settings.ini file,
separate from TM1 connection settings in config.ini.
Settings precedence (highest to lowest):
1. CLI arguments
2. JSON task file settings section
3. settings.ini file
4. Built-in defaults
"""
import ... | cubewise-code/rushti | src/rushti/settings.py | .py | 4053401653714cb5 | 7.56 | 12 |
"""Stats backend defaults and path/backend resolution."""
from rushti.utils import resolve_app_path
# Default database location relative to application directory
DEFAULT_DB_PATH = resolve_app_path("data/rushti_stats.db")
# Default retention period in days
DEFAULT_RETENTION_DAYS = 90
# Default storage backend
DEFAUL... | cubewise-code/rushti | src/rushti/stats/paths.py | .py | 25de15b80cf6afed | 7.56 | 12 |
"""StatsRepository Protocol and ``create_stats_database`` factory.
This module defines the structural typing seam between the two storage
backends — ``rushti.stats.sqlite.StatsDatabase`` and
``rushti.stats.dynamodb.DynamoDBStatsDatabase`` — so callers depend on
the abstract surface (``StatsRepository``) rather than a ... | cubewise-code/rushti | src/rushti/stats/repository.py | .py | cf0b748890f8dcc4 | 7.56 | 12 |
"""RushTI task domain model.
This module defines the core task representations used throughout the
execution pipeline:
- Wait: Marker for norm-mode sequence boundaries
- Task: Base task for norm-mode execution
- OptimizedTask: Extended task with explicit predecessors for opt-mode
- ExecutionMode: Enum for execution mo... | cubewise-code/rushti | src/rushti/task.py | .py | f70e2cae99d4e8e8 | 7.56 | 12 |
import PIL
from PIL import ImageFont, Image, ImageDraw, ImageFilter, ImageEnhance
import requests
import time
import random
########### FONTS ###########
NOT_LOAD_FONT = ImageFont.truetype("Fonts/Poppins-ExtraBold.ttf", 64)
RANK_FONT = ImageFont.truetype("Fonts/Tharon.ttf", 128)
SCORE_FONT = ImageFont.truetype("Fonts/... | AeroAstroid/TheBrainOfTWOWCentral | Config/_asgen_functions.py | .py | 5ef394910160732c | 7.45 | 7 |
import argparse
import importlib.metadata
import os
import sys
from pathlib import Path
from typing import Dict
# Define available commands and their descriptions
# Use a dictionary for easier management and help text generation
COMMANDS = {
"add": "Add a new task.",
"show": "Show tasks (default command). Filt... | mkaz/tasks | tasks/config.py | .py | 73291dcabe995ba6 | 7.56 | 12 |
"""
Task
A simple command-line task list.
"""
import sqlite3
import webbrowser
from pathlib import Path
# local
from . import reports
from .config import init_args
from .editor import edit_task
from .db import TaskDb
from .task import Task
def get_task_or_error(db: TaskDb, args: dict) -> Task | None:
"""Validat... | mkaz/tasks | tasks/main.py | .py | 4113914494d17ecc | 7.56 | 12 |
import pytest
import sqlite3
from pathlib import Path
import tempfile
import os
from tasks.db import TaskDb
@pytest.fixture
def temp_db():
"""Create a temporary database for testing."""
# Create a temporary file that will be used as the SQLite DB
with tempfile.NamedTemporaryFile() as tf:
path = tf... | mkaz/tasks | tests/conftest.py | .py | 6a749194e635408e | 8.06 | 12 |
import pytest
import sys
from io import StringIO
from unittest.mock import patch
import sqlite3
from tasks.main import main
@pytest.fixture
def capture_output():
"""Fixture to capture stdout/stderr"""
output = StringIO()
with patch("sys.stdout", output):
yield output
def test_add_task(mock_env_... | mkaz/tasks | tests/test_cli.py | .py | fc81705dd771d2f1 | 7.06 | 12 |
import sqlite3
import pytest
from tasks.db import TaskDb
def test_create_schema(temp_db):
"""Test creating the schema."""
# Schema should already be created by the fixture
conn = sqlite3.connect(temp_db)
conn.row_factory = sqlite3.Row
# Check if the table exists
cur = conn.cursor()
cur.exe... | mkaz/tasks | tests/test_db.py | .py | e3fe9898ba9fb30a | 7.06 | 12 |
import pytest
from tasks.task import Task
from tasks.db import TaskDb
def test_task_create(connection):
"""Test creating a new task."""
db = TaskDb(connection)
# Test with just task text
entry = {"task_entry": "Test create task"}
task_id = db.create_task(entry)
assert task_id is not None
... | mkaz/tasks | tests/test_task.py | .py | ea51da2d98c230c5 | 8.06 | 12 |
from collections import defaultdict
from datetime import datetime
import os
import re
from urllib.parse import urlsplit, urlunsplit, parse_qs, urlencode
import requests
from lxml import html as etree
UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Saf... | okfde/bundesrat-scraper | bundesrat/bundesrat.py | .py | 081e954586ee1b11 | 7.54 | 11 |
import re
import pdb
from lxml import html as etree
import requests
from lxml import html as etree
import pdfcutter
# Import relative Parent Directory for Helper Classes
import os, sys
sys.path.insert(0, os.path.abspath('..')) #Used when call is ` python3 file.py`
sys.path.insert(0, os.path.abspath('.')) #Used when ... | okfde/bundesrat-scraper | hamburg/scraper_hamburg.py | .py | 06913eee79d04821 | 7.54 | 11 |
import itertools
from urllib.parse import urlsplit
import os
import requests
from pdfcutter import utils
from lxml import html as etree
import urllib3
# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
#Escape . and ) in TOPs for regex
#Cant use re.escape because it escapes spa... | okfde/bundesrat-scraper | helper.py | .py | cfc8edf75151f966 | 7.54 | 11 |
import json
import re
import os
import sys
import requests
from lxml import html as etree
from datetime import datetime
import subprocess
# Import relative Parent Directory for Helper Classes
sys.path.insert(0, os.path.abspath('..')) #Used when call is ` python3 file.py`
sys.path.insert(0, os.path.abspath('.')) #Used ... | okfde/bundesrat-scraper | sachsen/scraper_sachsen.py | .py | eb139d1005e30670 | 7.54 | 11 |
"""Email-related code and templates."""
from .scriptures import scripture_mapping
def get_lesson_info(scripture_name: str):
"""Get lesson information based on scripture name.
Args:
scripture_name: The scripture name (e.g., "Luke", "John", "Ephesians", "James")
Returns:
dict: Dictionary ... | cbcgb-com/sgbs-training | sgbs_training/email.py | .py | c853dc6a60b0d511 | 7.52 | 10 |
import pandas as pd
import streamlit as st
import plotly.express as px
# ---------------------------- Helpers ----------------------------
def prepare_mortality(df):
df = df.copy()
df["age"] = df["age"].astype(int)
for c in df.columns:
if str(c).isdigit():
df[c] = pd.to_numeric(df[c], e... | rcsmit/streamlit_scripts | aantal_vrijkomende_woningen.py | .py | 2160186b672ee5cf | 7.42 | 6 |
"""
market_data.py — Shared data layer voor Should I Be Trading?
Importeer dit in zowel app.py als backtest.py.
"""
import pandas as pd
import numpy as np
import time
import warnings
warnings.filterwarnings("ignore")
from scoring import SECTORS, compute_scores
# ── Live data (voor app.py — huidige dag) ────────────... | rcsmit/streamlit_scripts | bloomberg_dashboard/market_data.py | .py | c23f94460bc76778 | 7.42 | 6 |
import random
import plotly.express as px
import pandas as pd
import streamlit as st
import numpy as np
from scipy.stats import binom
# House class to represent each house
class House:
def __init__(self, house_id):
self.house_id = house_id
self.clean_count = 0
def clean(self):
self... | rcsmit/streamlit_scripts | cleaning_simulation.py | .py | 00ba02a165ae3c9b | 7.42 | 6 |
import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
# nieuwe versie lonen_inflatie.py
def get_df():
"""Get the DF with the possibilities.
Loading from Google Sheets gives the 2 first rows as column header.
Returns:
df: the dataframe with th... | rcsmit/streamlit_scripts | cpi_loon.py | .py | 0c3faa6ee5194aaf | 7.42 | 6 |
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import streamlit as st
import datetime as dt
# from scipy import stats
# import datetime as dt
from utils import get_data_yfinance
def calculate_assets(df, choice, transactions):
"""Calculate the worth of the portfolio
... | rcsmit/streamlit_scripts | crypto_portfolio.py | .py | 378c130876a11bee | 7.42 | 6 |
import polars as pl
import streamlit as st
import pandas as pd
import pydeck as pdk
import numpy as np
import polars as pl
try:
st.set_page_config(
page_title="EasyMap",
layout="wide"
)
except:
pass
def generate_data():
"""
group the cities and take the average of the lat and lon
... | rcsmit/streamlit_scripts | easy_map_nl.py | .py | d13d25617c8c4ec8 | 7.42 | 6 |
import streamlit as st
import pymupdf # pymupdf
import io
import requests
import pandas as pd
pdf_parking_url_1 = "https://github.com/rcsmit/streamlit_scripts/raw/refs/heads/main/input/template_parking_1.pdf"
pdf_parking_url_2 = "https://github.com/rcsmit/streamlit_scripts/raw/refs/heads/main/input/template_parking_... | rcsmit/streamlit_scripts | ecg_doorsigns.py | .py | 47919b5d16345b93 | 7.42 | 6 |
import json
import io
import re
from collections import defaultdict
from urllib.parse import quote
from html import unescape
import requests
import streamlit as st
# -------------------- PAGE ----------------------
try:
st.set_page_config(page_title="SVG + JSON Merger", layout="wide")
except:
pass
st.title("... | rcsmit/streamlit_scripts | generate_monopoly.py | .py | 05c3026834e665d6 | 7.42 | 6 |
from collections import OrderedDict
from datetime import datetime
import os
from tabulate import tabulate
import yaml
from . import constants
from .cost_explorer_client import CostExplorerClient
from .date_util import DateUtil
from .logger import get_logger
class CostExplorer:
"""
convert responce data clas... | toyama0919/awscost | src/awscost/cost_explorer.py | .py | cc17ab330c71b6d1 | 7.57 | 13 |
from boto3.session import Session
from .logger import get_logger
class CostExplorerClient:
def __init__(
self,
granularity,
start,
end,
filter=None,
metrics=None,
aws_profile=None,
debug=False,
client=None,
):
self.granularity = ... | toyama0919/awscost | src/awscost/cost_explorer_client.py | .py | 09e47b6cd655e5b0 | 7.57 | 13 |
from datetime import datetime, timedelta
class DateUtil:
@staticmethod
def get_start(granularity, point, today=None):
"""
Automatic adjustment of datapoint scale by month, day
``today`` can be injected for deterministic testing. Defaults to
``datetime.today()`` when omitted.
... | toyama0919/awscost | src/awscost/date_util.py | .py | 7651aeb3764200db | 7.57 | 13 |
#!/usr/bin/python3
"""Persistent log of noticed public-IP changes, capped by entry count."""
import os
from datetime import datetime
HISTORY_DIR = os.path.join(os.environ['HOME'], '.local', 'share', 'locindicator')
HISTORY_FILE = os.path.join(HISTORY_DIR, 'ip-history.log')
MAX_ENTRIES = 100
def _read_lines():
if... | icamys/locindicator | iphistory.py | .py | 56f06d66bb3f1cd6 | 7.64 | 18 |
#!/usr/bin/python3
"""Tray indicator process for locindicator.
Polls get-location.sh every 15 seconds, updates the tray icon/label with the
current flag/country/IP, and logs IP changes to iphistory so the most recent
ones can be browsed inline in the tray dropdown, newest (current) first.
"""
import logging
import os
... | icamys/locindicator | locindicator.py | .py | 3aa537a6c8a7f35c | 7.64 | 18 |
import numpy as np
from pyrle import Rle
from pyrle.src.coverage import _remove_dupes
def test_defragment_keeps_a_single_run_value():
"""A result that collapses to one run must keep its value.
`_remove_dupes` returned the typed memoryviews it was handed on its
single-element path, while every other path... | pyranges/pyrle | tests/test_defragment.py | .py | 1b9ee5b27f244978 | 8.15 | 19 |
import sys
import yaml
import pkgutil
import requests
import logging
import re
import httpx
import json
from datetime import date
import cdblib
def percent_list(part_list, whole_list):
"""return percent of the part"""
w = len(whole_list)
if not w:
return (w,0)
p = 100 * float(len(part_list))/f... | dmachard/python-blocklist-aggregator | blocklist_aggregator/aggregator.py | .py | efd65cd9477ae812 | 7.6 | 15 |
import unittest
import warnings
import blocklist_aggregator
class TestFetching(unittest.TestCase):
def setUp(self):
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
def test1_fetch(self):
"""test fetch"""
domains = blocklist_aggregator.fetch()
se... | dmachard/python-blocklist-aggregator | tests/test_fetch.py | .py | 13bdc8b393d24e11 | 8.1 | 15 |
import unittest
import cdblib
import blocklist_aggregator
class TestSaving(unittest.TestCase):
def test1_save_raw(self):
"""test save list of domains as raw format"""
fn = "./outputs/blocklist_raw.txt"
blocklist_aggregator.save_raw(filename=fn)
with open(fn, "r") as f:
... | dmachard/python-blocklist-aggregator | tests/test_save.py | .py | 98e6e41cf9a04388 | 8.1 | 15 |
import os
import random
import warnings
from types import ModuleType
from typing import Dict, List, Optional, TypedDict, Union
class _WordList(TypedDict):
path: str
n: int
list: List[str]
def _load_words(txt_file: str) -> List[str]:
"""Load all words from the text file.
Args:
txt_file: ... | the-lay/py-friendly-words | friendlywords/friendlywords.py | .py | 3780056b9934a464 | 7.56 | 12 |
#Copyright Thomas TEMPE, 2020
from supervisor import ticks_ms
from board_po import backlight, backlight_map
N_PIXELS = len(backlight_map)
_BLUE = (0, 0, 255)
_OFF = (0, 0, 0)
HINT_DELAY_MS = 2000
LH_PERIOD_MS = 3000
LH_PEAK_HALF_MS = 400
NOTE_CYCLE_MS = 5000
NOTE_GROUP_PEAK_MS = 1250
NOTE_ENVELOPE_HALF_MS = 450
# K... | ttempe/Pocket_Organ | CircuitPy/backlight.py | .py | 6d75dcd0f5fb6f11 | 7.56 | 12 |
import board_po as board
import mux
from supervisor import ticks_ms
# TODO:
# - Calibrate for effect of load on displayed level
# Resting OCV lookup for single-cell Li-ion: (voltage V, true SOC %), ascending voltage
_OCV = [(3.00, 0), (3.50, 10), (3.65, 20), (3.75, 40), (3.82, 60), (3.95, 80), (4.20, 100), (10000, 10... | ttempe/Pocket_Organ | CircuitPy/battery.py | .py | ce312dbab98df1e3 | 7.56 | 12 |
# Holtek BS8112A-3 capacitive touch (12 keys).
import time
_REG_KEYSTATUS0 = 0x08
_REG_SETTINGS = 0xB0
_KEY_MASK = 0x0FFF # Key1..Key12
# Option2 @ 0xB4: bit7=1, bit6=LSC (0=faster general, 1=more power-saving)
_OPTION2_LSC_OFF = 0x98
# Kn_TH bits5:0: valid 8..63. Higher = less sensitive (better for direct skin co... | ttempe/Pocket_Organ | CircuitPy/bs8112a.py | .py | 396cbf879058c314 | 7.56 | 12 |
import displayio, busio
import adafruit_displayio_ssd1306
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
from adafruit_display_shapes.rect import Rect
from supervisor import ticks_ms
import board_po as board
from version import version
WHITE = 0xFFFFFF
BLACK = 0x000000
#Screen s... | ttempe/Pocket_Organ | CircuitPy/display.py | .py | 975cfba469b7d581 | 7.56 | 12 |
import time, array
import board_po as board
import mux
import bs8112a
import micropython
#TODO:
# * Measure in low/high temperature environment, determine need to re-calibrate
chord = micropython.const(0)
melody = micropython.const(1)
drum = micropython.const(2)
expr_bend_up = micropython.const(13)
# Melody pitc... | ttempe/Pocket_Organ | CircuitPy/keyboard.py | .py | 36f8cf88d6ea66c1 | 7.56 | 12 |
# Hobbyist Steno Keyboard - MicroPython driver for a hobbyist steno machine (keyboard)
# Copyright (C) 2023 Thomas TEMPE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ei... | ttempe/Pocket_Organ | CircuitPy/keys.py | .py | a55d32393b511850 | 7.56 | 12 |
import board_po as board
from adafruit_midi.note_off import NoteOff
from adafruit_midi.note_on import NoteOn
from adafruit_midi.control_change import ControlChange
from adafruit_midi.midi_message import MIDIUnknownEvent
from adafruit_midi.pitch_bend import PitchBend
import time
#TODO: remove allocation of new buffer ... | ttempe/Pocket_Organ | CircuitPy/midi.py | .py | 2d55318a7168b66b | 7.56 | 12 |
#This module drives the 14 analog keys with Hall effect sensors.
#The keys are multiplexed (address is set through mux_A, _B, and _C)
#and readings are collected through two ADCs.
#
# Key order is:
# 0~7: the note keys (C, D, E.. CC)
# 8~13: the left-hand keys (left to right, top to bottom)
#
# The magnets must be inst... | ttempe/Pocket_Organ | CircuitPy/misc/hall_sensor_keyb.py | .py | b936fe720cfc7dea | 7.56 | 12 |
# Hobbyist Steno Keyboard - MicroPython driver for a hobbyist steno machine (keyboard)
# Copyright (C) 2023 Thomas TEMPE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ei... | ttempe/Pocket_Organ | CircuitPy/misc/keys.py | .py | 9f617989f8be6fd0 | 7.56 | 12 |
"""Loop-section timers: avg and peak (active only when board.verbose)."""
import board_po as board
import gc
from time import monotonic_ns
# name -> [sum_us, count, peak_us]
total = {}
counts = {}
peaks = {}
last_timestamp = 0
last_disp = 0
def stamp(name = None):
if board.verbose:
global last_timestamp, ... | ttempe/Pocket_Organ | CircuitPy/profiler.py | .py | f7095ede5944d1f0 | 7.56 | 12 |
"""Flash wrtite speed test.
https://chatgpt.com/share/6816e05e-e72c-8005-a364-95f27606465d
Assumption:
* Flash read and write operations are blocking on CircuitPython on RP2040. There is no preemption.
* Writes add an acceptable amount of delay (<2ms) if no bit changes from 0 to 1
* if a bit changes from 0 1, that tr... | ttempe/Pocket_Organ | CircuitPy/test_speed.py | .py | eea2d483a8afd73d | 8.06 | 12 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os
import re
import sys
package = 'rich_text_renderer'
requirements = [
]
test_requirements = [
]
def get_version(package):
"""
Return package version as list... | contentful/rich-text-renderer.py | setup.py | .py | 89e816c7b0f49a75 | 7.48 | 8 |
import math
from math import log, pi
import numba as nb
import numpy as np
from numpy.typing import NDArray
from ._cube_lattice import cube_lattice
@nb.jit(
nb.float64(nb.float64, nb.int64),
fastmath=True,
error_model="numpy",
cache=True,
nogil=True,
)
def int_sin_m(x: float, m: int) -> float: ... | hafaio/fibonacci_lattice | fiblat/_sphere_lattice.py | .py | 7b7f805b8b3e24da | 7.5 | 9 |
"""Test cube lattice."""
import numpy as np
import pytest
from pytest_benchmark.fixture import BenchmarkFixture
from fiblat import cube_lattice
def test_one_dim() -> None:
"""Test cube with single dimension (line)."""
one = cube_lattice(1, 4)
assert np.allclose(one, np.arange(4)[:, None] / 4)
def test... | hafaio/fibonacci_lattice | tests/test_cube.py | .py | 3c7e9f63ff84481d | 8 | 9 |
"""Test sphere lattice."""
import numpy as np
import pytest
from pytest_benchmark.fixture import BenchmarkFixture
from fiblat import sphere_lattice
from fiblat._sphere_lattice import inv_int_sin_m, inv_int_sin_ms
def test_on_unit_sphere(benchmark: BenchmarkFixture) -> None:
"""Test points are on the unit sphere... | hafaio/fibonacci_lattice | tests/test_sphere.py | .py | a62e2b820b762e55 | 8 | 9 |
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow import keras
from sklearn.metrics import mean_squared_error
import math
def get_data(df, feature_window, forecast_horizon=1):
"""
inputs:
df, a pandas dataframe containing features and target
... | AnthonyBurre/Surf-Height-Prediction | legacy/wave_rnn.py | .py | d14b5012ea7c79f2 | 7.45 | 7 |
"""How much of the model-selection table is signal vs test-window luck?
This project scores everything on one fixed test window (2023-01-01 →
2024-12-31), so a 1 cm RMSE gap between two models might just be which storms
happened to land after the cutoff. There is no cross-validation here to average
that out (an earlie... | AnthonyBurre/Surf-Height-Prediction | notebooks/test_window_noise.py | .py | ae2e509e8c3d3d5a | 7.95 | 7 |
"""Does Mooloolaba tide phase modulate hsig_m residuals?
Pulls 2023-2024 tide gauge readings (10-min, CKAN Datastore) at the buoy
location, aligns them to the 30-min wave grid, and asks whether residuals
from a persistence forecast at h=12h show structure vs the tide. Informed
project roadmap and now leaving tide out... | AnthonyBurre/Surf-Height-Prediction | notebooks/tide_residual_check.py | .py | 1c06b4fb559376d1 | 7.45 | 7 |
"""Baseline forecasters. sklearn-style fit/predict so they drop into the same harness as regressors.
Why these matter: an ML model is only useful if it beats the dumbest
thing that also knows the autocorrelation structure of the series.
Persistence is that thing for any process with strong short-horizon
autocorrelatio... | AnthonyBurre/Surf-Height-Prediction | src/forecast/baselines.py | .py | e7db20091a8245ee | 7.45 | 7 |
"""Feature engineering building blocks for wave-height forecasting.
All functions are pure — they take a DataFrame and return a new one —
so they compose in any order without surprising side effects.
Leakage rule: these helpers only look at times ``<= t`` for the row
indexed at ``t``. Pair with ``data.make_target`` (... | AnthonyBurre/Surf-Height-Prediction | src/forecast/features.py | .py | a0df99af9bc8d6c5 | 7.45 | 7 |
"""Sequence-model forecasters in PyTorch: RNN, GRU, LSTM, and a TCN.
All four share the same windowing / scaling / training harness
(``_TorchSeqForecaster``); only the encoder architecture differs.
The models window their own input: for a row at time *t* they consume
the previous ``seq_len`` feature vectors ending at... | AnthonyBurre/Surf-Height-Prediction | src/forecast/neural.py | .py | 092c20557c83f18f | 7.45 | 7 |
"""Shared CKAN Datastore client for the QLD government open-data portal.
Two source families ride on top of the same retrying session / paginated GET /
404-skip loop:
- ``qld_ckan.wave`` — wave-buoy network (Mooloolaba, Brisbane, …).
- ``qld_ckan.wind`` — air-quality / met stations carrying 10 m wind.
Each sub-pac... | AnthonyBurre/Surf-Height-Prediction | src/qld_ckan/__init__.py | .py | 982e496323124eda | 7.45 | 7 |
import pandas as pd
import qld_ckan
from .constants import RESOURCE_IDS
# Re-exported so ``patch("qld_ckan.wave.downloader._session")``-style tests can
# replace the session for this sub-package without affecting the wind side.
_session = qld_ckan.session
_DATASTORE_BATCH = qld_ckan.DATASTORE_BATCH
def _normalize_... | AnthonyBurre/Surf-Height-Prediction | src/qld_ckan/wave/downloader.py | .py | 746a490549cfa2ff | 7.45 | 7 |
import logging
from pathlib import Path
import numpy as np
import pandas as pd
from .. import filter_resource_years, unify_frames
from .constants import BUOYS, COLUMN_RENAME_MAP, RESOURCE_IDS, SENTINEL_VALUE
from .downloader import fetch_all
logger = logging.getLogger(__name__)
_DATA_DIR = Path(__file__).parents[3]... | AnthonyBurre/Surf-Height-Prediction | src/qld_ckan/wave/pipeline.py | .py | 866297bee6595f35 | 7.45 | 7 |
import pandas as pd
import qld_ckan
from .constants import RESOURCE_IDS
# Re-exported so ``patch("qld_ckan.wind.downloader._session")``-style tests can
# replace the session for this sub-package without affecting the wave side.
_session = qld_ckan.session
_DATASTORE_BATCH = qld_ckan.DATASTORE_BATCH
# Pre-2015 colu... | AnthonyBurre/Surf-Height-Prediction | src/qld_ckan/wind/downloader.py | .py | 746c1ed77780f69f | 7.45 | 7 |
import logging
from pathlib import Path
import pandas as pd
from .. import filter_resource_years, unify_frames
from .constants import COLUMN_RENAME_MAP, RESOURCE_IDS, STATIONS
from .downloader import fetch_all
logger = logging.getLogger(__name__)
_DATA_DIR = Path(__file__).parents[3] / "data"
# Source timestamps a... | AnthonyBurre/Surf-Height-Prediction | src/qld_ckan/wind/pipeline.py | .py | 0bba95c3918609b9 | 7.45 | 7 |
"""``features.build_design`` — the canonical design-matrix builder.
These tests pin ``build_design`` to the exact hand-rolled chain the notebooks
used to duplicate, so the rewrite to a single core builder is provably
behaviour-preserving, and lock the one reconciled divergence (engineered drops
raw ``*_deg`` wind bear... | AnthonyBurre/Surf-Height-Prediction | src/tests/test_build_design.py | .py | 1e018526a9fb53d0 | 7.95 | 7 |
"""Tests for residual-mode training in the sequence forecasters."""
import numpy as np
import pytest
from forecast.neural import GRUForecaster
def _finite_mask(X, y):
return ~(X.isna().any(axis=1) | y.isna())
class TestResidualMode:
def test_constant_residual_raises(self, synthetic_df):
"""residual... | AnthonyBurre/Surf-Height-Prediction | src/tests/test_neural_residual.py | .py | 3eb8a00a7b091834 | 7.95 | 7 |
"""Post-download exploratory plots.
Charts that only make sense *before* a forecasting model exists — used to
screen candidate features and decide which neighbour sources are worth
pulling in:
1. ``feature_horizon_heatmap`` — *within one source*: how each channel
correlates with a target at a range of forecast ho... | AnthonyBurre/Surf-Height-Prediction | src/viz/eda.py | .py | 0afe1cb9811a77d6 | 7.45 | 7 |
"""Time-series plots — shared primitives for any time-indexed series.
These functions are deliberately context-free: they work equally well on
a raw downloaded channel (post-download EDA) and on a model's prediction
or residual series (post-modeling diagnostics). Single-source and multi-
source overlays share the same... | AnthonyBurre/Surf-Height-Prediction | src/viz/timeseries.py | .py | f5235b8628bac69c | 7.45 | 7 |
import requests
import pandas as pd
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from cad_tickers.exchanges.tsx.get_ticker_data import get_ticker_data
# since tsx lacks documentation
# unlikely that I can figure out what the other endpoints do
tsx_json_url = "https://www.tsx.com/json... | FriendlyUser/cad_tickers | cad_tickers/exchanges/tsx/get_tickers.py | .py | 9b19125a3ec56060 | 7.42 | 6 |
import requests
import time
from cad_tickers.news.ceo import SearchParams, ceo_url, \
news_link_from_spiel, \
params_to_dict
from cad_tickers.news.ceo.utils import art_pixel_height, earlier_timestamp, module_logger
from typing import Tuple, List
from dataclasses import replace
# get spiels from
def get_spiels... | FriendlyUser/cad_tickers | cad_tickers/news/ceo/main.py | .py | 436830ea476156d2 | 7.42 | 6 |
import requests
import bs4
from bs4 import BeautifulSoup
from cad_tickers.news.ceo.utils import module_logger
def extract_article(article_url: str)-> bs4.element.Tag:
"""Extracts data from given ceo news url"""
r = requests.get(article_url)
if r == None:
module_logger.warning('No data returned f... | FriendlyUser/cad_tickers | cad_tickers/news/ceo/scrap.py | .py | e6b53d79ef9ba00c | 7.42 | 6 |
import re
import datetime
import logging
from dataclasses import asdict
from typing import Type, Union
from cad_tickers.news.ceo import SearchParams
# create logger
module_logger = logging.getLogger(__name__)
ceo_url = "https://ceo.ca"
art_pixel_height = 96
def params_to_dict(sp: Type[SearchParams]) -> dict:
"""... | FriendlyUser/cad_tickers | cad_tickers/news/ceo/utils.py | .py | fa5f0c5d5720ab4e | 7.42 | 6 |
import requests
import bs4
import pandas as pd
from typing import List, Union, Tuple
from concurrent.futures import ThreadPoolExecutor
def scrap_news_for_ticker(ticker: str) -> List[dict]:
"""Extracts webpage data from a ticker
TODO add a delay
Parameters:
ticker - yahoo finance ticker
Returns... | FriendlyUser/cad_tickers | cad_tickers/news/stock_news.py | .py | 006ffd3778163808 | 7.42 | 6 |
import requests
from cad_tickers.exchanges.classes import CSESedarFilings, CSETicker
from typing import Union
from cad_tickers.util import make_cse_path
def get_cse_ticker_data(ticker, get_dict: bool = True) -> Union[CSETicker, dict]:
"""
Parameters:
ticker - stock ticker for the cse without exchange ... | FriendlyUser/cad_tickers | cad_tickers/sedar/cse.py | .py | f6f2da08505eeeee | 7.42 | 6 |
import requests
import json
from cad_tickers.util.utils import get_random_agent
from datetime import datetime
from cad_tickers.exchanges.tsx.gql_data import GQL
from typing import Union
def get_ticker_filings(
symbol: str,
fromDate: str = datetime.today().replace(day=1).strftime("%Y-%m-%d"),
toDate: str =... | FriendlyUser/cad_tickers | cad_tickers/sedar/tsx.py | .py | 7b7d2aa8d3ec318e | 7.42 | 6 |
import pandas as pd
import bs4
from typing import List
from random_user_agent.user_agent import UserAgent
def transform_name_to_slug(raw_ticker: str) -> str:
"""
Parameters:
raw_ticker - cse ticker to be converted to slug
Returns:
transformed - raw_ticker
"""
transformed = raw_ticker.l... | FriendlyUser/cad_tickers | cad_tickers/util/utils.py | .py | 7e175b40d7f58e90 | 7.42 | 6 |
import requests
import re
import os
def getFilename_fromCd(cd):
"""
Get filename from content-disposition
"""
if not cd:
return None
fname = re.findall("filename=(.+)", cd)
if len(fname) == 0:
return None
return fname[0]
list_of_stocks_files = [101, 102, 106, 110, 114, 11... | FriendlyUser/cad_tickers | scripts/download_xlsx.py | .py | bab1586f36dfa098 | 7.42 | 6 |
from cad_tickers.news.iiroc_halts import get_halts_resumption
from cad_tickers.news.stock_news import (
scrap_news_for_ticker,
find_news_source,
find_news_link_and_text,
)
import os
import bs4
def test_get_halts_resumption():
halts_df = get_halts_resumption()
assert len(halts_df) > 20
def test_st... | FriendlyUser/cad_tickers | tests/news/test_news.py | .py | ae53cfcc9d659196 | 7.92 | 6 |
import glob
import itertools
import logging
import os
import shutil
from datetime import datetime
import dateutil.parser as parser
from dateutil.relativedelta import relativedelta
from doc_curation import blog
from doc_curation.blog import scrape_index_from_anchors
from doc_curation.md import library
import regex
fo... | sanskrit-coders/doc_curation | doc_curation/blog/wordpress.py | .py | 412fcffef31b2d06 | 7.48 | 8 |
import json
import logging
# Remove all handlers associated with the root logger object.
import toml
import os
import json
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)s:%(asctime)s:%(module)s:%(lineno)d %(message)s")... | sanskrit-coders/doc_curation | doc_curation/book_data.py | .py | 037a0ef7d5a6aae1 | 7.48 | 8 |
import logging
import os
from typing import Any
from indic_transliteration import sanscript
import regex
from doc_curation.ebook import calibre_helper
from doc_curation.ebook.pandoc_helper import pandoc_from_md_file
from doc_curation.md.file import MdFile
def epub_from_md_file(md_path, epub_path, css_path=None, met... | sanskrit-coders/doc_curation | doc_curation/ebook/epub.py | .py | db1ad97b53fd3cd9 | 7.48 | 8 |
import logging
import os
from shutil import copyfile
from indic_transliteration import sanscript
import regex
from doc_curation.md import content_processor
from doc_curation.md.content_processor import footnote_helper, details_helper, embed_helper
from doc_curation.md.file import MdFile
from doc_curation.md.library.com... | sanskrit-coders/doc_curation | doc_curation/ebook/md_book.py | .py | 16caae36117128af | 7.48 | 8 |
import io
import logging
import os
import os.path
import regex
from pypdf import PdfReader, PdfWriter
import io
from fpdf import FPDF
from pypdf import PdfReader
from doc_curation.md.file import MdFile
SKT_FONT = '/home/vvasuki/gitland/indic-transliteration/sanskrit-fonts/fonts/ttf-devanagari/TiroDevanagariSanskri... | sanskrit-coders/doc_curation | doc_curation/ebook/pdf_book/__init__.py | .py | 0d43e4cca59bb26c | 7.48 | 8 |
import logging
import os
from doc_curation.ebook import pdf_book
from pypdf import PdfReader, PdfWriter, PageObject
from pypdf import Transformation
from pypdf.annotations import Line
from tqdm import tqdm
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm # Import cm for easy conversion
from repo... | sanskrit-coders/doc_curation | doc_curation/ebook/pdf_book/booklet_maker.py | .py | cee52d7bac8e5eb5 | 7.48 | 8 |
import regex
import subprocess, tempfile, os
import shutil
from curation_utils import file_helper
from doc_curation.md.content_processor import footnote_helper, quote_helper, details_helper
def md_links_to_latex(content: str) -> str:
"""
Convert Markdown links [text](url) into LaTeX \href{url}{text}.
"""
... | sanskrit-coders/doc_curation | doc_curation/ebook/pdf_book/latex.py | .py | b1ef0f964ddaf676 | 7.48 | 8 |
#!/usr/bin/env python3
# Not working as of 202205
import io
import os
import re
import subprocess
import sys
from tempfile import NamedTemporaryFile
from os import path
objstart = re.compile(b'^\d+ \d+ obj\s*$')
def writebuffer(fh, buffer):
for line in buffer:
fh.write(line)
def remove_watermark_objects(infile, ... | sanskrit-coders/doc_curation | doc_curation/ebook/pdf_book/removewatermark.py | .py | 89f7311dca3c06b0 | 7.48 | 8 |
import math
def equispaced_points_on_circumference(num_points, radius=1, start_angle=0, center=(0, 0)):
angle_diff = 2 * math.pi / num_points
points = []
for i in range(num_points):
angle = start_angle + i * angle_diff
x = center[0] + radius * math.cos(angle)
y = center[1] + radius * math.sin(angle... | sanskrit-coders/doc_curation | doc_curation/image/coordinate_geometry.py | .py | 7f7e28d2da8c2746 | 7.48 | 8 |
import regex
def set_audio_caption_from_filename(text, prefix):
"""
Example: replace <div class="audioEmbed" src="https://archive.org/download/tiruppAvai_vibhA/30__Vangakkadal_kadainda__suruTTi.mp3" caption=""></div>
with
<div class="audioEmbed" src="https://archive.org/download/tiruppAvai_vibhA/30__Van... | sanskrit-coders/doc_curation | doc_curation/md/content_processor/embed_helper.py | .py | e62c186b927dede3 | 7.48 | 8 |
import textwrap
import regex
import logging
from collections import defaultdict
REF_PATTERN = r"\[\^([^\]\n]+?) *\]"
DEF_ENDING = r"(?=$|\n\[\^|\n<|\n#|\n\n)"
DEFINITION_PATTERN_SINGLE_LINE = rf"(?<=\n)({REF_PATTERN}):\s*(\S[\s\S]+?){DEF_ENDING}"
DEFINITION_PATTERN_MULTI_LINE = rf"(?<=\n)({REF_PATTERN}): *\n(( .*|\... | sanskrit-coders/doc_curation | doc_curation/md/content_processor/footnote_helper.py | .py | 2f3ab19bad54dc59 | 7.48 | 8 |
import regex
def get_quote_level(line):
"""
Calculates the nesting level of a markdown blockquote line.
For example, '>> quote' is level 2.
"""
# Match one or more '>' characters, each possibly followed by a space
match = regex.match(r'^(>\s*)+', line)
if not match:
return 0
# The level is the numb... | sanskrit-coders/doc_curation | doc_curation/md/content_processor/quote_helper.py | .py | 4510bdcf23a40320 | 7.48 | 8 |
import regex
from indic_transliteration import sanscript
def remove_fake_linebreaks(content, *args, **kwargs):
""" Remove linebreaks which are treated as space within a paragraph when markdown is converted to html
:param content:
:param args:
:param kwargs:
:return:
"""
# -* account for lists.
... | sanskrit-coders/doc_curation | doc_curation/md/content_processor/space_helper.py | .py | 256a7f84a2efe2ae | 7.48 | 8 |
import logging
import os
import pathlib
import shutil
from functools import lru_cache
import regex
from doc_curation.md.file import MdFile
from doc_curation.md.library import metadata_helper, get_md_files_from_path
from indic_transliteration import sanscript
def defolderify_single_md_dirs(dir_path, dry_run=False):
... | sanskrit-coders/doc_curation | doc_curation/md/library/arrangement.py | .py | 0f1889380c6ca697 | 7.48 | 8 |
"""
Curate and process pdf files.
"""
import errno
import logging
import os
import shutil
import subprocess
from pathlib import Path
import xml.etree.ElementTree as ET
import random
from bs4 import BeautifulSoup
import json
import pypdf
import os
from pikepdf import Pdf
from curation_utils import list_helper
## To ... | sanskrit-coders/doc_curation | doc_curation/pdf/__init__.py | .py | 4ecf77d226e089fb | 7.48 | 8 |
import glob
import logging
import shutil
from curation_utils.google import drive
import os
import time
from pathlib import Path
from curation_utils import file_helper
from doc_curation import pdf
from doc_curation.pdf import compress_with_gs, detext_via_jpg, split_into_small_pdfs, _get_ocr_dir, \
detext_with_pdfima... | sanskrit-coders/doc_curation | doc_curation/pdf/drive_ocr.py | .py | 80b243febb87f56e | 7.48 | 8 |
"""Contains functions for working with a grascii configuration file.
Acts as the entry point for the grascii config command.
This can be invoked as a standalone program:
$ python -m grascii.config --help
"""
from __future__ import annotations
import argparse
import sys
from enum import Enum
from importlib.resources ... | grascii/grascii | grascii/config.py | .py | 3cad6c59bbd31d3f | 7.63 | 17 |
from __future__ import annotations
import argparse
import sys
from functools import lru_cache
from typing import TYPE_CHECKING
from lark import Lark, Token, Transformer, UnexpectedInput
from lark.exceptions import VisitError
from lark.visitors import v_args
from grascii.interpreter import interpretation_to_string
fr... | grascii/grascii | grascii/dephrase.py | .py | 9cef74bddf4636f6 | 7.63 | 17 |
from __future__ import annotations
from enum import Enum
from importlib.resources import files
from pathlib import Path
from typing import (
IO,
TYPE_CHECKING,
Any,
NamedTuple,
)
from grascii.dictionary import build, install, uninstall
from grascii.dictionary import list as list_dict
from grascii.dict... | grascii/grascii | grascii/dictionary/__init__.py | .py | 4dd97a40375cd3dc | 7.63 | 17 |
"""
Acts as the main entry point for the grascii build command and contains the
dictionary builder implementation.
This can be invoked as a standalone program:
$ python -m grascii.dictionary.build --help
"""
from __future__ import annotations
import argparse
import logging
import os
import pathlib
import re
import s... | grascii/grascii | grascii/dictionary/build.py | .py | 6670ad27ebefd84f | 7.63 | 17 |
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from shutil import copy
from grascii.dictionary.common import (
INSTALLATION_DIR,
DictionaryAlreadyExists,
get_dictionary_installed_name,
get_dictionary_path_name,
)
description = "Install a Grascii Dictionary"
d... | grascii/grascii | grascii/dictionary/install.py | .py | b44bad38f81a4514 | 7.63 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.