text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
import asyncio
from datetime import timedelta
from itertools import islice
from time import time
from typing import cast
from opentelemetry.trace import get_tracer
from cbltest.api.database import Database
from cbltest.api.error import CblTestError, CblTimeoutError
from cbltest.api.replicator_types import (
Repli... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/api/replicator.py | .py | c979c6455ce35219 | 7.74 | 2 |
from __future__ import annotations
from abc import abstractmethod
from enum import Enum, Flag, auto
from typing import Any, Final, cast
from cbltest.api.jsonserializable import JSONSerializable
from cbltest.assertions import _assert_not_empty
from cbltest.jsonhelper import _get_typed_required
from cbltest.responses i... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/api/replicator_types.py | .py | 247529c03cf13d14 | 7.74 | 2 |
import asyncio
import random
from collections.abc import Sequence
from cbltest.api.syncgateway import DatabaseConfig, SyncGateway
class SyncGatewayCluster:
"""
A cluster of Sync Gateway nodes, for operations that must coordinate across all
of them.
"""
def __init__(self, sync_gateways: Sequence[... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/api/syncgatewaycluster.py | .py | b08b403b92fd0b63 | 7.74 | 2 |
from typing import Any
from opentelemetry.trace import get_tracer
from cbltest.api.database import AllDocumentsEntry, Database
from cbltest.api.replicator_types import ReplicatorType
from cbltest.api.syncgateway import AllDocumentsResponseRow, SyncGateway
from cbltest.version import VERSION
def _compare_revisions(c... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/api/test_functions.py | .py | 026a5a6beed8ae65 | 7.74 | 2 |
from typing import Final, cast
from urllib.parse import urljoin, urlparse
from opentelemetry.trace import get_tracer
from cbltest.api.database import Database
from cbltest.assertions import _assert_not_null
from cbltest.globals import CBLPyTestGlobal
from cbltest.request_types import PostResetRequestMethods
from cblt... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/api/testserver.py | .py | e20afcfb57d4357f | 7.74 | 2 |
from datetime import datetime, timedelta, timezone
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, pkcs12
from cryptography.x509 import (
BasicConstraints,
Certificate,
... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/api/x509_certificate.py | .py | e3cc676cf48b3afa | 7.74 | 2 |
from enum import Enum
from json import dumps, load
from logging import warning
from pathlib import Path
from typing import Final
from .jsonhelper import (
_assert_string_entry,
_get_bool_or_default,
_get_int_or_default,
_get_str_or_default,
_get_typed,
_get_typed_nonnull,
)
class TestServerIn... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/configparser.py | .py | 8f1c5a23da88a1d7 | 7.74 | 2 |
import asyncio
from collections.abc import Awaitable, Iterable, Sequence
import pytest_asyncio
from cbltest import CBLPyTest
from cbltest.api.cluster import CouchbaseCluster
from cbltest.api.error import CblTestError
from cbltest.api.syncgateway import SyncGateway
from cbltest.api.syncgatewaycluster import SyncGateway... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/plugins/cluster_cleanup.py | .py | c13986b6b8d7bcb1 | 7.74 | 2 |
import os
from collections.abc import AsyncGenerator
from pathlib import Path
import pytest
import pytest_asyncio
from cbltest import CBLPyTest
from cbltest.api.syncgateway import CouchbaseVersion
from cbltest.greenboarduploader import GreenboardUploader, resolve_branch
from cbltest.logging import cbl_info, cbl_warnin... | couchbaselabs/couchbase-lite-tests | client/src/cbltest/plugins/greenboard_fixture.py | .py | 0c7d8b6e05cd22bb | 7.74 | 2 |
from tkinter import ttk
from tkinter import filedialog, messagebox
import tkinter as tk
import webbrowser as web
import time
import sys
import os
import re
import json
import PIL.Image as Image
import windnd # pip install windnd
import ctypes
from ctypes.wintypes import MAX_PATH
# ==================== Config (JSON... | 745692208/ImageMergeTool | src/ImageMergeTool.py | .py | a527117224262e27 | 7.3 | 3 |
"""
Participant index anonymization DAG
"""
from datetime import timedelta, datetime
from airflow import DAG
from airflow.models import Param
from lib.config import CONFIG_FILE, JAR, SPARK_FAILURE_MSG, DEFAULT_ARGS
from lib.operators.spark import SparkOperator
from lib.slack import Slack
from lib.tasks.notify import ... | Ferlab-Ste-Justine/unic-dag | dags/anonymized_participant_index.py | .py | 180f1890d52ade8f | 7.15 | 1 |
"""
Iceberg Table Maintenance DAG
"""
from datetime import timedelta
from typing import List
import pendulum
from airflow import DAG
from airflow.models import Param
from lib.operators.spark_iceberg import SparkIcebergOperator
from lib.config import DEFAULT_TIMEOUT_HOURS, DEFAULT_ARGS, SPARK_FAILURE_MSG, JAR, LOCAL_T... | Ferlab-Ste-Justine/unic-dag | dags/iceberg_table_maintenance.py | .py | 04e4e87243c22b70 | 7.15 | 1 |
import subprocess
from airflow.providers.postgres.hooks.postgres import PostgresHook
class PostgresCaHook(PostgresHook):
"""
Interact with Postgres DB.
:param postgres_conn_id: The connection ID used to connect to Postgres
:param ca_path: Filepath where ca certificate file will be located
:param c... | Ferlab-Ste-Justine/unic-dag | dags/lib/hooks/postgresca.py | .py | afe266ee22addaa5 | 7.15 | 1 |
# pylint: disable=import-outside-toplevel
import subprocess
from enum import Enum
from airflow.models import Variable
from lib.templates.resource_centric import resource_centric_template
from lib.templates.table_centric import table_centric_template
from lib.templates.variable_centric import variable_centric_template... | Ferlab-Ste-Justine/unic-dag | dags/lib/opensearch.py | .py | 034e012d5ca4e8e7 | 7.15 | 1 |
# pylint: disable=too-many-locals
import csv
from contextlib import ExitStack
from tempfile import NamedTemporaryFile
from typing import List, Dict
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.postgres.hooks.postgres import PostgresHook
from lib.operators.postgresca import PostgresC... | Ferlab-Ste-Justine/unic-dag | dags/lib/operators/copy_csv_to_postgres.py | .py | 5b67f94195c98379 | 7.15 | 1 |
import subprocess
from typing import Sequence
from airflow.exceptions import AirflowSkipException
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
class PostgresCaOperator(SQLExecuteQueryOperator):
"""
Execute SQL in Postgres with CA certificate
:param postgres_conn_id: The... | Ferlab-Ste-Justine/unic-dag | dags/lib/operators/postgresca.py | .py | b5a94f0278cd271f | 7.15 | 1 |
# pylint: disable=too-many-instance-attributes, too-many-locals
import csv
import logging
import re
from tempfile import NamedTemporaryFile
from typing import List, Sequence
import psycopg2
from airflow.exceptions import AirflowSkipException
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.provide... | Ferlab-Ste-Justine/unic-dag | dags/lib/operators/upsert_csv_to_postgres.py | .py | 3930eca9b0f3f56d | 7.15 | 1 |
"""
Miscellaneous model inputs.
This module provides helper functions and configuration required by the model,
including accessors for country and region datasets, hazard scenario selection,
and preprocessing of national and subnational administrative boundaries.
Written by Ed Oughton
February 2022
"""
import os
impo... | edwardoughton/open-rigbi | scripts/misc.py | .py | 1cb8b82c3f654a47 | 7.15 | 1 |
"""
Validate flood area statistics.
The workflow uses national Aqueduct rasters so regional fragments cannot be
double counted. Alternate coastal percentile rasters are excluded because
Figure 8 and Figure S1 use the default (95th-percentile) coastal layer.
"""
import argparse
import os
import shutil
import subproces... | edwardoughton/open-rigbi | scripts/validation.py | .py | 98f6c73e617c9c36 | 7.15 | 1 |
#!/usr/bin/env python
# source: https://github.com/nbering/terraform-inventory
'''
Terraform Inventory Script
==========================
This inventory script generates dynamic inventory by reading Terraform state
contents. Servers and groups a defined inside the Terraform state using special
resources defined by the... | status-im/infra-template | ansible/terraform.py | .py | dec104ce834681fd | 7 | 0 |
#!/usr/bin/env python3
"""
Retrieve and disseminate files and metadata to Clarivate Web of Science Book Citation Index (BKCI)
"""
import logging
import sys
from datetime import datetime, timezone
from ftplib import FTP, error_perm
from io import BytesIO, TextIOWrapper
from errors import DisseminationError
from uploade... | thoth-pub/thoth-dissemination | bkciuploader.py | .py | 6c2c1da041f21710 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Retrieve and disseminate DOI deposit metadata files to Crossref
Based on guide at https://www.crossref.org/documentation/register-maintain-records/direct-deposit-xml/https-post/
"""
import logging
import sys
import requests
from errors import DisseminationError
from uploader import Uploader
... | thoth-pub/thoth-dissemination | crossrefuploader.py | .py | ac74406395b9f651 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Retrieve and disseminate files and metadata to
Cambridge University Library pilot collaboration DSpace
"""
from dspaceuploader import DSpaceUploader, MetadataProfile
from uploader import Location
class CULUploader(DSpaceUploader):
def __init__(self, work_id, export_url, client_url, ver... | thoth-pub/thoth-dissemination | culuploader.py | .py | 10536d0249c28450 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Retrieve and disseminate files and metadata to a DSpace repository
"""
from swordv2uploader import SwordV2Uploader, MetadataProfile
class DSpaceUploader(SwordV2Uploader):
# Currently DSpace dissemination is only implemented via SWORDv2
# This class will be extended once we implemen... | thoth-pub/thoth-dissemination | dspaceuploader.py | .py | 99366d8eab042774 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Custom errors for Dissemination Service
"""
class DisseminationError(Exception):
"""Exception to report generic errors"""
def __init__(self, message):
super().__init__(message)
class InternetArchiveIdentifierCollisionError(DisseminationError):
"""Refuse to modify an I... | thoth-pub/thoth-dissemination | errors.py | .py | d5bfb30ebb49c2ad | 7.35 | 4 |
#!/usr/bin/env python3
"""
Retrieve and upload files and metadata to dedicated Thoth server
for automated content fetching by Google Play crawler
Based on guide at https://support.google.com/books/partner/answer/2763162
"""
import logging
import sys
from datetime import date
from google.cloud import storage
from error... | thoth-pub/thoth-dissemination | googleplayuploader.py | .py | 845e2c619753e4a0 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Retrieve and disseminate files and metadata to OAPEN FTP server
Deprecated in favour of dissemination via OAPEN SWORD server (oapensworduploader.py)
"""
import logging
import sys
from ftplib import FTP, error_perm
from io import BytesIO
from errors import DisseminationError
from uploader imp... | thoth-pub/thoth-dissemination | oapenftpuploader.py | .py | f1cced98bad42201 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Retrieve and disseminate files and metadata to
OAPEN DSpace using SWORD protocol
"""
from dspaceuploader import DSpaceUploader, MetadataProfile
from uploader import Location
class OAPENSWORDUploader(DSpaceUploader):
"""Dissemination logic for OAPEN SWORD"""
def __init__(self, work... | thoth-pub/thoth-dissemination | oapensworduploader.py | .py | ab0575a2540fc323 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Wrapper class for SFTP connections
"""
from paramiko import ssh_exception, AutoAddPolicy, SSHClient
class SFTPClient():
"""Wrapper around third-party SFTP client"""
def __init__(self, host, username, password, port: int = 22):
"""Set up SFTP connection"""
paramiko ... | thoth-pub/thoth-dissemination | sftpclient.py | .py | 810ab368760d4949 | 7.35 | 4 |
#!/usr/bin/env python3
"""Helpers for configuring and patching Thoth client access."""
import json
from os import environ
from uuid import UUID
PUBLICATION_LOCATIONS_QUERY = """
query PublicationLocations($publicationId: Uuid!, $limit: Int!, $offset: Int!) {
publication(publicationId: $publicationId) {
publica... | thoth-pub/thoth-dissemination | thothapi.py | .py | 04e2c16441faabad | 7.35 | 4 |
"""Preconfigured PPC benchmark shops compared on one seeded run.
Pure Job Shop (PJS, undirected routing), General Flow Shop (GFS, directed/sorted
routing), and Pure Flow Shop (PFS, every job visits all machines in a fixed
order) — the standard stylized shops of the workload-control literature
(Oosterman, Land & Gaalma... | dmezzogori/simulatte | examples/gallery_benchmark_shops.py | .py | 74757ca6bc199184 | 7.3 | 3 |
"""Release triggers and starvation avoidance.
Exercises the periodic_trigger primitive directly (in the Periodic-release
system) and contrasts a starvation-avoidance pull — built via the callback API
(psp.on_arrival / shop_floor.on_processing_end) — and a periodic-release pull
against the immediate-release baseline:
... | dmezzogori/simulatte | examples/gallery_release_triggers.py | .py | f296c13b0b71507a | 7.3 | 3 |
"""Workload-control release policies compared on one seeded shop.
Immediate release (push baseline) vs LumsCor, SLAR, SLAR-Limit, and Continuous
Release — all workload-control pull policies that hold jobs in a Pre-Shop Pool
and release against load norms.
Run: uv run python examples/gallery_release_workload.py
"""
f... | dmezzogori/simulatte | examples/gallery_release_workload.py | .py | 3ef641c05416e24c | 7.3 | 3 |
"""Composite dispatching rules.
Rules that combine several scheduling signals — processing time, due-date
slack, machine utilization, downstream queue load — into one priority index.
"""
from __future__ import annotations
import math
from typing import TYPE_CHECKING
from simulatte.dispatching_rules.work_content imp... | dmezzogori/simulatte | src/simulatte/dispatching_rules/composite.py | .py | ab122ed39dc06129 | 7.3 | 3 |
"""Due-date-based dispatching rules.
Stateless ``(job, server) -> float`` rules that order a queue by operation
due dates derived from the job's due date. Lower numeric value = served first.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover
from simula... | dmezzogori/simulatte | src/simulatte/dispatching_rules/due_date.py | .py | bd8ef2c8d2f42217 | 7.3 | 3 |
"""Processing-time and baseline dispatching rules.
Stateless ``(job, server) -> float`` rules that order a queue from local
processing information — or, for first-come-first-served, defer entirely to
arrival order. Lower numeric value = served first.
"""
from __future__ import annotations
from typing import TYPE_CHE... | dmezzogori/simulatte | src/simulatte/dispatching_rules/processing.py | .py | b20b2e4bc1033298 | 7.3 | 3 |
"""Slack- and ratio-based dispatching rules.
``(job, server) -> float`` rules that order a queue by a job's remaining slack
relative to the work it has left. Includes the parameterized factories
(``planned_slack_time``, ``slack_per_remaining_operation``) — call them
with a per-operation allowance to obtain the callabl... | dmezzogori/simulatte | src/simulatte/dispatching_rules/slack.py | .py | 6daba5958dc674ac | 7.3 | 3 |
"""Tardiness-cost dispatching rules (ATC, COVERT).
Index rules that estimate a job's marginal tardiness cost per unit of imminent
processing time. Both are parameterized factories; call with a look-ahead
parameter to obtain the ``(job, server) -> float`` callable. The returned
callable yields the *negated* priority in... | dmezzogori/simulatte | src/simulatte/dispatching_rules/tardiness_cost.py | .py | f7d1b52bc77e94b7 | 7.3 | 3 |
"""Work-content dispatching rules.
Look-ahead rules that order a queue by the workload a job will encounter at the
next machine on its route. Lower numeric value = served first.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING: # pragma: no cover
from simulatte.job impor... | dmezzogori/simulatte | src/simulatte/dispatching_rules/work_content.py | .py | 4e38af7750d93bd6 | 7.3 | 3 |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
import gymnasium
class SimulatteEnv(gymnasium.Env, ABC):
"""Base class for wrapping simulations as Gymnasium environments.
Subclass this and implement the six abstract methods to define your
simulation's obser... | dmezzogori/simulatte | src/simulatte/experimental/gymnasium.py | .py | 73d8ac0477a9f2ed | 7.3 | 3 |
from __future__ import annotations
from typing import TYPE_CHECKING
import simpy
from simpy.events import ProcessGenerator
if TYPE_CHECKING:
from collections.abc import Callable
from simulatte.environment import Environment
from simulatte.intralogistics.agv import AGV
from simulatte.intralogistics.g... | dmezzogori/simulatte | src/simulatte/intralogistics/charging.py | .py | c9378ff733e79e3f | 7.3 | 3 |
from __future__ import annotations
from typing import TYPE_CHECKING
import simpy
import simpy.resources.resource
from simpy.events import ProcessGenerator
if TYPE_CHECKING:
from simulatte.environment import Environment
from simulatte.intralogistics.agv import AGV
from simulatte.intralogistics.graph impor... | dmezzogori/simulatte | src/simulatte/intralogistics/parking.py | .py | 2bf5180be26f5f0e | 7.3 | 3 |
"""Job management and scheduling logic for jobshop simulations."""
from __future__ import annotations
import uuid
from abc import ABC, abstractmethod
from enum import Enum, auto
from typing import TYPE_CHECKING, Any
from simulatte.environment import Environment
if TYPE_CHECKING: # pragma: no cover
from collect... | dmezzogori/simulatte | src/simulatte/job.py | .py | b15f2e296062efa2 | 7.3 | 3 |
import praw # New import
import pathlib
import re
import os
root = pathlib.Path(__file__).parent.resolve()
# --- Reddit API Credentials from Environment Variables ---
# Make sure you have set these in your environment!
CLIENT_ID = os.getenv("REDDIT_CLIENT_ID")
CLIENT_SECRET = os.getenv("REDDIT_CLIENT_SECRET")
USER_A... | coldter/coldter | build_readme.py | .py | 0b2ba19dde7ba83d | 7.35 | 4 |
#!/usr/bin/env python3
"""Render the yearly-progress banner.
A Python port of the original yearProgress.js, kept byte-for-byte compatible
with its output (used by build_readme.py via yearProgress.txt).
"""
import sys
from datetime import datetime, timezone
# JavaScript's Date.prototype.toUTCString() always emits Eng... | coldter/coldter | yearProgress.py | .py | 942f39a6add6a384 | 7.35 | 4 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | opentelekomcloud-infra/validatetoken | validatetoken/echo/service.py | .py | 40ad615b184618e0 | 7 | 0 |
"""Generate a config report for Mink settings."""
# ruff: file-ignore[print]
from __future__ import annotations
import argparse
import importlib
import json
import os
import pkgutil
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from dotenv import dotenv_values
from pydantic impor... | spraakbanken/mink-backend | config_helper.py | .py | 5e66de038f938690 | 7 | 0 |
"""Memcached client management."""
from collections.abc import Generator
from contextlib import contextmanager
from pymemcache import serde
from pymemcache.client.base import Client
from mink.core.config import settings
from mink.core.logging import logger
def cache_namespace(key: str) -> str:
"""Return a name... | spraakbanken/mink-backend | mink/cache/memcached.py | .py | ab6628c79bb8bcea | 7 | 0 |
"""Helpers for working with Mink settings classes and environment variables."""
from __future__ import annotations
import importlib
from collections.abc import Iterable, Mapping, Sequence
from pathlib import Path
from dotenv import dotenv_values
from pydantic_settings import BaseSettings
from mink.core.config impor... | spraakbanken/mink-backend | mink/core/config_utils.py | .py | 4032de8a201fdf91 | 7 | 0 |
"""Class defining resource info objects."""
import json
from pathlib import Path
from mink.cache import jobs_cache
from mink.core import exceptions, registry, utils
from mink.core.config import settings
from mink.core.jobs import BaseJob
from mink.core.logging import logger
from mink.core.resource import Resource
fro... | spraakbanken/mink-backend | mink/core/info.py | .py | 355e3bf5aeb58fb2 | 7 | 0 |
"""Routes related to jobs status and information."""
from datetime import datetime
from fastapi import APIRouter, Depends, Query, status
from fastapi.responses import JSONResponse
from mink.core import exceptions, models, registry, return_codes, route_utils, utils
from mink.core.config import settings
from mink.core... | spraakbanken/mink-backend | mink/core/job_routes.py | .py | 10ae72ef407ce3fd | 7 | 0 |
"""Utilities related to the resource registry and job queue.
The registry and job queue live in the cache and also on the local file system (as backup).
"""
import json
from collections.abc import Callable
from functools import wraps
from pathlib import Path
from mink.cache import jobs_cache
from mink.core import ex... | spraakbanken/mink-backend | mink/core/registry.py | .py | e040f584d799776d | 7 | 0 |
"""Classes defining resource objects."""
from dataclasses import dataclass
from typing import Any
from mink.core import exceptions, utils
@dataclass(frozen=True, slots=True)
class ResourceType:
"""Value object representing a resource type."""
value: str
def __post_init__(self) -> None:
"""Vali... | spraakbanken/mink-backend | mink/core/resource.py | .py | 9d50a9c5dde6f303 | 7 | 0 |
"""Registry for resource type specifications."""
# ruff: file-ignore[import-outside-top-level], avoids circular import
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
from mink.core.resource import ResourceType
@dataclass(froz... | spraakbanken/mink-backend | mink/core/resource_specs.py | .py | c9ca88657294457b | 7.5 | 0 |
"""Collection of general routes."""
import copy
import json
import re
from collections import defaultdict
from collections.abc import Callable
from pathlib import Path
from fastapi import APIRouter, Request
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.responses import HTMLResponse... | spraakbanken/mink-backend | mink/core/routes.py | .py | 60ea4807f73a5a04 | 7 | 0 |
"""Classes defining job statuses."""
from collections import UserDict
from collections.abc import Container, Iterable
from enum import StrEnum
class Status(StrEnum):
"""Class for representing the status of a job."""
none = "none"
waiting = "waiting"
running = "running"
done = "done"
error = ... | spraakbanken/mink-backend | mink/core/status.py | .py | e3022ab5b3b9dfa9 | 7 | 0 |
"""Class defining user objects."""
from typing import Any
from mink.core import utils
class User:
"""A user item holding information about some user data and settings."""
def __init__(
self,
id: str, # ruff: ignore[builtin-argument-shadowing]
name: str,
email: str,
... | spraakbanken/mink-backend | mink/core/user.py | .py | 3f0b1d32d94d463a | 7 | 0 |
"""General utility functions."""
from __future__ import annotations
import datetime
import gzip
import logging
import os
import pickle
import shutil
import tomllib
import unicodedata
import zipfile
from collections.abc import Mapping, Sequence
from enum import Enum
from pathlib import Path
from typing import TYPE_CHE... | spraakbanken/mink-backend | mink/core/utils.py | .py | 8fdc0bbf1e8116ca | 7 | 0 |
"""Karp job implementations."""
import shlex
from mink.core import exceptions, registry, utils
from mink.core.jobs import BaseJob
from mink.core.logging import logger
from mink.core.resource_specs import get_spec
from mink.core.status import Status
from mink.karp import cache
from mink.karp.config import karp_setting... | spraakbanken/mink-backend | mink/karp/jobs.py | .py | 5dab09d086bcd251 | 7 | 0 |
"""Karp resource spec registration."""
# ruff: file-ignore[import-outside-top-level], avoids circular import
from enum import StrEnum, auto
from typing import Any, cast
from mink.core.resource import ResourceType
from mink.karp.config import karp_settings
LEXICON = ResourceType("lexicon")
class ProcessName(StrEnu... | spraakbanken/mink-backend | mink/karp/spec.py | .py | 08c597d2cb2a9a28 | 7.5 | 0 |
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "girder_client",
# "pyyaml",
# ]
# ///
# End pep723 blocks
import argparse
import os
import tempfile
import girder_client
import girder_client.cli
import yaml
def get_girder_client(opts):
"""
Log in to Girder and retur... | DigitalSlideArchive/large-image-utilities | fiducial_tps.py | .py | 47449d627ad8128f | 7.35 | 4 |
"""Conversation-aware query rewriting for the legacy search agent."""
import re
import json
import logging
from typing import Optional, Any
from pydantic import BaseModel
from langchain_core.messages import HumanMessage
logger = logging.getLogger(__name__)
class RewriteResult(BaseModel):
rewritten_query: str
... | vitality-vis/rest-api | agents/agent_v1_legacy/query_rewriter.py | .py | 641cc1db2363e1a5 | 7.39 | 5 |
"""
Process-local session state owned by the legacy research assistant.
Holds the global ``SESSIONS`` dict and helpers for ``agent_v1_legacy`` modules,
without circular imports.
"""
from typing import Optional
# Single global store: chat_id -> session dict
SESSIONS: dict = {}
def get_session(chat_id: str) -> Optiona... | vitality-vis/rest-api | agents/agent_v1_legacy/session_state.py | .py | 95ab3a8c8b551d0f | 7.39 | 5 |
"""Minimal structured decision logging for search v2."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal
from uuid import uuid4
from logger_config import log_structured
from .models import RetrievalPlan
@dataclass(frozen=True)
class SearchV2Trace:
"""Own the... | vitality-vis/rest-api | agents/agent_v2/logging.py | .py | 1a8ea9a1e891fe85 | 7.39 | 5 |
"""Public and internal DTOs for agent v2 and its search capability."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Annotated, Literal
from pydantic import BaseModel, Field
MAX_SEARCH_QUERY_LENGTH = 10_000
MAX_RETRIEVAL_CALLS = 8
MAX_CALLS_BY_TOOL = {
"bm25": 3,... | vitality-vis/rest-api | agents/agent_v2/models.py | .py | b3c481db5f031564 | 7.39 | 5 |
"""Shared retrieval-plan execution, fusion, and reranking for search v2."""
from __future__ import annotations
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from service.search import SearchUnavailableError, search
from app.chat.run_control import... | vitality-vis/rest-api | agents/agent_v2/search_executor.py | .py | 050063cb81ce8a09 | 7.39 | 5 |
"""Typed retrieval actions and adapters shared by low and medium search."""
from __future__ import annotations
from collections import Counter
from typing import Annotated, Any
from model.paper import SearchRequest
from pydantic import BaseModel, ConfigDict, Field
from .models import (
BM25RetrievalAction,
E... | vitality-vis/rest-api | agents/agent_v2/search_tools.py | .py | 54d83509c1eed794 | 7.39 | 5 |
"""Public corpus bootstrap endpoints (UMAP + filter metadata)."""
from flask import Blueprint, current_app, jsonify
from flask_cors import cross_origin
from service import zilliz
from service.static_cache import cached_data
corpus_bp = Blueprint("corpus", __name__)
@corpus_bp.route("/getUmapPoints", methods=["GET... | vitality-vis/rest-api | app/api/public/corpus.py | .py | 05e09da8e5c1620d | 7.39 | 5 |
"""Explicit papers/full blueprint allowlists for profile-aware registration.
HTTP paths are unchanged; this module only controls which blueprints are imported and registered.
"""
from __future__ import annotations
from collections.abc import Iterable
from importlib import import_module
from typing import Any
# (imp... | vitality-vis/rest-api | app/api/route_allowlist.py | .py | 3e979639ace05a74 | 7.39 | 5 |
"""FastAPI + WSGIMiddleware (+ optional Chat / Socket.IO) composition."""
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING
from a2wsgi import WSGIMiddleware
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.asgi.life... | vitality-vis/rest-api | app/asgi/application.py | .py | 67f805fbd86afe84 | 7.39 | 5 |
"""Process lifespan: cache init, session reset, capability refresh."""
from __future__ import annotations
from typing import TYPE_CHECKING
from app.profiles import AppProfile, discover_capabilities
from app.wsgi import apply_profile_config
from service.static_cache import cached_data
if TYPE_CHECKING:
from app.... | vitality-vis/rest-api | app/asgi/lifespan.py | .py | 986fe115d3b2bda8 | 7.39 | 5 |
"""Bridge Agent events from a dedicated worker thread to the ASGI event loop."""
from __future__ import annotations
import asyncio
import logging
import threading
from collections.abc import AsyncIterator, Awaitable, Callable
from concurrent.futures import CancelledError as FutureCancelledError
from dataclasses impor... | vitality-vis/rest-api | app/chat/event_bridge.py | .py | 874a730d54c9700a | 7.39 | 5 |
"""Transport-independent Chat turn request models."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
ChatPipeline = Literal["v2"]
ChatEffort = Literal["low", "medium", "high"]
ChatMode = Literal["auto", "chat", "search", "synthesis"]
class ChatDomainErro... | vitality-vis/rest-api | app/chat/models.py | .py | 53cd820970ef5dd4 | 7.39 | 5 |
"""
Sphinx extension to render Jinja2 in .rst files.
This will render Jinja2 BEFORE .rst files are parsed.
"""
from sphinx.application import Sphinx
def jinja2_rendering(app: Sphinx, docname: str, source: list) -> None:
"""Render Jinja2 in .rst files before the Sphinx magic.
THIS ONLY WORKS IN HTML RENDERING... | btr1975/cookiecutter-python-library | {{cookiecutter.git_repo_name}}/docs/_ext/jinja2_rendering.py | .py | 6704eadc8b823662 | 7.24 | 2 |
"""
This module contains the configuration for the Insalan app.
"""
import django_stubs_ext
from django.apps import AppConfig
from rest_framework import generics, serializers
class InsalanConfig(AppConfig):
"""Insalan configuration"""
name: str = "insalan"
def ready(self) -> None:
# pylint: dis... | InsaLan/backend-insalan.fr | insalan/apps.py | .py | a7d76b618a6eeaec | 7.35 | 4 |
"""
This module contains test cases for the models in the insalan.cms app.
The test cases cover the following models:
- Content
- Constant
Each test case verifies the functionality and behavior of the respective model.
"""
from django.db.utils import IntegrityError
from django.test import TestCase
from django.core.ex... | InsaLan/backend-insalan.fr | insalan/cms/tests.py | .py | ffd4da77d292bf0d | 7.85 | 4 |
import os
from io import BytesIO
from typing import Any
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Model
from PIL import Image
# TODO: remove pillow-avif-plugin from dependecies when updating pillow to 11.3.0
# https://github.com/python-pillow/Pillow/pu... | InsaLan/backend-insalan.fr | insalan/components/image_field.py | .py | 3ea2ea40d1b7db46 | 7.35 | 4 |
"""
This module contains the models for the ecological statistics app.
It includes the following models:
- TravelData: Represents the travel informations of a person coming to an event.
"""
from django.db.models import CASCADE, CharField, ForeignKey, Model, TextChoices
from django.utils.translation import gettext_laz... | InsaLan/backend-insalan.fr | insalan/ecology/models.py | .py | e62bd383cc9b1644 | 7.35 | 4 |
"""
Serializers for classes in the langate module.
"""
from typing import Any
from rest_framework import serializers
class SimplifiedUserDataSerializer(serializers.Serializer[Any]):
"""
Serializer class for SimplifiedUserData
"""
username = serializers.CharField(max_length=100)
first_name = ser... | InsaLan/backend-insalan.fr | insalan/langate/serializers.py | .py | 98646c1c2d36e7f2 | 7.35 | 4 |
"""
This module contains the views for the Langate app.
LangateUserView is an API endpoint used by the langate to authenticate and verify a user's data.
It handles retrieving and checking user data, and provides a response containing
all the necessary information for the langate to identify the user.
"""
from typing ... | InsaLan/backend-insalan.fr | insalan/langate/views.py | .py | 4dd46184ba350bc4 | 7.35 | 4 |
from django.core.validators import FileExtensionValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from insalan.components.image_field import ImageField
class Partner(models.Model):
class PartnerType(models.TextChoices):
"""There are two types of sponsors"""
... | InsaLan/backend-insalan.fr | insalan/partner/models.py | .py | 76db121df18d8238 | 7.35 | 4 |
from datetime import datetime, timedelta
import pendulum
from airflow.models import DAG, Variable
from airflow.decorators import task
from kubernetes import client
from operators.dbt_operator import create_dbt_operator
from operators.slack_operator import slack_info, slack_error
from allowlists.allowlist import slack_a... | navikt/team_familie_airflow_dags | dags/up_dagsprosessering.py | .py | 189576cef3e523a0 | 7 | 0 |
from datetime import timedelta
import json
import pendulum
from airflow.models import DAG, Variable
from airflow.decorators import task
from airflow.exceptions import AirflowSkipException
from kubernetes import client
from operators.dbt_operator import create_dbt_operator
from operators.slack_operator import slack_in... | navikt/team_familie_airflow_dags | dags/up_maanedsprosessering.py | .py | 8877a04a16153d5b | 7 | 0 |
import datetime, os, json, re
from os import getenv
from google.cloud import secretmanager
from pathlib import Path
def get_periode():
"""
henter periode for the tidligere måneden eksample--> i dag er 19.04.2022, metoden vil kalkulerer periode aarMaaned eks) '202203'
:param periode:
:return: periode
... | navikt/team_familie_airflow_dags | felles_metoder/felles_metoder.py | .py | 0e6da7599752d287 | 7 | 0 |
#!/usr/bin/env python3
#
# testing.py
"""
Pytest helpers.
.. extras-require:: testing
:pyproject:
"""
#
# Copyright © 2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "... | domdfcoding/handy-archives | handy_archives/testing.py | .py | 89354939508096c8 | 7.5 | 0 |
# From https://github.com/python/cpython/blob/main/Lib/test/test_shutil.py
# Copyright (C) 2003 Python Software Foundation
# stdlib
import os
import pathlib
import unittest.mock
from shutil import (
ReadError,
RegistryError,
get_archive_formats,
get_unpack_formats,
make_archive,
register_archive_format,
... | domdfcoding/handy-archives | tests/test_unpack_archive.py | .py | 7fb09d60c1ac6dfa | 7.5 | 0 |
# stdlib
import os
import unittest
from typing import Callable, no_type_check
@no_type_check
def requires_gzip(reason: str = "requires gzip") -> Callable:
try:
# stdlib
import gzip
except ImportError:
gzip = None
return unittest.skipUnless(gzip, reason)
@no_type_check
def requires_zlib(reason: str = "requi... | domdfcoding/handy-archives | tests/utils.py | .py | 16ae12db220028f6 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""This script will handle custom alerts raised for WAS scanning"""
# Standard imports
from __future__ import print_function
__author__ = "Prabhas Gupte"
__copyright__ = "Copyright (C) 2016, Qualys, Inc."
__license__ = "New BSD"
__version__ = "1.0"
# Standard imports
import sys
import json
im... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/apply_qualys_tag_to_webapp.py | .py | 76c792afb20b0c4e | 7 | 0 |
#!/usr/bin/python
"""
This is the main entry point for TA-QualysCloudPlatform
"""
# Standard imports
from __future__ import print_function
import time
import sys, os
# dynamically load all the .whl files
TA_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
WHL_DIR = TA_ROOT + "/bin/whl/"
for filena... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/qualys.py | .py | 5852ff4a212d33f2 | 7 | 0 |
__author__ = 'mwirges'
from qualysModule import qlogger
from qualysModule.splunkpopulator.assethost import HostIdRetriever
from qualysModule.splunkpopulator.detectionpopulator import HostDetectionPopulator
import time
import six.moves.queue as Queue
from threading import Thread, ThreadError, Lock
from six.moves impor... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/qualysModule/splunkpopulator/DetectionFetchCoordinator.py | .py | 4a5965c7d8c26b28 | 7 | 0 |
from __future__ import print_function
__author__ = 'mwirges'
from qualysModule.splunkpopulator.basepopulator import BasePopulator
from qualysModule.splunkpopulator.utils import IDSet
from qualysModule import qlogger
import six.moves.queue as Queue
import time
import qualysModule.splunkpopulator.utils
from six.moves ... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/qualysModule/splunkpopulator/assethost.py | .py | e3407abc1bd8b13d | 7 | 0 |
# -*- coding: utf-8 -*-
__author__ = "Qualys, Inc"
__copyright__ = "Copyright (C) 2018, Qualys, Inc"
__license__ = "New BSD"
__version__ = "1.0"
import sys
import abc
from threading import current_thread
from qualysModule.splunkpopulator.utils import QualysAPIClient, bool_value
from qualysModule import *
import qualys... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/qualysModule/splunkpopulator/basepopulator_json.py | .py | a62fad1530a4857d | 7 | 0 |
import os
import sys
import abc
import six
plugin_directory = os.path.realpath(os.path.dirname(__file__))
sys.path.append(plugin_directory)
class QIDParser():
# : :type: list of BaseQIDParser
PLUGINS = {}
@staticmethod
def load_plugins():
for root, dirs, files in os.walk(plugin_directory):
... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/qualysModule/splunkpopulator/qid_plugins/__init__.py | .py | cd6ac7d4099e6cd8 | 7 | 0 |
# -*- coding: utf-8 -*-
from __future__ import print_function
__author__ = "Qualys, Inc."
__copyright__ = "Copyright (C) 2017, Qualys, Inc"
__license__ = "New BSD"
__version__ = "1.0"
import re, os, sys
# dynamically load all the .whl files
TA_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os... | zarguell/qualys-ta-splunk | TA-QualysCloudPlatform/bin/qualysModule/splunkpopulator/utils.py | .py | 1add4af81263f68f | 7 | 0 |
"""Cached external data sources and projection-sheet ingestion."""
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from typing import Callable
import pandas as pd
from fantasyhelper.sheets import get_gspread_client
def cached_frame(name: str, cache_directory: st... | oradwastaken/FantasyHelper | fantasyhelper/data_sources.py | .py | a6e2e7fc28a51fd7 | 7 | 0 |
from datetime import date, timedelta
def get_previous_monday() -> str:
today = date.today()
days_since_monday = today.weekday()
previous_monday = today - timedelta(days=days_since_monday)
return previous_monday.strftime("%Y-%m-%d")
def get_current_season() -> str:
"""
Returns the season str... | oradwastaken/FantasyHelper | fantasyhelper/dates.py | .py | ecb51f0ae27c353c | 7 | 0 |
"""Player identity normalization and Yahoo eligibility handling."""
from __future__ import annotations
import re
import unicodedata
import pandas as pd
SKATER_POSITIONS = ("C", "LW", "RW", "D")
def normalize_name(value: object) -> str:
text = unicodedata.normalize("NFKD", str(value or ""))
text = "".join(... | oradwastaken/FantasyHelper | fantasyhelper/players.py | .py | 64051092bc1b1fcb | 7 | 0 |
"""Schedule quality calculations."""
from __future__ import annotations
import pandas as pd
def weekly_team_games(games: pd.DataFrame) -> pd.DataFrame:
"""Convert NHL game rows into per-team Monday-week game counts."""
if games.empty:
return pd.DataFrame(columns=["week_start", "team", "games"])
... | oradwastaken/FantasyHelper | fantasyhelper/schedule.py | .py | bc65eb2ea89f5867 | 7 | 0 |
"""OAuth-backed Google Sheets publishing."""
from __future__ import annotations
from pathlib import Path
import gspread
import pandas as pd
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPES = ["https://w... | oradwastaken/FantasyHelper | fantasyhelper/sheets.py | .py | 1fe6b3a36cb52567 | 7 | 0 |
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2018, Will Thames <will@thames.id.au>
#
# This file is part of Ansible
#
# Ansible 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, either version 3 o... | devopscorner/demo | ansible/roles/amazon-aws/amazon-aws/plugins/action/aws_s3.py | .py | 348e233ca01687aa | 7.3 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.