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 |
|---|---|---|---|---|---|---|
# Copyright 2016-2018 Scality
#
# 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,... | scality/bert-e | bert_e/server/doc.py | .py | 006b5e6ede33169e | 7.15 | 1 |
#!/usr/bin/env python3
"""
Script to calculate basic statistics for NASA contracts by fiscal year.
For each given fiscal year, this script will:
1. Calculate sum total of all obligations grouped by month of Award Date
2. Count new awards (Modification 0) by category by month
Usage:
python award_stats.p... | planetary-society/nasa-contracts | award_stats.py | .py | 3fb4b6dea731dd75 | 7.3 | 3 |
#!/usr/bin/env python3
"""
Fetch NASA Procurement Data View exports for specified fiscal years.
Each fiscal year is written to a separate CSV with derived State and District
columns and the two currency columns rewritten as plain whole-dollar integers.
Source field text is otherwise preserved verbatim.
"""
import arg... | planetary-society/nasa-contracts | fetch-contracts.py | .py | 4fafa3b4d0ed6939 | 7.3 | 3 |
# SPDX-FileCopyrightText: 2019 Snoonet
# SPDX-FileCopyrightText: 2020-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""
Utility functions for working with asyncio
"""
import asyncio
from collections.abc import Awaitable, Callable
from datetime import timedelta
from functools import ... | TotallyNotRobots/bnc-bot | bncbot/async_util.py | .py | f03449046eacddf6 | 7.15 | 1 |
# SPDX-FileCopyrightText: 2019 Snoonet
# SPDX-FileCopyrightText: 2020-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
import hashlib
import random
import secrets
import string
from collections.abc import Iterable
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
... | TotallyNotRobots/bnc-bot | bncbot/util.py | .py | c44e3574e3d259b5 | 7.15 | 1 |
"""
This script adds a new indicator to this implementation of Open SDG.
Usage example: the following would add 1.1.z, called "My indicator name",
as a new indicator:
python scripts/batch/add_indicator.py 1.1.z "My indicator name"
What this script actually does:
1. This script creates a file in the _indicators/ f... | armstat/sdg-site-armenia | scripts/batch/add_indicator.py | .py | b96e5017d3225084 | 7 | 0 |
"""
This script adds a new language to this implementation of Open SDG.
Usage example: the following would add Spanish (es) as a new language:
python scripts/batch/add_language.py es
What this script actually does:
1. This script creates new copies of all goals, indicators, and pages, in the new
language.
What t... | armstat/sdg-site-armenia | scripts/batch/add_language.py | .py | 3116895ab19b80c9 | 7 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Exceptions raised by the library."""
from typing import TYPE_CHECKING, AnyStr
if TYPE_CHECKING:
from polymatch.base import AnyPattern
__all__ = [
"DuplicateMatcherRegistrationError",
"NoMat... | TotallyNotRobots/poly-match | polymatch/error.py | .py | 8ac7dd10957dcbe0 | 7 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Glob pattern matcher."""
from fnmatch import translate
from typing import TYPE_CHECKING, AnyStr
from polymatch.matchers.regex import RegexMatcher
if TYPE_CHECKING:
import regex
class GlobMatcher(... | TotallyNotRobots/poly-match | polymatch/matchers/glob.py | .py | 053fb44e7c32c6b2 | 7 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Pattern matcher registry.
This also implements parsing the pattern from a simple string e.g.:
>>> from polymatch.registry import pattern_registry
>>> pat = pattern_registry.pattern_from_string("c... | TotallyNotRobots/poly-match | polymatch/registry.py | .py | e0fe57819293cc13 | 7 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Test base patterns."""
import pytest
from polymatch import pattern_registry
from polymatch.base import CaseAction
from polymatch.error import (
PatternNotCompiledError,
PatternTextTypeMismatchEr... | TotallyNotRobots/poly-match | tests/base_test.py | .py | db90cb97887cbd89 | 7.5 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Test glob matcher."""
import pytest
from polymatch import pattern_registry
data = (
("glob::*", "", True),
("glob::*?", "", False),
("glob::*?", "a", True),
("glob:cf:*!*@thing", "itd!a... | TotallyNotRobots/poly-match | tests/test_glob.py | .py | 8b6c7468ffff23ac | 7.5 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Test regex matcher."""
import pytest
from polymatch import pattern_registry
data = (
(r"regex::\btest\b", "test", True),
(r"regex::\btest\b", "test1", False),
(r"regex::\btest\b", "test res... | TotallyNotRobots/poly-match | tests/test_regex.py | .py | f72dfe961d08470f | 7.5 | 0 |
# SPDX-FileCopyrightText: 2018-present linuxdaemon <linuxdaemon.irc@gmail.com>
#
# SPDX-License-Identifier: MIT
"""Test the pattern registry."""
import pytest
from polymatch import pattern_registry
from polymatch.base import CaseAction
from polymatch.error import (
DuplicateMatcherRegistrationError,
NoMatche... | TotallyNotRobots/poly-match | tests/test_registry.py | .py | 14416c4735005b75 | 7.5 | 0 |
import logging
from contextlib import contextmanager
from pathlib import Path
from tempfile import NamedTemporaryFile
import requests
from insights import extract as extract_archive
from opentelemetry import trace
from ..telemetry import get_tracer
from ..utils import config, metrics
from .profile import get_system_p... | RedHatInsights/insights-puptoo | src/puptoo/process/__init__.py | .py | ef6c7fbfc98efdbd | 7.39 | 5 |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashMap = {}
for i, num in enumerate(nums):
hashMap[num] = i
for i, num in enumerate(nums):
other = targe... | damiangao/LeetCode_Notes | 1.py | .py | 80f637ac086ac86f | 7.3 | 3 |
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
curr_layer_count = 1
next_layer_count = 0
if not root:
return res
q = deque()
q.append(root)
cu... | damiangao/LeetCode_Notes | 107.py | .py | 34dc1df92c80f7e2 | 7.3 | 3 |
# elegant solution
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = 10 ** 4
max_profit = 0
for x in prices:
max_profit = max(max_profit, x - min_price)
min_price = min(min_price, x)
return max_profit
class Solution(object):
def ... | damiangao/LeetCode_Notes | 121.py | .py | 17200a9c68aefa9a | 7.3 | 3 |
class Solution(object):
def findKthPositive(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
# max_num = arr[-1]
# lost = max_num - len(arr)
lost = []
i = 1
j = 0
while i <= len(arr) + k:
if j >= ... | damiangao/LeetCode_Notes | 1539.py | .py | a78c512cb82b0338 | 7.3 | 3 |
# solution1
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
len1, len2 = 0, 0
tempA, tempB = headA, headB
while tempA:
tempA = tempA.next
len1 += 1
... | damiangao/LeetCode_Notes | 160.py | .py | dba92f8b2b8da173 | 7.3 | 3 |
# Libraries
import os
from collections import Counter
import pandas as pd
from gensim.models import FastText, Word2Vec
# Define locations
corpusdir = "corpora"
modeldir = 'models'
# Languages whose script doesn't separate words with whitespace at all, so
# a plain split(' ') collapses each line to ~1 token (confirmed... | SemanticPriming/word2manylanguages | 02_model_training/model_training.py | .py | c7172df937b64858 | 7 | 0 |
"""Parse the Zenodo DOI source table into a clean, machine-readable list.
The source (source/dataset_list_source.pdf) is a multi-page table, one row
per language, where languages split across several Zenodo uploads have their
DOIs crammed into a single cell as free text ("Part 1: ...\\nPart 2: ...", or
for some langua... | SemanticPriming/word2manylanguages | download/build_dataset_list.py | .py | ebbebe7a4c79b160 | 7 | 0 |
"""Shared helpers for talking to the project's Zenodo records.
Used by both build_dataset_list.py (regenerating the DOI/file tables) and
zenodo_download.py (downloading model files) so the two agree on what counts
as a model file and how split files are grouped back together.
"""
import re
import requests
# Model f... | SemanticPriming/word2manylanguages | download/zenodo_common.py | .py | f6936e724e49ab13 | 7 | 0 |
"""Download trained model files from the project's Zenodo archives.
Reads zenodo_dois.csv (built by build_dataset_list.py from
source/dataset_list_source.pdf) to find which Zenodo record(s) hold a given
language's files. Languages whose files didn't fit in a single upload are
split across multiple records ("parts"); t... | SemanticPriming/word2manylanguages | download/zenodo_download.py | .py | b834435b0607df8c | 7 | 0 |
"""
Builds unigram frequency counts for every language directly from this
project's own cleaned/deduplicated corpus, rather than relying on
download/README.md's section 3 (eval_inputs/counts/, mirrored from van
Paridon & Thompson's subs2vec frequency_source/) -- so the frequency
baseline is always self-consistent with ... | SemanticPriming/word2manylanguages | eval_inputs/build_counts_tokenized.py | .py | 753c0bf366d9951f | 7 | 0 |
"""
Progress tracker for the 59-language word2manylanguages pipeline.
For each language, checks:
- models/ : how many of the 60 trained model files exist
(5 dims x 6 windows x 2 algos)
- eval_results/counts : whether the frequency-counts eval file exists,
... | SemanticPriming/word2manylanguages | progress_tracker.py | .py | 6ed69ea0e73c8132 | 7 | 0 |
"""End-to-end intent-routing tests for ovos-skill-number-facts (en-US).
These assert *per-utterance* that the Adapt pipeline routes an utterance to the
right trivia handler and that the skill speaks the fact back. They deliberately
use subset assertions over the captured message stream rather than a strict
full-sequen... | OpenVoiceOS/ovos-skill-number-facts | test/end2end/test_intents_en_us.py | .py | de7890fb45e353a1 | 7.65 | 1 |
#!/usr/bin/env python3
"""
Instagram APOD Example
Simple example showing how to fetch APOD data and prepare it for Instagram posting.
This is a test/demo version that doesn't actually post to Instagram.
"""
import os
import sys
from pathlib import Path
# Add the pyasan package to the path
sys.path.insert(0, str(Path... | jeorryb/pyasan | examples/instagram_example.py | .py | fe162d432a080022 | 7.15 | 1 |
"""Base NASA API client."""
from typing import Dict, Any, Optional
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from .config import Config
from .exceptions import APIError, AuthenticationError, RateLimitError
class NASAClient:
"""Base client fo... | jeorryb/pyasan | pyasan/client.py | .py | 5010c8f1d44412f4 | 7.15 | 1 |
"""Configuration management for PyASAN."""
import os
from typing import Optional
from dotenv import load_dotenv
from .exceptions import ConfigurationError
class Config:
"""Configuration manager for NASA API credentials and settings."""
def __init__(self, api_key: Optional[str] = None, load_env: bool = True... | jeorryb/pyasan | pyasan/config.py | .py | c1d7cc9255d3e488 | 7.15 | 1 |
"""Data models for NASA Mars Rover Photos API responses."""
from datetime import datetime
from datetime import date as date_type
from typing import List, Any
from enum import Enum
from pydantic import BaseModel, Field, field_validator
class RoverName(str, Enum):
"""Supported Mars rovers."""
PERSEVERANCE = "... | jeorryb/pyasan | pyasan/mars_models.py | .py | 41185ba48bb0e6e0 | 7.15 | 1 |
"""Data models for NASA API responses."""
from datetime import datetime
from datetime import date as date_type
from typing import Optional, List, Any
from pydantic import BaseModel, Field, field_validator
class APODResponse(BaseModel):
"""Model for APOD API response."""
title: str = Field(..., description="... | jeorryb/pyasan | pyasan/models.py | .py | a712fd53571907e2 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Instagram Token Expiry Checker
Exits non-zero if the token is expired or has fewer than WARNING_DAYS remaining.
Used as a pre-flight check in the daily APOD workflow.
"""
import os
import sys
import requests
from datetime import datetime
WARNING_DAYS = 7 # Warn (and fail the job) when thi... | jeorryb/pyasan | scripts/check_token_expiry.py | .py | cecd72126956a625 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Generate a Long-Lived Instagram Access Token
This script helps you convert a short-lived token to a long-lived (60-day) token.
"""
import os
import sys
import requests
from pathlib import Path
# Add the pyasan package to the path
sys.path.insert(0, str(Path(__file__).parent.parent))
def ... | jeorryb/pyasan | scripts/get_new_long_lived_token.py | .py | a1a1e6373a225c2f | 7.15 | 1 |
#!/usr/bin/env python3
"""
Release script for PyASAN.
This script helps automate the release process by:
1. Updating version numbers in all relevant files
2. Creating a git tag
3. Pushing to GitHub (which triggers PyPI publication)
"""
import os
import re
import sys
import subprocess
from pathlib import Path
def ge... | jeorryb/pyasan | scripts/release.py | .py | 6154ec33d324b188 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Instagram Token Renewal Script
Automatically checks Instagram access token expiry and renews it if needed.
Designed to run in GitHub Actions with automatic secret updates.
"""
import os
import sys
import json
import requests
import logging
import base64
from datetime import datetime, timede... | jeorryb/pyasan | scripts/renew_instagram_token.py | .py | 3452325fffe5886e | 7.15 | 1 |
"""Tests for APOD client."""
import pytest
from datetime import date
from unittest.mock import patch
from pyasan.apod import APODClient
from pyasan.exceptions import ValidationError
from pyasan.models import APODResponse
class TestAPODClient:
"""Test cases for APODClient."""
def test_init(self):
""... | jeorryb/pyasan | tests/test_apod.py | .py | 3f177253dcfc7b11 | 7.65 | 1 |
"""Tests for Mars Rover Photos client."""
import pytest
from datetime import date as date_type
from unittest.mock import patch
from pyasan.mars import MarsRoverPhotosClient
from pyasan.mars_models import RoverName
from pyasan.exceptions import ValidationError
class TestMarsRoverPhotosClient:
"""Test cases for M... | jeorryb/pyasan | tests/test_mars.py | .py | 76a5c02ce119be79 | 7.65 | 1 |
#!/usr/bin/env python3
"""Script to add non-"latest" miniconda releases.
Written for python 3.7.
Checks the miniconda download archives for new versions,
then writes a build script for any which do not exist locally,
saving it to plugins/python-build/share/python-build.
Ignores releases below 4.3.30.
Also ignores sub... | ggear/asystem | src/all/_fedora/src/main/resources/pyenv/plugins/python-build/scripts/add_miniconda.py | .py | 70e0644b618c05c8 | 7.3 | 3 |
#!/usr/bin/env python3
'Adds the latest miniforge and mambaforge releases.'
from pathlib import Path
import logging
import os
import string
import requests
logger = logging.getLogger(__name__)
logging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'))
MINIFORGE_REPO = 'conda-forge/miniforge'
DISTRIBUTIONS = ['min... | ggear/asystem | src/all/_fedora/src/main/resources/pyenv/plugins/python-build/scripts/add_miniforge.py | .py | 3eca4bfde87ce0f9 | 7.3 | 3 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is just a module for administration purpose.
The idea is to leave PyFunceble run this script in order to get less headache
while debugging environnements.
Authors:
- @Funilrys, Nissar Chababy <contactTAfunilrysTODcom>
Contributors:
Let's contribute !
... | Ultimate-Hosts-Blacklist/BadIPs.com_Level_4 | administration.py | .py | 507d4011700b5eb3 | 7.15 | 1 |
class SaveAfterPostGenerationMixin:
"""
Mixin for saving Django model instances after post-generation hooks.
To use this derive the factory class that uses @factory.post_generation
decorator from factory.django.DjangoModelFactory as well as this, e.g.
class TestFactory(SaveAfterPostGenerationMixin,... | City-of-Helsinki/palvelutarjotin | common/mixins.py | .py | b71cfcb4f6390d9d | 7.24 | 2 |
import json
import logging
import requests
logger = logging.getLogger(__name__)
class NotificationService:
SEND_SMS_ENDPOINT = "message/send"
CONNECTION_TIMEOUT = 10
@property
def url(self):
"""The full URL for the SMS sending endpoint"""
return f"{self.api_url}{self.SEND_SMS_ENDPOI... | City-of-Helsinki/palvelutarjotin | common/notification_service.py | .py | bf42b2757a25c124 | 7.24 | 2 |
import enum
from datetime import datetime
from typing import Optional
import graphene
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import HttpRequest
from django.utils import timezone
from django.utils.translation import gettext... | City-of-Helsinki/palvelutarjotin | common/utils.py | .py | cee65ad0813aaa86 | 7.24 | 2 |
from typing import List
from django.db import models
from gdpr.consts import CLEARED_VALUE
class GDPRModel(models.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# raise a NotImplementedError
# immediately on launch of an app
# if the `gdpr_sensitiv... | City-of-Helsinki/palvelutarjotin | gdpr/models.py | .py | 344fd406c9eb255b | 7.24 | 2 |
import logging
from typing import TYPE_CHECKING, Optional
from helsinki_gdpr.types import ErrorResponse
if TYPE_CHECKING:
from organisations.models import User as UserType
logger = logging.getLogger(__name__)
def get_user(user: "UserType") -> "UserType":
"""Function used by the Helsinki Profile GDPR API to... | City-of-Helsinki/palvelutarjotin | gdpr/service.py | .py | 0511c4b2dd4096c4 | 7.24 | 2 |
import datetime
import jwt
import pytest
from django.utils import timezone
from helusers.settings import api_token_auth_settings
from rest_framework.test import APIClient
from common.tests.conftest import * # noqa
from .keys import rsa_key
@pytest.fixture
def gdpr_api_client():
return APIClient()
def get_ap... | City-of-Helsinki/palvelutarjotin | gdpr/tests/conftest.py | .py | c6fb2e57f1dd872c | 7.74 | 2 |
import urllib.parse
import uuid
import pytest
import requests_mock
from auditlog.models import LogEntry
from django.conf import settings
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APIClient
from gdpr.service import d... | City-of-Helsinki/palvelutarjotin | gdpr/tests/test_gdpr_api.py | .py | ceb29344f70943f8 | 7.74 | 2 |
import json
import math
import requests
import responses
from graphene_linked_events.utils import bbox_for_coordinates, format_response
def test_bbox_for_coordinates():
"""
Bounding box for Katri Valan puisto with a distance of 3 km from center to corner.
"""
bbox = bbox_for_coordinates(24.963692, 6... | City-of-Helsinki/palvelutarjotin | graphene_linked_events/tests/test_utils.py | .py | 052c6d19b2b87e8d | 7.74 | 2 |
# https://stackoverflow.com/questions/6578986/how-to-convert-json-data
# -into-a-python-object/15882054#15882054
import json
from collections import namedtuple
from typing import List
from django.conf import settings
from geopy import Point
from geopy import distance as geopy_distance
from graphene_linked_events.rest... | City-of-Helsinki/palvelutarjotin | graphene_linked_events/utils.py | .py | d0afeee04ae0b6bf | 7.24 | 2 |
import csv
import glob
import io
import os
import re
from collections import defaultdict
from logging import getLogger
from typing import DefaultDict, Dict, Mapping, Optional, Sequence, Tuple
import requests
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import tr... | City-of-Helsinki/palvelutarjotin | notification_importers/notification_importer.py | .py | 0255bb7250953b49 | 7.24 | 2 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is just a module for administration purpose.
The idea is to leave PyFunceble run this script in order to get less headache
while debugging environnements.
Authors:
- @Funilrys, Nissar Chababy <contactTAfunilrysTODcom>
Contributors:
Let's contribute !
... | Ultimate-Hosts-Blacklist/BadIPs.com_Level_3 | administration.py | .py | efb7c537b0b56398 | 7.24 | 2 |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site ... | bihealth/sodar-django-site | sodar_django_site/contrib/sites/migrations/0003_set_site_domain_and_name.py | .py | 319f721e4af44952 | 7.15 | 1 |
"""Module for using HTTP Auth Basic login if user is not already authenticated
via Django session.
"""
import base64
from functools import wraps
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.utils.decorators import method_decorato... | bihealth/sodar-django-site | sodar_django_site/users/auth.py | .py | d7efb9b4d51686fa | 7.15 | 1 |
"""
Fourier-transform tools: k-space windows and the forward chi(k) -> chi(R)
transform used to turn EXAFS oscillations into a pseudo-radial-distribution
function.
Transforming k-weighted EXAFS oscillations into an R-space
pseudo-radial-distribution function is the original idea of
D. E. Sayers, E. A. Stern & F. W. Ly... | htlemke/escape-fel | escape/exafs/fourier.py | .py | 0e76b37c82517de2 | 7.35 | 4 |
"""
Quick-look plotting helpers for the three standard EXAFS views:
mu(E) with background, chi(k) k-weighted, and |chi(R)|.
These are thin matplotlib wrappers meant to save typing in notebooks;
for publication figures you will likely want to build your own plots
directly with matplotlib, using the arrays these functio... | htlemke/escape-fel | escape/exafs/plotting.py | .py | 13e7eff792ef81e3 | 7.35 | 4 |
"""
Pre-edge subtraction and post-edge (edge-step) normalization.
Every raw XAS spectrum mu(E) sits on top of a smooth, slowly-varying
"pre-edge" background (absorption from other elements/shells, sample
holder, detector response, etc.) and has an overall step height at
the edge that depends on sample thickness and co... | htlemke/escape-fel | escape/exafs/preedge.py | .py | e42691902db69fc0 | 7.35 | 4 |
"""
Small standalone helper functions that don't belong in a specific
processing stage.
"""
from __future__ import annotations
import numpy as np
def kweight_chi(k, chi, kweight=2):
"""Return k^kweight * chi(k) -- the most common way to plot/inspect EXAFS."""
k = np.asarray(k, dtype=float)
chi = np.asarr... | htlemke/escape-fel | escape/exafs/utils.py | .py | 2dfc6036dc975b57 | 7.35 | 4 |
"""Tools for reading ixp.h5 files from deprecated ixppy. (work in progress)"""
from .utilities import findItemnamesGroups
import h5py
from .. import Array
from threading import Thread
import numpy as np
import dask.array as da
def parse_ixp(ixp_file):
# with h5py.File(ixp_file, "r") as fh:
fh = h5py.File(ixp... | htlemke/escape-fel | escape/parse/ixppy_tmp.py | .py | 82908c7092bdc001 | 7.35 | 4 |
import pickle
from distributed.protocol import serialize, deserialize
import inspect
SOURCETYPES = ["factory", "dataset", "status", "array_map_index_blocks"]
class Source:
def __init__(
self,
type,
factory=None,
args=[],
kwargs={},
base_dataset=None,
iargou... | htlemke/escape-fel | escape/storage/source.py | .py | 3d1a84c4f22837c0 | 7.35 | 4 |
import click
from funai.llm import get_model
from funutil import getLogger
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
from .audio_gen import generate_podcast
from .script import generate_script, parse_script_plan
from .templates import enhance_prompt, initial_dial... | farfarfun/funpaper | src/funpaper/podcast/command.py | .py | 6abf958cb0352eb7 | 7 | 0 |
# -*- coding: utf-8 -*-
import re
import string
from collections import OrderedDict, namedtuple
from notetool.tool.log import logger
from six import integer_types, itervalues, string_types
from ..utils.iter import expand_generator
class Color(object):
"""
Aggregate a single color different representations... | farfarfun/fungame | src/notegame/games/nonogram/core/color.py | .py | ad5cc9d326993beb | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Defines the basic terms and functions for nonogram game
"""
from notetool.tool.log import logger
from six import integer_types, iteritems, string_types, with_metaclass
from six.moves import range
from notegame.games.nonogram.core.color import Color, ColorBlock
from notegame.games.nonogram... | farfarfun/fungame | src/notegame/games/nonogram/core/common.py | .py | d85fb8e7f53fc811 | 7 | 0 |
# -*- coding: utf-8 -*-
"""Define nonogram solver that solves line-by-line"""
import time
from notetool.tool.log import logger
from six.moves import range, zip
from ..solver import solve_line
from ..utils.priority_dict import PriorityDict
from .common import BOX, SPACE, UNKNOWN, is_color_cell
def _is_pixel_updated... | farfarfun/fungame | src/notegame/games/nonogram/core/propagation.py | .py | 5dcd5f8c8437eb2a | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Defines various renderers for the game of nonogram
"""
from abc import ABC
from sys import stdout
from notetool.tool.log import logger
from six import integer_types, itervalues, text_type
from ..utils.iter import max_safe, pad
from ..utils.other import two_powers
from .common import BOX, ... | farfarfun/fungame | src/notegame/games/nonogram/core/renderer.py | .py | f3cddcb79611c436 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
The program's entry point
"""
import json
from notegame.games.nonogram.core.backtracking import Solver
from notegame.games.nonogram.core.board import make_board
from notegame.games.nonogram.core.renderer import BaseAsciiRenderer
from notegame.games.nonogram.reader import read_example
def... | farfarfun/fungame | src/notegame/games/nonogram/main.py | .py | 916598acfacd2789 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Defines methods to parse data file with the board defined
"""
import os
import re
from six import PY2, string_types
from six.moves.configparser import RawConfigParser
from notegame.games.nonogram.core.color import ColorMap
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
_INLINE... | farfarfun/fungame | src/notegame/games/nonogram/reader.py | .py | 27567cde51a7e49f | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Dynamic programming algorithm to solve nonograms (using recursion)
See details in the work 'An Efficient Approach to Solving Nonograms':
https://ir.nctu.edu.tw/bitstream/11536/22772/1/000324586300005.pdf
"""
from six.moves import zip
from ..core.common import BOX, SPACE, UNKNOWN, partial_... | farfarfun/fungame | src/notegame/games/nonogram/solver/efficient.py | .py | abbcb2a95eccd69b | 7 | 0 |
# -*- coding: utf-8 -*-
from collections import defaultdict
from functools import wraps
from time import time
from notetool.tool.log import logger
class Cache(object):
"""
具有大小限制和命中计数器的简单词典。
"""
def __init__(self, max_size=10 ** 5, increase=False, do_not_increase_after=10 ** 6):
"""
... | farfarfun/fungame | src/notegame/games/nonogram/utils/cache.py | .py | c1eb9f240a7fef91 | 7 | 0 |
# -*- coding: utf-8 -*-
from notetool.tool.log import logger
from six import iteritems, text_type
class StateMachineError(ValueError):
"""
Represents an error occurred when trying
to make bad transition with a FSM
"""
BAD_TRANSITION = 1
BAD_ACTION = 2
def __init__(self, *args, **kwargs)... | farfarfun/fungame | src/notegame/games/nonogram/utils/fsm.py | .py | 515d7fda10e0bf10 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Here lie the utilities methods that does not depend on any domain
e.g. manipulations with collections or streams.
"""
import logging
import multiprocessing
import os
import sys
from contextlib import contextmanager
from datetime import datetime
from functools import wraps
from threading imp... | farfarfun/fungame | src/notegame/games/nonogram/utils/other.py | .py | 579981ea2370f54a | 7 | 0 |
# -*- coding: utf-8 -*-
"""
Based on Matteo Dell'Amico's solution
https://gist.github.com/matteodellamico/4451520
"""
from heapq import heapify, heappush, heappop
from six import iteritems
class PriorityDict(dict):
"""
Dictionary that can be used as a priority queue.
Keys of the dictionary are items to... | farfarfun/fungame | src/notegame/games/nonogram/utils/priority_dict.py | .py | a334e46ec3c0120f | 7 | 0 |
import os
import pickle
import random
import demjson
import numpy as np
import pandas as pd
import tensorflow as tf
from notedata.manage import DatasetManage
from notekeras.features.feature_parse import define_feature_json
from notetool.tool import exists_file, log
from sklearn.model_selection import train_test_split
... | farfarfun/fundata | src/fundata/dataset/datas.py | .py | 0ab8b55e65c5a204 | 7.3 | 3 |
import os
import sqlite3
import time
from time import strftime
from typing import List
import pandas as pd
from notebuild.shell import run_shell
from notetool.tool import log
class BaseTable:
"""
表维度的底层数据库的通用实现
"""
def __init__(self, table_name: str = "default_table", columns: List[str] = None):
... | farfarfun/fundata | src/fundata/tables_bak/core.py | .py | edd47a4fc2afa2d8 | 7.3 | 3 |
import mcpi.block
from mcpi.block import Block
from mcpi.minecraft import Minecraft
from mcpi.vec3 import Vec3
class MineCraftConn:
"""The main class to interact with a running instance of Minecraft Pi."""
def __init__(self, mc: Minecraft = None):
self.mc = mc or Minecraft.create()
def get_block... | farfarfun/funcraft | notecraft/core/core.py | .py | 5dafe8c42ae9fabb | 7 | 0 |
"""
Document Parsers for De-AI Writing Checker
Supports LaTeX, Typst, Markdown, and plain text.
"""
import re
from abc import ABC, abstractmethod
from typing import Any
class DocumentParser(ABC):
"""Abstract base class for document parsers."""
@abstractmethod
def split_sections(self, content: str) -> di... | nerdneilsfield/dotfiles | agents/.agents/skills/deai/scripts/parsers.py | .py | 0832ed51e7c3a944 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Style Profile Analyzer for De-AI Skill.
Analyzes one or more reference documents and outputs a JSON style profile
that captures the author's writing characteristics across 8 dimensions.
The profile can then be fed to an LLM during rewrite mode to match the
target style, producing text that s... | nerdneilsfield/dotfiles | agents/.agents/skills/deai/scripts/style_profile.py | .py | 1fc15d209460027f | 7.35 | 4 |
#!/usr/bin/env python3
"""
为文档中的ASCII图表添加学术风格的图片生成注释
深度分析ASCII内容和上下文,生成准确的图片描述
"""
import re
import argparse
from pathlib import Path
def analyze_ascii_content(ascii_content):
"""分析ASCII图的内容特征"""
features = {
'has_boxes': '┌' in ascii_content or '┬' in ascii_content or '├' in ascii_content,
'ha... | nerdneilsfield/dotfiles | claude/.claude/skills/generate-figures/scripts/add_figure_prompts.py | .py | f4aef9486549a290 | 7.35 | 4 |
#!/usr/bin/env python3
"""
使用 LLM 分析 ASCII 图并生成图片 prompt (支持并发)
"""
import argparse
import os
import re
import sys
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import NamedTuple
try:
import openai
except ImportError:
print("Error: openai library not found... | nerdneilsfield/dotfiles | claude/.claude/skills/generate-figures/scripts/add_figure_prompts_llm.py | .py | 2ad0c0a8de73981f | 7.35 | 4 |
#!/usr/bin/env python3
"""
使用 LLM 分析 ASCII 图并生成图片 prompt (支持并发 + 去重)
优化版本:更多上下文、去重检查、更强的system prompt、JSON输出
"""
import argparse
import json
import os
import re
import sys
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import NamedTuple
from difflib import SequenceM... | nerdneilsfield/dotfiles | claude/.claude/skills/generate-figures/scripts/add_figure_prompts_llm_v2.py | .py | 048cfd0c700c0637 | 7.35 | 4 |
#!/usr/bin/env python3
"""Scan document files for figure prompts and generate images."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import shlex
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib imp... | nerdneilsfield/dotfiles | claude/.claude/skills/generate-figures/scripts/generate_figures.py | .py | 28c20003672ebb5b | 7.35 | 4 |
#!/usr/bin/env python3
"""Insert generated figures into document, replacing ASCII diagrams."""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
from typing import NamedTuple
class FigureInfo(NamedTuple):
"""Information about a figure to insert."""
index: int
... | nerdneilsfield/dotfiles | claude/.claude/skills/generate-figures/scripts/insert_figures.py | .py | 0b27b0582ccc1140 | 7.35 | 4 |
#!/usr/bin/env python3
"""Analyze and suggest improvements for Nano Banana Pro prompts."""
from __future__ import annotations
import argparse
import sys
from typing import NamedTuple
class PromptAnalysis(NamedTuple):
"""Analysis results for a prompt."""
has_subject: bool
has_composition: bool
has_ac... | nerdneilsfield/dotfiles | claude/.claude/skills/generate-figures/scripts/optimize_prompt.py | .py | 962815caa253f695 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Experiment analysis helper for LaTeX papers.
This script formats the raw experiment data into a structured prompt
for the LLM to generate standard IEEE/ACM compliant paragraphs.
"""
import argparse
import sys
from pathlib import Path
def generate_request(input_data: str) -> str:
path =... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/analyze_experiment.py | .py | 947f0d0bbdc7ada6 | 7.35 | 4 |
#!/usr/bin/env python3
"""
LaTeX Format Checker - chktex wrapper with enhanced reporting
Usage:
python check_format.py main.tex
python check_format.py main.tex --strict
python check_format.py main.tex --config .chktexrc
"""
import argparse
import re
import shutil
import subprocess
import sys
from pathlib ... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/check_format.py | .py | 3b201feb3d8d8fac | 7.35 | 4 |
#!/usr/bin/env python3
"""
LaTeX Compilation Script - Unified compiler for pdflatex/xelatex/lualatex
Default Behavior:
Uses latexmk which automatically handles all dependencies (bibtex/biber,
cross-references, indexes, glossaries) and determines the optimal number
of compilation passes. This is the recomme... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/compile.py | .py | 1693f114ec998d8c | 7.35 | 4 |
#!/usr/bin/env python3
"""
De-AI Batch Processor for English Academic Papers
Batch processes entire LaTeX/Typst chapters or documents.
Usage:
python deai_batch.py main.tex --chapter chapter3/introduction.tex
python deai_batch.py main.typ --all-sections
python deai_batch.py main.tex --section introduction -... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/deai_batch.py | .py | c03db3c5e04935ec | 7.35 | 4 |
#!/usr/bin/env python3
"""
De-AI Writing Trace Checker for English Academic Papers
Analyzes LaTeX/Typst source code for AI writing patterns.
Usage:
python deai_check.py main.tex --section introduction
python deai_check.py main.typ --analyze
python deai_check.py main.tex --fix-suggestions
"""
import argpar... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/deai_check.py | .py | 215b4db3b2f6b691 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Prose Extractor - Extract plain text from LaTeX/Typst for analysis
Usage:
python extract_prose.py main.tex
python extract_prose.py main.typ
python extract_prose.py main.tex --output prose.txt
python extract_prose.py main.tex --keep-structure
"""
import argparse
import sys
fr... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/extract_prose.py | .py | ab124b261de77d66 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Online bibliography verification via CrossRef and Semantic Scholar APIs.
Verifies bibliography entries against online databases to detect:
- Invalid DOIs
- Metadata mismatches (year, journal)
- Missing DOIs (suggests from title search)
Usage:
# As a module (imported by verify_bib.py):
... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/online_bib_verify.py | .py | 1da41f1663cf9f12 | 7.35 | 4 |
"""
Document Parsers for Academic Writing Skills
Support for LaTeX and Typst document parsing.
"""
import re
from abc import ABC, abstractmethod
from typing import Any
class DocumentParser(ABC):
"""Abstract base class for document parsers."""
@abstractmethod
def split_sections(self, content: str) -> dic... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-paper-en/scripts/parsers.py | .py | e7e5cc88d02582f2 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Experiment analysis helper for Chinese LaTeX thesis and journals.
This script formats the raw experiment data into a structured prompt
for the LLM to generate standard, highly formal academic paragraphs.
"""
import argparse
import sys
from pathlib import Path
def generate_request(input_dat... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-thesis-zh/scripts/analyze_experiment.py | .py | 8fad005fdfa79761 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Terminology Consistency Checker - Check term usage consistency in thesis
Usage:
python check_consistency.py main.tex
python check_consistency.py main.tex --terms
python check_consistency.py main.tex --abbreviations
"""
import argparse
import re
import sys
from collections import... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-thesis-zh/scripts/check_consistency.py | .py | 6e3bec6e15834136 | 7.35 | 4 |
#!/usr/bin/env python3
"""
LaTeX Format Checker (Chinese) - chktex wrapper with Chinese support
Usage:
python check_format.py main.tex
python check_format.py main.tex --strict
"""
import argparse
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Optional
class ... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-thesis-zh/scripts/check_format.py | .py | 465e9d408208d9d9 | 7.35 | 4 |
#!/usr/bin/env python3
"""
LaTeX Compilation Script - 中文学位论文编译器 (xelatex/lualatex)
默认行为:
使用 latexmk + XeLaTeX 自动处理所有依赖(bibtex/biber、交叉引用、
索引、术语表),并自动决定最优编译次数。这是中文论文的推荐方案。
Usage:
python compile.py main.tex # 默认: latexmk + xelatex
python compile.py main.tex --compiler xelatex # ... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-thesis-zh/scripts/compile.py | .py | 8b8f910ac9641696 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Thesis Structure Mapper - Map multi-file thesis structure
Usage:
python map_structure.py main.tex
python map_structure.py main.tex --json
python map_structure.py main.tex --detect-template
"""
import argparse
import re
import sys
from pathlib import Path
from typing import Optio... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-thesis-zh/scripts/map_structure.py | .py | 977631746d0be4cd | 7.35 | 4 |
#!/usr/bin/env python3
"""
标题优化工具 - 中文学位论文
基于 GB/T 7713.1-2006 规范及国际最佳实践。
生成和优化学位论文标题。
"""
import argparse
import re
import sys
from pathlib import Path
from typing import Optional
# Import parsers from the same directory
try:
from parsers import extract_abstract, extract_title
except ImportError:
import os
... | nerdneilsfield/dotfiles | claude/.claude/skills/latex-thesis-zh/scripts/optimize_title.py | .py | dce8c1767bae8ec1 | 7.35 | 4 |
#TODO: handle binary str variables (as in logistic regression)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import combinations
from IPython.display import display
from sklearn.cluster import KMeans as KM_Base
from sklearn.metrics import silhouette_samples, silhouette... | RandanCSS/randan | randan/clustering.py | .py | 8ce06ef0cd5b03d6 | 7.39 | 5 |
#!/usr/bin/env python
# coding: utf-8
'''
(EN) A module that simplifies scraping TG data
(RU) Модуль для упрощения скрапинга данных из TG
'''
# 0. Активировать требуемые для работы скрипта модули и пакеты + пререквизиты
# 0.0 В общем случае требуются следующие модули и пакеты (запасной код, т.к. они прописаны в setup... | RandanCSS/randan | randan/scrapingTG/scrapingTG.py | .py | 824bec47bdde2765 | 7.39 | 5 |
#!/usr/bin/env python
# coding: utf-8
'''
(EN) A module that simplifies and manages the web scraping workflow of VK
(RU) Модуль для упрощения скрапинга VK
'''
# 0. Активировать требуемые для работы скрипта модули и пакеты + пререквизиты
# В общем случае требуются следующие модули и пакеты (запасной код, т.к. они проп... | RandanCSS/randan | randan/scrapingVK/scrapingVK_tools.py | .py | bd9394c878de88d6 | 7.39 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.