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
#!/usr/bin/python # coding: utf-8 # <<<<<<<<<<<<<<<<<<<<<<<<<< Imports >>>>>>>>>>>>>>>>>>>>>>>>>> import os import re import sys import argparse # for menu system import openpyxl from openpyxl import Workbook from openpyxl.styles import PatternFill import tkinter as tk from tkinter import filedialog, scr...
LincolnLandForensics/HodgePodge
NCMEC/ICACCops_parser.py
.py
1776ef9d6641db22
7.62
16
#!/usr/bin/env python3 # coding: utf-8 ''' Dump all of your NCMEC .zip, .pdf, or .txt files into the NCMEC folder. it will export the emails, ip's, md5's, phone numbers and users into _output folder Example: python NCMEC_PDFs_parser.py ''' # <<<<<<<<<<<<<<<<<<<<<<<<<< Imports >>>>>>>>>>>>>>>>>>>>>>>>>...
LincolnLandForensics/HodgePodge
NCMEC/NCMEC_PDF_parser.py
.py
ea440fccc1d1fb51
7.62
16
import requests # pip install requests from openpyxl import Workbook # pip install openpyxl import time import os import threading import tkinter as tk from tkinter import ttk, filedialog, scrolledtext, messagebox version = '1.3' # Constants VIN_API_ENDPOINT = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValue...
LincolnLandForensics/HodgePodge
VinDecoder/VIN_Decoder.py
.py
c9a6038349ebd6b2
7.62
16
#!/usr/bin/python # coding: utf-8 # <<<<<<<<<<<<<<<<<<<<<<<<<< Imports >>>>>>>>>>>>>>>>>>>>>>>>>> import os import sys import exifread # pip install exifread import hashlib # pip install hashlib import openpyxl # pip install openpyx import argparse # for menu system from datetime import datetime imp...
LincolnLandForensics/HodgePodge
exif_read/exif_read.py
.py
0d8e7a6fd74608a9
7.62
16
#!/usr/bin/python # <<<<<<<<<<<<<<<<<<<<<<<<<< Imports >>>>>>>>>>>>>>>>>>>>>>>>>> import os import sys import datetime from tabula import read_pdf # pip install tabula-py import pandas as pd # <<<<<<<<<<<<<<<<<<<<<<<<<< Pre-Sets >>>>>>>>>>>>>>>>>>>>>>>>>> author = 'LincolnLandForensics' descri...
LincolnLandForensics/HodgePodge
pdf2xlsx/pdf_tables2xlsx.py
.py
54e1fe6cf1a9eb83
7.62
16
#!/usr/bin/env python3 # coding: utf-8 ''' This is a clone of https://github.com/ndaidong/people-detecting.git it counts the approximate number of people in a folder of videos and outputs it to .xlsx ''' # <<<<<<<<<<<<<<<<<<<<<<<<<< Imports >>>>>>>>>>>>>>>>>>>>>>>>>> import os import cv2 import sys import ...
LincolnLandForensics/HodgePodge
peopleCount2/peopleCount3.py
.py
66f58191270d9018
7.62
16
#!/usr/bin/python # coding: utf-8 # <<<<<<<<<<<<<<<<<<<<<<<<<< Imports >>>>>>>>>>>>>>>>>>>>>>>>>> import os import plistlib import xlsxwriter from datetime import datetime import argparse import tkinter as tk from tkinter import ttk, filedialog, messagebox from tkinter.scrolledtext import ScrolledText impo...
LincolnLandForensics/HodgePodge
plist_parser/plist_parser.py
.py
9bc47b4917399fb9
7.62
16
import requests import os import json SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.environ.get("BEARER_TOKEN") app_token = os.environ.ge...
FundF/Spritmonitor-API-sample-code
Add_Fuel_Entry/add_fuel_entry.py
.py
2d0da135c59be18d
7.59
14
import requests import os import json SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.environ.get("BEARER_TOKEN") app_token = os.environ.ge...
FundF/Spritmonitor-API-sample-code
List_Expense_Entries/list_expense_entries.py
.py
24682544118741ee
7.59
14
import requests import os import json SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.environ.get("BEARER_TOKEN") app_token = os.environ.ge...
FundF/Spritmonitor-API-sample-code
List_Fuel_Entries/list_fuel_entries.py
.py
9f1e16c558a5a385
7.59
14
import requests import os import json SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.environ.get("BEARER_TOKEN") app_token = os.environ.ge...
FundF/Spritmonitor-API-sample-code
List_General_Infos/list_general_infos.py
.py
07ec94443d87438c
7.59
14
import requests import os import json SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.environ.get("BEARER_TOKEN") app_token = os.environ.ge...
FundF/Spritmonitor-API-sample-code
List_Vehicle_Statistics/list_vehicle_statistics.py
.py
57e8da387d6624f2
7.59
14
import requests import os import json SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.environ.get("BEARER_TOKEN") app_token = os.environ.ge...
FundF/Spritmonitor-API-sample-code
List_Vehicles/list_vehicles_of_user.py
.py
26bc22b5b6f3f425
7.59
14
import requests import os import json import datetime from urllib.parse import quote SM_API_URL = "https://api.spritmonitor.de/v1" # To set your enviornment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bearer_token>' # export 'APP_TOKEN'='<your_app_token>' bearer_token = os.enviro...
FundF/Spritmonitor-API-sample-code
Manage_Expense_Entries/manage_expense_entries.py
.py
49d619394d7643aa
7.59
14
#!/usr/bin/env python3 import argparse class ProcessArgs: # make the parser a class variable, to limit running processArgs to only one Args object. parser = None def __init__(self): self.argProcessors = [self] # guarantee the args data member is defined, even if processArgs doesn't initialize args. ...
JCSDA/mpas-jedi
graphics/ProcessArgs.py
.py
6beaf4a8f23829c1
7.45
7
#!/usr/bin/env python3 import inspect import logging import multiprocessing as mp import analysis.StatisticsDatabase as sdb # AnalysisBase and derived classes from analysis.AnalysisBase import AnalysisBase ## derived from CategoryBinMethodBase from analysis.category.CYAxisExpLines import CYAxisExpLines from analysi...
JCSDA/mpas-jedi
graphics/analysis/Analyses.py
.py
23394004195712c2
7.45
7
#!/usr/bin/env python3 import basic_plot_functions as bpf import binning_utils as bu from copy import deepcopy import numpy as np import plot_utils as pu import var_utils as vu from analysis.category.CategoryBinMethodBase import CategoryBinMethodBase import analysis.StatisticsDatabase as sdb class BinValLines(Catego...
JCSDA/mpas-jedi
graphics/analysis/category/CYAxisBinValLines.py
.py
a9980b2513886532
7.45
7
#!/usr/bin/env python3 import basic_plot_functions as bpf from copy import deepcopy import numpy as np import plot_utils as pu import re from analysis.category.CategoryBinMethodBase import CategoryBinMethodBase import analysis.StatisticsDatabase as sdb class CYAxisFCLines(CategoryBinMethodBase): ''' Similar ...
JCSDA/mpas-jedi
graphics/analysis/category/CYAxisFCLines.py
.py
6ceeae69c5011a54
7.45
7
from __future__ import annotations from datetime import datetime, timezone from typing import Any from tinuous.base import WorkflowSpec from tinuous.circleci import CircleCI class FakeResponse: def __init__(self, data: dict[str, Any]) -> None: self.data = data def json(self) -> dict[str, Any]: ...
con/tinuous
test/test_circleci.py
.py
987d5d7393d49604
8.02
10
"""Adaptive Lighting integration in Home-Assistant.""" import logging from typing import Any import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import CONF_SOURCE from homeassistant.core import Even...
aronnebrivio/homeassistant-config
custom_components/adaptive_lighting/__init__.py
.py
3a9e2b0f4b629530
7.42
6
"""Utility functions for adaptation commands.""" import logging from collections.abc import AsyncGenerator from dataclasses import dataclass from enum import IntFlag, auto from typing import Any from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_BRIGHTNESS_PCT, ATTR_BRIGHTNESS_STEP, AT...
aronnebrivio/homeassistant-config
custom_components/adaptive_lighting/adaptation_utils.py
.py
2b550c0adeae0bea
7.42
6
"""Config flow for Adaptive Lighting integration.""" import logging from typing import Any import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_NAME from homeassistant.core import callback from homeassistant.helpers.selector import EntitySelector, EntitySelectorConfig...
aronnebrivio/homeassistant-config
custom_components/adaptive_lighting/config_flow.py
.py
27e0e11e5eb299e8
7.42
6
"""Utility functions for HA core.""" import logging from collections.abc import Awaitable, Callable from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.helpers import device_registry, entity_registry from homeassistant.util.read_only_dict import ReadOnlyDict from .adaptation_utils import Ser...
aronnebrivio/homeassistant-config
custom_components/adaptive_lighting/hass_utils.py
.py
77b06520d8e1dede
7.42
6
"""Helper functions for the Adaptive Lighting custom components.""" from __future__ import annotations import base64 import math from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from homeassistant.core import HomeAssistant def clamp(value: float, minimum: float, maximum: float) -> float: """Clamp va...
aronnebrivio/homeassistant-config
custom_components/adaptive_lighting/helpers.py
.py
2ab7962cb9f40348
7.42
6
"""Adds config flow for HACS.""" from __future__ import annotations import asyncio from contextlib import suppress from typing import TYPE_CHECKING from aiogithubapi import ( GitHubDeviceAPI, GitHubException, GitHubLoginDeviceModel, GitHubLoginOauthModel, ) from aiogithubapi.common.const import OAUTH...
aronnebrivio/homeassistant-config
custom_components/hacs/config_flow.py
.py
441a9c4db4479e4c
7.42
6
"""Coordinator to trigger entity updates.""" from __future__ import annotations from collections.abc import Callable from typing import Any from homeassistant.core import CALLBACK_TYPE, callback from homeassistant.helpers.update_coordinator import BaseDataUpdateCoordinatorProtocol class HacsUpdateCoordinator(BaseD...
aronnebrivio/homeassistant-config
custom_components/hacs/coordinator.py
.py
57de5e25dac992af
7.42
6
"""HACS Data client.""" from __future__ import annotations import asyncio from typing import Any from aiohttp import ClientSession, ClientTimeout import voluptuous as vol from .exceptions import HacsException, HacsNotModifiedException from .utils.logger import LOGGER from .utils.validate import ( VALIDATE_FETCH...
aronnebrivio/homeassistant-config
custom_components/hacs/data_client.py
.py
6ce3f09c893ece99
7.42
6
"""HACS Base entities.""" from __future__ import annotations from typing import TYPE_CHECKING, Any from homeassistant.core import callback from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import E...
aronnebrivio/homeassistant-config
custom_components/hacs/entity.py
.py
fd47a707af90bae2
7.42
6
"""Helper constants.""" # pylint: disable=missing-class-docstring from enum import StrEnum class HacsGitHubRepo(StrEnum): """HacsGitHubRepo.""" DEFAULT = "hacs/default" INTEGRATION = "hacs/integration" class HacsCategory(StrEnum): APPDAEMON = "appdaemon" INTEGRATION = "integration" LOVELAC...
aronnebrivio/homeassistant-config
custom_components/hacs/enums.py
.py
7ce438a20360293c
7.42
6
import logging import os from enum import IntEnum log = logging.getLogger(__name__) """ Namespace containing various enums and constants used elsewhere within the application. @todo consider making "common" a package (directory), and each of these classes can be modules (files) within it """ VERSION = "4.2....
WasatchPhotonics/ENLIGHTEN
enlighten/common.py
.py
e9c42d764b0894d7
7.45
7
import logging import re log = logging.getLogger(__name__) class ColorNames: """ These are colors we can reference by name in .ini files or elsewhere. The static ColorNames lookups have been extracted out of Colors, in part so Configuration can "have" a ColorNames without needing a full Colors o...
WasatchPhotonics/ENLIGHTEN
enlighten/data/ColorNames.py
.py
9c7fd0bd2e8fe7d3
7.45
7
import logging import numpy as np from datetime import datetime from collections import deque log = logging.getLogger(__name__) ## # Encapsulates a "moving window" dataset such as used for detector temperature, # laser temperature, battery charge, battery temperature, ambient temperature etc. # # @todo We may need ...
WasatchPhotonics/ENLIGHTEN
enlighten/data/RollingDataSet.py
.py
066d9c6a89ee6798
7.45
7
import logging from enlighten.EnlightenFeature import EnlightenFeature log = logging.getLogger(__name__) class BatteryFeature(EnlightenFeature): """ @todo track battery state in SpectrometerApplicationState to support multiple connected spectrometers """ def __init__(self, ctl): super().__in...
WasatchPhotonics/ENLIGHTEN
enlighten/device/BatteryFeature.py
.py
1bdd1980d19be364
7.45
7
import logging from wasatch.SpectrometerState import SpectrometerState from enlighten.EnlightenFeature import EnlightenFeature log = logging.getLogger(__name__) class ExternalTriggerFeature(EnlightenFeature): """ Encapsulate external hardware triggering. """ def __init__(self, ctl): supe...
WasatchPhotonics/ENLIGHTEN
enlighten/device/ExternalTriggerFeature.py
.py
6d9ca43f647d40cd
7.45
7
from .. import util import logging log = logging.getLogger(__name__) from enlighten.ui.ScrollStealFilter import ScrollStealFilter from enlighten.ui.MouseWheelFilter import MouseWheelFilter from enlighten.EnlightenFeature import EnlightenFeature class GainDBFeature(EnlightenFeature): """ This class encapsulat...
WasatchPhotonics/ENLIGHTEN
enlighten/device/GainDBFeature.py
.py
f8d2e6a922a2431a
7.45
7
import logging from enlighten.EnlightenFeature import EnlightenFeature log = logging.getLogger(__name__) class MultiPos(EnlightenFeature): """ Used for spectrometers with articulated optics. Note that this class is not currently instantiated by BusinessObjects, and would not work as enlighten_lay...
WasatchPhotonics/ENLIGHTEN
enlighten/device/MultiPos.py
.py
fb570b84a8321535
7.45
7
import logging from enlighten.common import LaserStates log = logging.getLogger(__name__) ## # These are things that are very much ENLIGHTEN-specific and not generic # enough to be in Wasatch.PY's SpectrometerState. That class is for spectrometer # state that "any" Python-based spectroscopy app is likely to need, a...
WasatchPhotonics/ENLIGHTEN
enlighten/device/SpectrometerApplicationState.py
.py
797df09d7ba54c67
7.95
7
import os import re import logging from html import escape from pygtail import Pygtail from wasatch import applog from enlighten import common from enlighten.util import unwrap from enlighten.EnlightenFeature import EnlightenFeature if common.use_pyside2(): from PySide2 import QtCore, QtGui else: from PySid...
WasatchPhotonics/ENLIGHTEN
enlighten/file_io/LoggingFeature.py
.py
d69013bb3f61c805
7.45
7
import queue import re from subprocess import Popen, PIPE import threading from pathlib import Path from typing import AnyStr, IO, List import discord from discord.ext import commands from discord import option from utils.check_channel_access import access_check class DfrotzRunner(commands.Cog): """ This will o...
jp00p/AGIMUS
cogs/chaoszork.py
.py
ca2366f2bd7b681e
7.57
13
import math import time import pytz from common import * from utils.check_channel_access import access_check command_config = config["commands"]["slots spin"] # Set up Slot Choices slot_choices = [ discord.OptionChoice(name=show, value=show.upper()) for show in command_config["parameters"][0]["allowed"] ] clas...
jp00p/AGIMUS
cogs/slots.py
.py
297356c7d35552f9
7.57
13
import wolframalpha from handlers.xp import grant_xp from common import * WOLFRAM_ALPHA_ID = os.getenv('WOLFRAM_ALPHA_ID') wa_client = None if WOLFRAM_ALPHA_ID: wa_client = wolframalpha.Client(WOLFRAM_ALPHA_ID) command_config = config["commands"]["computer"] async def computer(message:discord.Message): if not ...
jp00p/AGIMUS
commands/computer.py
.py
58bd218ce702cb9c
7.57
13
#!/usr/bin/env -S python3 -B # # count-action-users: Generates Shields endpoint with number of users of a GitHub Action # # Copyright (c) 2021-2023 Vincent A Cicirello # https://www.cicirello.org/ # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
cicirello/count-action-users
ActionUserCounter.py
.py
027bab6fd077db05
7.54
11
# count-action-users: Generates Shields endpoint with number of users of a GitHub Action # # Copyright (c) 2021 Vincent A Cicirello # https://www.cicirello.org/ # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "...
cicirello/count-action-users
tests/tests.py
.py
91a59843752f867c
7.04
11
#!/usr/bin/env python3 """MAC Address Spoofer - CLI entry point.""" import asyncio from rich import print from macspoofer.modules.args_parser import ArgumentParser from macspoofer.modules.error_config import configure_tracebacks from macspoofer.spoofer import run_spoofer_logic from macspoofer.utils.exceptions import...
DanielKirshner/MacSpoofer
macspoofer/cli.py
.py
4e019fe26f5a01b5
7.54
11
"""Command-line argument parsing for MAC Address Spoofer.""" import argparse from dataclasses import dataclass import art from macspoofer import __version__ @dataclass class SpooferArgs: """Parsed command-line arguments for the spoofer.""" interface: str auto: bool = False ci: bool = False class...
DanielKirshner/MacSpoofer
macspoofer/modules/args_parser.py
.py
594dcd3574c1d59d
7.54
11
"""Network interface management for MAC spoofing.""" import contextlib import os from collections.abc import AsyncIterator from enum import StrEnum from macspoofer.utils import shell_utils from macspoofer.utils.exceptions import CustomException, ErrorCode SYSFS_NET_PATH = "/sys/class/net" class InterfaceState(StrE...
DanielKirshner/MacSpoofer
macspoofer/modules/interface.py
.py
434ed3dcf320bf96
7.54
11
"""MAC Address Spoofer - Core spoofing logic and TUI.""" import asyncio import sys import art from rich import print from macspoofer.modules.args_parser import SpooferArgs from macspoofer.modules.interface import NetworkInterface from macspoofer.utils import shell_utils from macspoofer.utils.exceptions import Custom...
DanielKirshner/MacSpoofer
macspoofer/spoofer.py
.py
0b2602d1c96c5689
7.54
11
"""Custom exceptions and error codes for MacSpoofer.""" from enum import IntEnum class ErrorCode(IntEnum): """Error codes for expected MacSpoofer failures, grouped by subsystem.""" # Shell command execution COMMAND_EXECUTION_FAILED = 1000 COMMAND_NOT_FOUND = 1001 # Environment prerequisites ...
DanielKirshner/MacSpoofer
macspoofer/utils/exceptions.py
.py
f7cc046bce68fccd
7.54
11
"""Random MAC address generation utilities.""" import random from enum import Enum class HexValuesLength(Enum): """Defines the length of different MAC address components.""" MAC_ADDRESS = 12 # Full MAC address (6 bytes = 12 hex chars) OUI = 6 # Organizationally Unique Identifier (3 bytes) NIC = 6 ...
DanielKirshner/MacSpoofer
macspoofer/utils/random_utils.py
.py
d3aa00e92e76d1fd
7.54
11
"""Shell command utilities for system-level operations.""" import asyncio import os import sys from macspoofer.utils.exceptions import CustomException, ErrorCode def check_for_linux() -> bool: """Check if the current platform is Linux. Every system facility this tool relies on is Linux-specific: ``/sys...
DanielKirshner/MacSpoofer
macspoofer/utils/shell_utils.py
.py
ce87b67cb306e161
7.54
11
"""Vendor OUI (Organizationally Unique Identifier) registry. Loads vendor-to-OUI mappings from a JSON database generated by ``scripts/update_vendor_db.py`` (source: Wireshark manuf file). """ from __future__ import annotations import json from functools import cache from importlib import resources from macspoofer.u...
DanielKirshner/MacSpoofer
macspoofer/utils/vendors.py
.py
11736446053f0964
7.54
11
#!/usr/bin/env python3 """Update the vendor OUI database from Wireshark's manuf file. Downloads (or reads a local copy of) the Wireshark manufacturer database and produces a normalised JSON mapping used at runtime by VendorRegistry. Usage: python scripts/update_vendor_db.py # download late...
DanielKirshner/MacSpoofer
scripts/update_vendor_db.py
.py
13170606493ee72c
7.54
11
from pydantic import BaseModel, Field from parrot.tools.abstract import AbstractTool, ToolResult class WeatherLookupArgs(BaseModel): """Arguments for the WeatherLookupTool.""" city: str = Field(description="The name of the city") class WeatherLookupTool(AbstractTool): """ Retrieves current weather i...
phenobarbital/navigator-auth
.agent/skills/parrot-scaffold-tool/examples/WeatherTool.py
.py
4a217ef004d7815c
7.6
15
#!/usr/bin/env python3 """ HAR Filter - Filter HAR files to API-relevant entries only. This script removes static assets, analytics, tracking, and CDN resources from HAR files, keeping only API-relevant requests. Usage: python har_filter.py <input.har> --output <filtered.har> [--stats] """ import argparse import...
phenobarbital/navigator-auth
.agent/skills/reverse-engineering-api/scripts/har_filter.py
.py
dee3b6e43dda1834
7.6
15
#!/usr/bin/env python3 """ HAR Validator - Validate generated API client against HAR analysis. This script validates that a generated API client properly implements all endpoints found in the HAR analysis. Usage: python har_validate.py <api_client.py> <analysis.json> """ import argparse import ast import json im...
phenobarbital/navigator-auth
.agent/skills/reverse-engineering-api/scripts/har_validate.py
.py
f76b1c1e3dc10e10
7.6
15
from itertools import chain from aiohttp import web from navigator.views import BaseView from navigator_session import get_session from navigator_auth import AuthHandler from navigator_auth.abac.pdp import PDP from navigator_auth.abac.decorators import groups_protected from navigator_auth.abac.storages.pg import pgStor...
phenobarbital/navigator-auth
examples/test_abac.py
.py
4dc5f2b651ffec05
7.1
15
from aiohttp import web from navigator_auth.decorators import ( is_authenticated, user_session ) from navigator_auth import AuthHandler from navigator.views import BaseView from navigator import Application from navigator.responses import HTMLResponse # @is_authenticated() # @user_session() class ChatHandler(...
phenobarbital/navigator-auth
examples/test_decorators.py
.py
8364081732c6ed30
8.1
15
from typing import Any, Optional from collections.abc import MutableMapping, Iterator from aiohttp import web from datamodel import BaseModel # Lazy import to avoid circular dependency at module load time; # resolved at first EvalContext construction. _ABAC_TENANT_TRUST_HEADERS: Optional[bool] = None _ABAC_TENANT_HEAD...
phenobarbital/navigator-auth
navigator_auth/abac/context.py
.py
5c5fe47d97d2c115
7.6
15
from typing import Union, Optional, Any from aiohttp import web, hdrs from navconfig.logging import logger from navigator_auth.libs.json import json_encoder def default_headers(message: str, exception: BaseException = None) -> dict: headers = { "X-ABAC-RESPONSE": message, hdrs.CONNECTION: "keep-ali...
phenobarbital/navigator-auth
navigator_auth/abac/errors.py
.py
33b4f6e6de3275b8
7.6
15
import re import logging from dataclasses import dataclass, field from typing import Optional, List, Tuple, Any from navigator_auth.abac.policies.resource_policy import ResourcePolicy from navigator_auth.abac.policies.abstract import PolicyEffect from navigator_auth.abac.policies.resources import SubjectSpec logger = ...
phenobarbital/navigator-auth
navigator_auth/abac/policies/adapter.py
.py
d2a9df3dc30798ec
7.6
15
""" Environment model for PBAC evaluation. Provides rich environment context including day segments, business hours, and timezone awareness for time-based access control policies. """ from __future__ import annotations import datetime as _dt import time as _time_mod from enum import Enum from typing import Optional ...
phenobarbital/navigator-auth
navigator_auth/abac/policies/environment.py
.py
1e7b3ee2fbe643f6
7.6
15
from typing import Union from .abstract import PolicyEffect, PolicyResponse from ..context import EvalContext from .environment import Environment from .obj import ObjectPolicy class FilePolicy(ObjectPolicy): def is_allowed( self, ctx: EvalContext, env: Environment, ...
phenobarbital/navigator-auth
navigator_auth/abac/policies/file.py
.py
fa0692211a2f3624
7.6
15
from typing import List, Union, Dict, Set from navigator_auth.abac.policies.abstract import AbstractPolicy, PolicyEffect, PolicyResponse from navigator_auth.abac.context import EvalContext from navigator_auth.abac.policies.environment import Environment from navigator_auth.abac.policies.resources import ResourcePattern...
phenobarbital/navigator-auth
navigator_auth/abac/policies/resource_policy.py
.py
7876deec918df403
7.6
15
from aiohttp import web from datamodel import BaseModel from navigator_auth.handlers.model import ModelHandler from navigator_auth.abac.storages.pg import ModelPolicy from navigator_auth.abac.decorators import groups_protected class PolicyHandler(ModelHandler): """ CRUD Handler for ABAC Policies. """ ...
phenobarbital/navigator-auth
navigator_auth/abac/policyhandler.py
.py
bbdacb13fc202674
7.6
15
from abc import ABCMeta, abstractmethod class AbstractStorage(metaclass=ABCMeta): """AbstractStorage. Base class for Any Policy Storage. Raises: RuntimeError: Some exception raised. web.InternalServerError: Database connector is not installed. Returns: A collection of Polici...
phenobarbital/navigator-auth
navigator_auth/abac/storages/abstract.py
.py
cb39a183790116b0
7.1
15
"""DB (asyncdb) Extension. DB connection for any Application. """ from collections.abc import Callable from navconfig.logging import logging from asyncdb import AsyncDB from asyncdb.exceptions import ProviderError, DriverError from navigator_auth.exceptions import AuthException, ConfigError from .abstract import Abstra...
phenobarbital/navigator-auth
navigator_auth/abac/storages/db.py
.py
d588cb1499268656
7.6
15
from typing import Optional from uuid import UUID from datetime import datetime from asyncdb.models import Model, Field from navigator_auth.exceptions import ConfigError from .db import DBStorage class pgStorage(DBStorage): """pgStorage. Getting Policies from Postgres Database. """ driver: str = 'pg...
phenobarbital/navigator-auth
navigator_auth/abac/storages/pg.py
.py
f4d38d968abdbea9
7.6
15
"""Element cache for incremental build.""" import dbm import enum import itertools import json import os import time import typing as tg import zlib import base as b UNCOMPRESSED_LIMIT = 40 # length of longest string to store uncompressed ZLIB_WBITS = -15 Cacheable = str | list[str] | b.StrAnyDict # what can be pu...
fubinf/sedrila
py/cache.py
.py
fe92424d9748fb62
7.54
11
"""Simple facade for asymmetric encryption/decryption.""" import typing as tg import tempfile import shutil import os import subprocess import gnupg def encrypt_gpg(plaintext: bytes, fingerprints: tg.Iterable[str], pubkey_data: dict | None = None) -> bytes: """ Encrypts data asymmetrically wi...
fubinf/sedrila
py/mycrypt.py
.py
f57d081deaf617e0
7.54
11
import os import argparse_subcommand as ap_sub class SedrilaArgParser(ap_sub.ArgumentParser): """One-trick pony class for obtaining the expensive description only when needed.""" def format_help(self): self.description = f"sedrila {self.get_version()}: Tool for 'self-driven lab' (SeDriLa) university...
fubinf/sedrila
py/sdrl/argparser.py
.py
698c1e825f969554
7.54
11
""" CourseSI: Course subclass for student and instructor subcommands. """ import calendar import dataclasses import datetime as dt import typing as tg import base as b import sdrl.course from sdrl.course import Course, Chapter, Taskgroup, Task @dataclasses.dataclass class BonusPeriodResult: period_num: int ...
fubinf/sedrila
py/sdrl/course_si.py
.py
d27c60413d4e368a
7.54
11
"""Combined Elements registry/factory and build orchestrator.""" import itertools import base as b import typing as tg class Directory: """ Each Element is registered here and can be accessed by type and name. The Builder knows when to build each and builds them in an order such that when a Product...
fubinf/sedrila
py/sdrl/directory.py
.py
e1125069ebcd10dc
7.54
11
"""Data structure, macros, and page generation for a glossary page (term dictionary and cross-reference)""" import re import typing as tg import base as b import cache import sdrl.constants as c import sdrl.elements as el import sdrl.macros as macros import sdrl.markdown as md import sdrl.partbuilder class Glossary(...
fubinf/sedrila
py/sdrl/glossary.py
.py
e5a0f9b0575bbc82
7.54
11
"""sedrila-specific HTML generation helper routines.""" import sdrl.constants as c difficulty_levels = ('verylow', 'low', 'medium', 'high') def as_attribute(text: str) -> str: """Cleans text so that it can appear between double quotes in an HTML attribute.""" return text.replace('"', "'").replace("\n", " ") ...
fubinf/sedrila
py/sdrl/html.py
.py
26cb5376deda5d5b
7.54
11
""" Command protocol checker for SeDriLa courses. Parses @PROT_SPEC blocks, validates them, and compares author/student protocol files. """ import os import re import typing from dataclasses import dataclass import base as b import mycrypt @dataclass class CheckRule: """Rule parsed from a single @PROT_SPEC bloc...
fubinf/sedrila
py/sdrl/protocolchecker.py
.py
26a849375473b12a
7.54
11
""" Heuristic 'rename' refactoring on SeDriLa courses: - given an old and a new partname, - rename all matching dirs first (exploiting the fact that partnames are globally unique, even across part types), - rename all matching files - apply precise replacements in *.md files: mentions in 'assumes:', 'requires:', PA...
fubinf/sedrila
py/sdrl/rename.py
.py
654a7b67fe3db6a3
7.54
11
""" Manage the replacements data for the <replacement id='abcde'>...</replacement> markdown extension It comes from a file that contains as many such <replacement> groups as needed, separated by whatever, e.g. two empty lines. """ import re import base as b replacement_expr_re = r"<replacement +?id=[\'\"]([\w_-]+?)[\...
fubinf/sedrila
py/sdrl/replacements.py
.py
dea4b674741bc731
7.54
11
"""Reports with statistics of course (for author) or student work (for student and instructor).""" import dataclasses import datetime as dt import typing as tg import base as b import sdrl.html as h if tg.TYPE_CHECKING: import sdrl.course import sdrl.course_si import sdrl.participant @dataclasses.datacl...
fubinf/sedrila
py/sdrl/report.py
.py
ce8e69af61ec0ac0
7.54
11
""" Snippet extraction and inclusion functionality for sedrila. Allows extracting code snippets from solution files and including them in task files. """ import dataclasses import os import re from typing import Callable, Optional import base as b import sdrl.constants as c import sdrl.macros as macros IDENTIFIER_RE ...
fubinf/sedrila
py/sdrl/snippetchecker.py
.py
e37db3a4b0513267
7.54
11
""" server pseudo-role: development-only, non-robust, barely protected webserver for serving a file tree created by 'sedrila author'. """ import http.server import os import sys import click import argparse_subcommand as ap_sub # CLI: sedrila server @click.command(name="server") @click.option("--quiet", "-q", is_f...
fubinf/sedrila
py/sdrl/subcmd/server.py
.py
60ea86619eca66d6
7.54
11
"""student role: submit tasks to instructor or view status""" import argparse from collections.abc import Sequence import contextlib import os import readline # noqa, is active automatically for input() import types import typing as tg import blessed import click import base as b import sgit import sdrl.constants as...
fubinf/sedrila
py/sdrl/subcmd/student.py
.py
6f2af66763446813
7.54
11
import re import unittest.mock as mock import sdrl.argparser as ap def test_get_version_returns_semver_string(): """get_version() reads pyproject.toml and returns a semantic version.""" version = ap.SedrilaArgParser.get_version() assert re.match(r'^\d+\.\d+\.\d+', version), f"unexpected version format: {...
fubinf/sedrila
py/sdrl/tests/argparser_test.py
.py
c2f9eaa8b5917405
8.04
11
# pytest tests for bonus/anti-procrastination logic. import datetime as dt import unittest.mock import pytest import base as b import sdrl.course import sdrl.course_si # ----- helpers ----- MINIMAL_CONFIGDICT = dict( title='Test Course', name='test', instructors=[dict(nameish='Test', email='test@t.de', ...
fubinf/sedrila
py/sdrl/tests/bonus_test.py
.py
5ca15e1a852f95b0
8.04
11
# pytest tests import contextlib import itertools import os import tempfile import textwrap # for code format import pytest import base as b import cache import sdrl.constants as c import sdrl.course import sdrl.coursebuilder import sdrl.directory as dir import sdrl.elements import sdrl.linkchecker as linkchecker impo...
fubinf/sedrila
py/sdrl/tests/linkchecker_test.py
.py
a6ba2bc0aafeb6d0
7.04
11
# -*- coding: utf-8 -*- """ Created on Mon Oct 24 10:11:36 2022 @author: ruzhu """ import time import cplex import numpy as np import pandas as pd from docplex.mp.model import Model from numdifftools import Jacobian from scipy.linalg import fractional_matrix_power from scipy.optimize import minimize from sklearn.dat...
DTUWindEnergy/hydesign
hydesign/HiFiEMS/DRO.py
.py
3d9e53314899fac9
7.42
6
# -*- coding: utf-8 -*- """ Created on Mon Nov 8 11:37:55 2021 @author: ruzhu """ import math import numpy as np import pandas as pd import rainflow from numpy import matlib as mb # import random # import matplotlib.pyplot as pltfrom docplex.mp.model import Model def Linear_Part( whole_SoC, kdelta1, k...
DTUWindEnergy/hydesign
hydesign/HiFiEMS/Deg_Calculation.py
.py
5f3c325564148686
7.42
6
# basic libraries import os import numpy as np import openmdao.api as om from hydesign.assembly.hpp_assembly import hpp_base from hydesign.costs.costs import battery_cost_comp as battery_cost from hydesign.costs.costs import pvp_cost_comp as pvp_cost from hydesign.costs.costs import shared_cost_comp as shared_cost fr...
DTUWindEnergy/hydesign
hydesign/assembly/hpp_assembly_hifi_dems.py
.py
96d73bf095c8af4a
7.42
6
"""Compatibility wrapper for the legacy PV-hybridization assembly. This module now delegates to the unified base assembly implementation. """ import warnings from hydesign.assembly.hpp_assembly import hpp_model as _base_hpp_model class hpp_model(_base_hpp_model): """Backward-compatible alias to the unified bas...
DTUWindEnergy/hydesign
hydesign/assembly/hpp_assembly_hybridization_pv.py
.py
3abf0caf83e17981
7.42
6
"""Compatibility wrapper for the legacy wind-hybridization assembly. This module now delegates to the unified base assembly implementation. """ import warnings from hydesign.assembly.hpp_assembly import hpp_model as _base_hpp_model class hpp_model(_base_hpp_model): """Backward-compatible alias to the unified b...
DTUWindEnergy/hydesign
hydesign/assembly/hpp_assembly_hybridization_wind.py
.py
4dd410fd27451209
7.42
6
import openmdao.api as om from hydesign.openmdao_wrapper import ComponentWrapper class shared_cost: """Pure Python Electrical infrastructure and land rent cost model""" def __init__(self, hpp_BOS_soft_cost, hpp_grid_connection_cost, land_cost): """Initialization of the shared costs model Pa...
DTUWindEnergy/hydesign
hydesign/costs/costs_hybridized_pv.py
.py
342e0ac7f9af5ab2
7.42
6
import openmdao.api as om from hydesign.openmdao_wrapper import ComponentWrapper class shared_cost: """Electrical infrastructure and land rent cost model""" def __init__(self, hpp_BOS_soft_cost, hpp_grid_connection_cost, land_cost): """Initialization of the shared costs model Parameters ...
DTUWindEnergy/hydesign
hydesign/costs/costs_hybridized_wind.py
.py
bae987f823f8c8f9
7.42
6
import json import warnings from pathlib import Path from persona.lib.format import clean_location from persona.lib.generate import preprocess_location_data DATA_DIR = Path(__file__).parent.parent / "data" def load_location_data() -> dict: # A directory may hold a leaf dataset ("<name>.json"), a "composite.json...
tom-draper/persona
src/persona/api/handler.py
.py
2415036381cba275
7.52
10
# Only aliases that resolve to a dataset belong here. Names that already match # a data directory once lowercased and underscored (united_kingdom, global, # united_states_of_america) resolve without an entry. alias = { "uk": "united_kingdom", "great_britain": "united_kingdom", "gb": "united_kingdom", "b...
tom-draper/persona
src/persona/lib/format.py
.py
bd97628668acff7c
7.52
10
""" Structural checks over the bundled demographic datasets. These guard the data itself rather than the generation logic: every dataset must parse, attribute all of its features to a source, and carry probability distributions that actually look like distributions. Run with: pytest """ import itertools import json ...
tom-draper/persona
tests/test_data_integrity.py
.py
2ca81505daf35d6e
8.02
10
from dataclasses import asdict from functools import partial from http import HTTPStatus from typing import Any from shared.application import MESHLambdaApplication from shared.common import SingletonCheckFailure, return_failure, singleton_check from shared.send_parameters import get_send_parameters from spine_aws_com...
NHSDigital/terraform-aws-mesh-client
src/mesh_check_send_parameters_application.py
.py
ca2d63a88ca69307
7.42
6
from http import HTTPStatus from typing import Any from aws_lambda_powertools.shared.functions import strtobool from requests import HTTPError from shared.application import MESHLambdaApplication from shared.common import SingletonCheckFailure, return_failure, singleton_check class HandshakeFailure(Exception): "...
NHSDigital/terraform-aws-mesh-client
src/mesh_poll_mailbox_application.py
.py
3e4c24710f417acf
7.42
6
from collections.abc import Generator from dataclasses import asdict from functools import partial from http import HTTPStatus from io import BytesIO from typing import Any from mypy_boto3_s3.service_resource import Object from shared.application import MESHLambdaApplication from shared.common import SingletonCheckFai...
NHSDigital/terraform-aws-mesh-client
src/mesh_send_message_chunk_application.py
.py
c791a97dd50d46f8
7.42
6
import json import os from collections.abc import Callable from urllib.parse import quote_plus from mypy_boto3_secretsmanager import SecretsManagerClient from mypy_boto3_ssm import SSMClient from mypy_boto3_stepfunctions import SFNClient from nhs_aws_helpers import secrets_client, ssm_client, stepfunctions BOOL_TRUE_...
NHSDigital/terraform-aws-mesh-client
src/shared/common.py
.py
19a9913acf0d7d83
7.42
6
""" Configuration control dataclasses for GlaMBIE. """ from dataclasses import dataclass from typing import Literal import yaml import logging from abc import ABC, abstractclassmethod from glambie.const.constants import ( ExtractTrendsMethod, YearType, SeasonalCorrectionMethod, ) from glambie.config.yaml_h...
earthwave/glambie
glambie/config/config_classes.py
.py
ec6d9564e2f5f0dc
7.52
10
from enum import Enum from glambie.const.constants import YearType from glambie.const.data_groups import GlambieDataGroup import yaml def enum_class_representer( yaml_dumper: yaml.dumper.Dumper, object_to_represent: Enum ) -> yaml.nodes.ScalarNode: """Represent any Enum as its value.""" return yaml_dumper...
earthwave/glambie
glambie/config/yaml_helpers.py
.py
c3ad8008f6911312
7.52
10