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 |
|---|---|---|---|---|---|---|
"""
Run every example in examples/ (aiohttp server with request id logging
implemented) and try to call it.
The examples are run one by one - each test starts the example server
on a free port, calls it and checks the response, the response header
with the request id and the log output.
"""
from aiohttp import Client... | messa/aiohttp-request-id-logging | tests/examples/test_demo.py | .py | 8f08e9f1359a54f5 | 8.06 | 12 |
"""note-python binary upload example.
This example uploads binary data to a Notehub proxy route using the
high-speed chunked upload mechanism. The data is staged through the
Notecard's binary buffer and sent to Notehub via web.post.
Before running this example:
1. Create a Proxy Route in your Notehub project (e.g. po... | blues/note-python | examples/binary-mode/upload/binary_upload_example.py | .py | 9102c773a777b4e1 | 7.64 | 18 |
#!/usr/bin/env python3
"""Minimal HTTP server that receives binary files routed from Notehub.
Receives binary files via a General HTTP/HTTPS route and saves them to
the current directory.
Usage:
python3 receive_binary.py [port]
Default port: 8080
Setup:
1. Run this script (optionally with ngrok to expos... | blues/note-python | examples/binary-mode/upload/receive_binary.py | .py | 4c2f8e19cf776389 | 7.64 | 18 |
"""note-python CircuitPython example.
This file contains a complete working sample for using the note-python
library on a CircuitPython device.
"""
import sys
import time
import notecard
if sys.implementation.name != "circuitpython":
raise Exception("Please run this example in a CircuitPython environment.")
impo... | blues/note-python | examples/notecard-basics/cpy_example.py | .py | 6a3525c7d3a51eef | 7.64 | 18 |
"""note-python MicroPython example.
This file contains a complete working sample for using the note-python
library on a MicroPython device.
"""
import sys
import time
import notecard
if sys.implementation.name != "micropython":
raise Exception("Please run this example in a MicroPython environment.")
from machine... | blues/note-python | examples/notecard-basics/mpy_example.py | .py | 04f8712b6eafb487 | 7.64 | 18 |
"""note-python CircuitPython Outboard Firmware Update example.
This file contains a complete working sample for demonstrating Notecard
Outboard Firmware Update from CircuitPython. It configures the Notecard to
enable Outboard Firmware Update for the host, then blinks the built-in LED with
a recognizable pattern that s... | blues/note-python | examples/outboard-dfu/circuit-python/code.py | .py | 12ed1e45db2e0653 | 7.64 | 18 |
"""Helper methods for doing binary transfers to/from a Notecard."""
import sys
from notecard.cobs import cobs_encode, cobs_decode
from notecard.notecard import Notecard, CARD_INTRA_TRANSACTION_TIMEOUT_SEC
BINARY_RETRIES = 2
if sys.implementation.name == 'cpython':
import hashlib
def _md5_hash(data):
... | blues/note-python | notecard/binary_helpers.py | .py | ecd0eed65045a9a0 | 7.64 | 18 |
"""Methods for COBS encoding and decoding arbitrary bytearrays."""
def cobs_encode(data: bytearray, eop: int) -> bytearray:
"""COBS encode an array of bytes, using eop as the end of packet marker."""
cobs_overhead = 1 + (len(data) // 254)
encoded = bytearray(len(data) + cobs_overhead)
code = 1
idx... | blues/note-python | notecard/cobs.py | .py | 6fbe649934cdb219 | 7.64 | 18 |
"""Module for computing the CRC32 of arbitrary data."""
crc32_lookup_table = [
0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C
]
def _logical_rshift(val, shift_am... | blues/note-python | notecard/crc32.py | .py | bb22b8155bfafb2a | 7.64 | 18 |
"""dfu Fluent API Helper."""
##
# @file dfu.py
#
# @brief dfu Fluent API Helper.
#
# @section description Description
# This module contains helper methods for calling dfu.* Notecard API commands.
# This module is optional and not required for use with the Notecard.
from notecard.validators import validate_card_objec... | blues/note-python | notecard/dfu.py | .py | 9b86ea1248658c32 | 7.64 | 18 |
"""Module for computing MD5 hash for MicroPython and CircuitPython."""
"""
Copyright [2018] [Mauro Riva <lemariva@mail.com> <lemariva.com>]
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... | blues/note-python | notecard/md5.py | .py | 18eb213a78de6fa5 | 7.64 | 18 |
"""Module for managing timeouts in note-python."""
import sys
import time
use_rtc = sys.implementation.name != 'micropython' and sys.implementation.name != 'circuitpython'
if not use_rtc:
if sys.implementation.name == 'circuitpython':
import supervisor
from supervisor import ticks_ms
_TI... | blues/note-python | notecard/timeout.py | .py | 2434e612992b537d | 7.64 | 18 |
"""TransactionManager-related code for note-python."""
import sys
import time
from notecard.timeout import start_timeout, has_timed_out
from notecard.gpio import GPIO
class TransactionManager:
"""Class for managing the start and end of Notecard transactions.
Some Notecards need to be signaled via GPIO when... | blues/note-python | notecard/transaction_manager.py | .py | 9c663ba89bb6e4ed | 7.64 | 18 |
"""Main Validation decorators for note-python."""
##
# @file validators.py
#
# @brief Validation decorators for note-python.
import sys
import notecard
if sys.implementation.name == "cpython":
import functools
def validate_card_object(func):
"""Ensure that the passed-in card is a Notecard."""
... | blues/note-python | notecard/validators.py | .py | 19b95bb7b34d28db | 7.64 | 18 |
#!/usr/bin/env python3
"""Generate Notecard API functions from notecard-schema."""
import requests
import time
from pathlib import Path
from typing import Dict, List, Optional, Any
import argparse
class NotecardAPIGenerator:
"""Generate Python API functions from Notecard JSON schema."""
reserved_keywords = ... | blues/note-python | scripts/generate_apis.py | .py | 954fac0fae3c3a71 | 7.64 | 18 |
import sys
import os
import pytest
from unittest.mock import MagicMock
sys.path.insert(0,
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
import notecard # noqa: E402
@pytest.fixture
def run_fluent_api_notecard_api_mapping_test():
def _run_test(fluent_api, notecard_api_name, ... | blues/note-python | test/fluent_api/conftest.py | .py | 0ea16978e126f8a0 | 7.14 | 18 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2014-2021 Damien P. George
# Copyright (c) 2017 Paul Sokolovsky
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated ... | blues/note-python | test/hitl/deps/pyboard.py | .py | 7c1a71ca7ec31faa | 7.14 | 18 |
from __future__ import annotations
import os
import sys
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
from loguru import logger
from imod_coupler.config import BaseConfig
def resolve_path(libname: str) -> str:
match sys.platform.lower():
case "win32":
e... | Deltares/imod_coupler | imod_coupler/drivers/driver.py | .py | 060b4495f840891a | 7.63 | 17 |
"""MetaMod: the coupling between MetaSWAP and MODFLOW 6
description:
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
import numpy as np
from loguru import logger
from numpy.typing import NDArray
from imod_coupler.config import BaseConfig
from imod_coupler.drivers.driver impo... | Deltares/imod_coupler | imod_coupler/drivers/metamod/metamod.py | .py | 5f82768d394f7967 | 7.63 | 17 |
from typing import Any
import numpy as np
from numpy.typing import NDArray
from imod_coupler.kernelwrappers.mf6_wrapper import Mf6Wrapper
from imod_coupler.kernelwrappers.ribasim_wrapper import RibasimWrapper
from imod_coupler.utils import MemoryExchange
class ExchangeBalance:
demands: dict[str, NDArray[np.floa... | Deltares/imod_coupler | imod_coupler/drivers/ribametamod/exchange.py | .py | d9f88d22b7418d1d | 7.63 | 17 |
"""Ribamod: the coupling between MetaSWAP and MODFLOW 6
description:
"""
from __future__ import annotations
import typing
from collections import ChainMap
from typing import Any
import numpy as np
from loguru import logger
from numpy.typing import NDArray
from scipy.sparse import csr_matrix
from imod_coupler.conf... | Deltares/imod_coupler | imod_coupler/drivers/ribamod/ribamod.py | .py | 567235ac1f51c434 | 7.63 | 17 |
from __future__ import annotations
from pathlib import Path
from sys import stderr
from typing import Any
import numpy as np
from loguru import logger
from numpy.typing import NDArray
from scipy.sparse import csr_matrix
from imod_coupler.config import LogLevel
from imod_coupler.logging.exchange_collector import Exch... | Deltares/imod_coupler | imod_coupler/utils.py | .py | 29fc739c31bc3d7b | 7.63 | 17 |
import abc
from collections.abc import Sequence
from pathlib import Path
from typing import Any
from primod.driver_coupling.driver_coupling_base import DriverCoupling
class CoupledModel(abc.ABC):
coupling_list: Sequence[DriverCoupling]
@abc.abstractmethod
def write(self, directory: str | Path, *args: An... | Deltares/imod_coupler | pre-processing/primod/coupled_model.py | .py | 36d0dafad22f9cb4 | 7.63 | 17 |
import abc
from pathlib import Path
from typing import Any
from pydantic import BaseModel
class DriverCoupling(BaseModel, abc.ABC):
"""
Abstract base class for driver couplings.
"""
# Config required for e.g. geodataframes
model_config = {"arbitrary_types_allowed": True}
@abc.abstractmethod... | Deltares/imod_coupler | pre-processing/primod/driver_coupling/driver_coupling_base.py | .py | adf5e20688d5f544 | 7.63 | 17 |
import geopandas as gpd
import numpy as np
import pandas as pd
import ribasim
import xarray as xr
from imod.mf6 import Drainage, GroundwaterFlowModel, Modflow6Simulation, River
from numpy.typing import NDArray
from ribasim.config import Basin, UserDemand
from primod.typing import Int
def _get_gwf_modelnames(mf6_simu... | Deltares/imod_coupler | pre-processing/primod/driver_coupling/util.py | .py | ae6cb4e2460ddbfe | 7.63 | 17 |
import abc
from io import TextIOWrapper
from pathlib import Path
from typing import Any
import pandas as pd
import xarray as xr
from imod.msw.fixed_format import VariableMetaData, format_fixed_width
from numpy.typing import NDArray
class GenericMapping(abc.ABC):
name: str
dataframe: pd.DataFrame
def wri... | Deltares/imod_coupler | pre-processing/primod/mapping/mappingbase.py | .py | 50d9de00a1160268 | 7.63 | 17 |
import geopandas as gpd
import numpy as np
import pandas as pd
import xarray as xr
from numpy.typing import NDArray
from scipy.spatial import KDTree
from primod.mapping.mappingbase import GenericMapping
from primod.typing import Bool, Float, Int
class NodeBasinMapping(GenericMapping):
def __init__(
self,... | Deltares/imod_coupler | pre-processing/primod/mapping/node_basin_mapping.py | .py | 5239211a1c29afbe | 7.63 | 17 |
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
import xarray as xr
class ModMaxLayer:
dataset: dict[str, Any]
_file_name: str = "nodes_max_layer.tsv"
def __init__(self, mod_id: xr.DataArray, mf6_max_layer: xr.DataArray) -> None:
self.dataset = {}
s... | Deltares/imod_coupler | pre-processing/primod/mapping/node_max_layer.py | .py | 4e49f0fb3c847d48 | 7.63 | 17 |
import numpy as np
import xarray as xr
from imod import mf6
from imod.msw.fixed_format import VariableMetaData
from numpy.typing import NDArray
from primod.mapping.mappingbase import MetaModMapping
from primod.typing import Int
class NodeSvatMapping(MetaModMapping):
"""
This contains the data to connect MODF... | Deltares/imod_coupler | pre-processing/primod/mapping/node_svat_mapping.py | .py | 14ca67bc40ea4fe5 | 7.63 | 17 |
import numpy as np
import xarray as xr
from imod import mf6
from imod.msw.fixed_format import VariableMetaData
from numpy.typing import NDArray
from primod.mapping.mappingbase import MetaModMapping
from primod.typing import Int
class RechargeSvatMapping(MetaModMapping):
"""
This contains the data to connect ... | Deltares/imod_coupler | pre-processing/primod/mapping/rch_svat_mapping.py | .py | cdad1e52ce4772da | 7.63 | 17 |
from io import TextIOWrapper
from typing import Any
import numpy as np
import pandas as pd
import xarray as xr
from imod.mf6.mf6_wel_adapter import Mf6Wel
from imod.msw.fixed_format import VariableMetaData
from numpy.typing import NDArray
from primod.mapping.mappingbase import MetaModMapping
from primod.typing import... | Deltares/imod_coupler | pre-processing/primod/mapping/wel_svat_mapping.py | .py | 16a20538e29d29d0 | 7.63 | 17 |
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import tomli_w
from imod.mf6 import Modflow6Simulation
from imod.msw import MetaSwapModel
from primod.coupled_model import CoupledModel
from primod.driver_coupling.metamod import MetaModDriverCoupling
from primod.model_mixin import M... | Deltares/imod_coupler | pre-processing/primod/metamod.py | .py | cde165af6cfc4b10 | 7.63 | 17 |
"""Module containing mixins for specific kernels, for example MODFLOW."""
from imod.mf6 import Modflow6Simulation, StructuredDiscretization
from imod.mf6.mf6_wel_adapter import Mf6Wel
class MetaModMixin:
"""MetaSWAP-Modflow coupling specific methods."""
@staticmethod
def get_mf6_pkgs_for_metaswap(
... | Deltares/imod_coupler | pre-processing/primod/model_mixin.py | .py | 6d7682a0c3a077f8 | 7.63 | 17 |
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import ribasim
import tomli_w
from imod.mf6 import Modflow6Simulation
from imod.msw import MetaSwapModel
from primod.coupled_model import CoupledModel
from primod.driver_coupling.driver_coupling_base import DriverCoupling
from primod... | Deltares/imod_coupler | pre-processing/primod/ribametamod.py | .py | 5af1162227ca8080 | 7.63 | 17 |
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import ribasim
import tomli_w
from imod.mf6 import Modflow6Simulation
from primod.coupled_model import CoupledModel
from primod.driver_coupling.ribamod import RibaModDriverCoupling
from primod.driver_coupling.util import (
_valid... | Deltares/imod_coupler | pre-processing/primod/ribamod.py | .py | becd646f213e9d29 | 7.63 | 17 |
from pathlib import Path
import markdown
import yaml
import git
def convert_markdown(text):
"""Convert Markdown text to HTML."""
return markdown.markdown(text, extensions=["extra"])
def build_html_table_with_card(rows, headers=None):
"""Build an HTML table with a special card formatting in the 'readme'... | cta-observatory/lstmcpipe | docs/produce_config_page.py | .py | 68b0e023a9dcf6cf | 7.48 | 8 |
#!/usr/bin/env python
from ruamel.yaml import YAML
import logging
log = logging.getLogger(__name__)
def load_config(config_path):
"""
Load the pipeline config, test for invalid values and
set paths to the data files/directories.
Parameters:
-----------
config_path: str or Path-like object
... | cta-observatory/lstmcpipe | lstmcpipe/config/pipeline_config.py | .py | 59562c801d7d98a7 | 7.48 | 8 |
from lstmcpipe.config import export_env
from lstmcpipe.config.pipeline_config import (
config_valid,
complete_lstmcpipe_config,
)
import tempfile
import os
import pytest
# from datetime import datetime
yaml_keys = ["prod_id", "stages_to_run", "prod_type", "workflow_kind", "stages"]
dummy_config = {k: None for... | cta-observatory/lstmcpipe | lstmcpipe/config/tests/test_pipeline_config.py | .py | f03a528102296fe1 | 7.98 | 8 |
# !/usr/bin/env python3
# Everything is hardcoded to LST telescopes - because this is just a temporal work that will no longer be used
# in the moment lstchain upgrades to V0.8
import os
import tables
import argparse
import numpy as np
from astropy.table import Table, vstack, join
from astropy.io.misc.hdf5 import wri... | cta-observatory/lstmcpipe | lstmcpipe/hiperta/reorganize_dl1hiperta300_to_dl1lstchain060.py | .py | aa21f3013f605ce0 | 7.48 | 8 |
#!/usr/bin/env python3
#
# Reorganize the DL1 output files of the HiPeRTA and HiPeCTA r0_to_dl1 codes to reach the lstchain
# file structure for DL1 files
#
# Usage :
# $ python reorganize_dl1_file -i input.h5 [-o outname.h5]
import os
import copy
import tables
import argparse
import numpy as np
import pandas as pd
im... | cta-observatory/lstmcpipe | lstmcpipe/hiperta/reorganize_dl1hiperta_to_dl1lstchain.py | .py | 583b1dbf2c8b0f06 | 7.48 | 8 |
# library of functions used for LST analysis data management
import os
import sys
import shutil
from pathlib import Path
_TRUE_VALUES = {"y", "yes", "t", "true", "on", "1"}
_FALSE_VALUES = {"n", "no", "f", "false", "off", "0"}
def strtobool(val):
"""Convert a string representation of truth to True or False, lik... | cta-observatory/lstmcpipe | lstmcpipe/io/data_management.py | .py | 8ef661c60aecb2b9 | 7.48 | 8 |
#!/usr/bin/env python
import shutil
from pathlib import Path
from lstmcpipe import prod_logs, __version__
def backup_log(file):
"""
Backups a log file.
This scenario should only happens if a MC prod is relaunched because it failed.
Parameters
----------
file : Path
Path object to the... | cta-observatory/lstmcpipe | lstmcpipe/io/lstmcpipe_tree_path.py | .py | fd7fde5e9e984e47 | 7.48 | 8 |
import subprocess
import json
import logging
import argparse
from pathlib import Path
from packaging import version
from lstchain.io.config import get_mc_config
from lstchain import __version__ as lstchain_version
BASE_LSTCHAIN_MC_CONFIG = get_mc_config()
# Configure logging
logging.basicConfig(level=logging.INFO) #... | cta-observatory/lstmcpipe | lstmcpipe/scripts/generate_nsb_levels_configs.py | .py | 78138cd9963d93f9 | 7.48 | 8 |
# #!/usr/bin/env python
import argparse
from pathlib import Path
from datetime import date
from lstmcpipe.config import paths_config
from lstmcpipe.utils import dump_lstchain_std_config
class ParseKwargs(argparse.Action):
"""
Parse a string formatted as `option1=foo` into a dict `{option1: foo}`
"""
... | cta-observatory/lstmcpipe | lstmcpipe/scripts/lstmcpipe_generate_config.py | .py | caf69bc46b29dfeb | 7.48 | 8 |
# #!/usr/bin/env python
import logging
import argparse
from pathlib import Path
import ctaplot
import matplotlib.pyplot as plt
from lstmcpipe.plots.plot_irfs import plot_summary_from_file
def plot_comparison(filelist, outfile=None, cta_north=False):
"""
Create a 2x2 plot comparing different sensitivity curve... | cta-observatory/lstmcpipe | lstmcpipe/scripts/script_compare_irfs.py | .py | 6c7b74b3ea7ad8ee | 7.48 | 8 |
"""
Procedure adapted from pyirf v0.4 example one (used with eventdisplay)
"""
import logging
import operator
from pathlib import Path
import numpy as np
from astropy import table
import astropy.units as u
from astropy.io import fits
from pyirf.binning import (
create_bins_per_decade,
add_overflow_bins,
c... | cta-observatory/lstmcpipe | lstmcpipe/scripts/script_dl2_to_sensitivity.py | .py | 22f9325ed6ea45f8 | 7.48 | 8 |
#!/usr/bin/env python
import shutil
import argparse
from pathlib import Path
from sklearn.model_selection import train_test_split
parser = argparse.ArgumentParser(
description="Script to move a directory and its content after creating the destination" " directory."
)
parser.add_argument(
"--input_dir",
"... | cta-observatory/lstmcpipe | lstmcpipe/scripts/script_train_test_splitting.py | .py | b7373222c70c5f39 | 7.98 | 8 |
# Most of the tests based on
# https://github.com/cta-observatory/cta-lstchain/blob/master/lstchain/scripts/tests/test_lstchain_scripts.py
import pytest
import subprocess
from importlib.metadata import entry_points
def find_entry_points(package_name):
"""from: https://stackoverflow.com/a/47383763/3838691"""
... | cta-observatory/lstmcpipe | lstmcpipe/scripts/tests/test_scripts.py | .py | b99b82ec4cf5d642 | 7.98 | 8 |
"""
This module provides an interface to the Elastic Compute Service (ECS) service from Alicloud.
"""
from footmark.dns.connection import DNSConnection
from footmark.regioninfo import get_regions
def regions(**kw_params):
"""
Get all available regions for the ECS service.
You may pass any of the arguments... | alibaba/footmark | footmark/dns/__init__.py | .py | 8c5581b26037cd9c | 7.6 | 15 |
"""
This module provides an interface to the Elastic Compute Service (ECS) service from Alicloud.
"""
from footmark.ecs.connection import ECSConnection
from footmark.regioninfo import get_regions
def regions(**kw_params):
"""
Get all available regions for the ECS service.
You may pass any of the arguments... | alibaba/footmark | footmark/ecs/__init__.py | .py | 963e885ff150acb0 | 7.6 | 15 |
class ECSObject(object):
def __init__(self, connection=None):
self.connection = connection
if self.connection and hasattr(self.connection, 'region'):
self.region = connection.region
else:
self.region = None
class TaggedECSObject(ECSObject):
"""
Any ECS resou... | alibaba/footmark | footmark/ecs/ecsobject.py | .py | a6b269449df3c5a7 | 7.6 | 15 |
class image(object):
"""description of class"""
"""
Represents an ECS Image
"""
from footmark.ecs.ecsobject import TaggedECSObject
class Image(TaggedECSObject):
def __init__(self, connection=None):
super(Image, self).__init__(connection)
self.tags = {}
def __repr__(self):
return ... | alibaba/footmark | footmark/ecs/image.py | .py | 4157718badb83c33 | 7.6 | 15 |
"""
Represents an ECS Instance
"""
import base64
from footmark.ecs.ecsobject import TaggedECSObject
class Instance(TaggedECSObject):
"""
Represents an instance.
"""
def __init__(self, connection=None):
super(Instance, self).__init__(connection)
self.tags = {}
def __repr__(self):
... | alibaba/footmark | footmark/ecs/instance.py | .py | db696a41caeae282 | 7.6 | 15 |
"""
Represents an ECS key pair
"""
from footmark.ecs.ecsobject import TaggedECSObject
class KeyPair(TaggedECSObject):
"""
Represents an ECS key pair.
:ivar id: The unique ID of the key pair.
:ivar name: The name of the key pair.
:ivar create_time: The timestamp of when the key pair was created.
... | alibaba/footmark | footmark/ecs/keypair.py | .py | b615d22560fcd507 | 7.6 | 15 |
"""
Represents an ECS Network Interface
"""
from footmark.ecs.ecsobject import TaggedECSObject
class NetworkInterfaceSet(TaggedECSObject):
"""
Represents an network interface.
"""
def __init__(self, connection=None):
super(NetworkInterfaceSet, self).__init__(connection)
self.tags = {}... | alibaba/footmark | footmark/ecs/networkinterface.py | .py | fa244632ffbd0676 | 7.6 | 15 |
from footmark.regioninfo import RegionInfo
class ECSRegionInfo(RegionInfo):
"""
Represents an ECS Region
"""
def __init__(self, connection=None):
from footmark.ecs.connection import ECSConnection
super(ECSRegionInfo, self).__init__(connection, connection_cls=ECSConnection)
| alibaba/footmark | footmark/ecs/regioninfo.py | .py | 5b907fa2f729063f | 7.1 | 15 |
"""
Represents an ECS Security Group
"""
from footmark.ecs.ecsobject import TaggedECSObject
class SecurityGroup(TaggedECSObject):
def __init__(self, connection=None):
super(SecurityGroup, self).__init__(connection)
self.tags = {}
def __repr__(self):
return 'SecurityGroup:%s' % self.id... | alibaba/footmark | footmark/ecs/securitygroup.py | .py | fa9275c795441a6b | 7.6 | 15 |
"""
Represents an ECS Elastic Block Storage Volume
"""
from footmark.ecs.ecsobject import TaggedECSObject
class Disk(TaggedECSObject):
"""
Represents an EBS volume.
:ivar id: The unique ID of the volume.
:ivar create_time: The timestamp of when the volume was created.
:ivar status: The status of ... | alibaba/footmark | footmark/ecs/volume.py | .py | 55f6dbecd2e515d2 | 7.6 | 15 |
"""
Represents an VRouter object
"""
from footmark.ecs.ecsobject import TaggedECSObject
class VRouterList(TaggedECSObject):
def __init__(self, connection=None):
super(VRouterList, self).__init__(connection)
self.tags = {}
def __repr__(self):
return 'VRouterList'
def __setattr__(s... | alibaba/footmark | footmark/ecs/vrouter.py | .py | 7f39e867db3cfcbd | 7.1 | 15 |
"""
Represents an ECS Zone
"""
from footmark.ecs.ecsobject import *
class Zone(TaggedECSObject):
"""
Represents an instance type family.
"""
def __init__(self, connection=None):
super(Zone, self).__init__(connection)
self.tags = {}
def __repr__(self):
return 'Zone:%s' ... | alibaba/footmark | footmark/ecs/zone.py | .py | 1a8b41f4d721e924 | 7.6 | 15 |
"""
This module provides an interface to the Elastic Compute Service (ECS) service from Alicloud.
"""
from footmark.ess.connection import ESSConnection
from footmark.regioninfo import get_regions
def regions(**kw_params):
"""
Get all available regions for the ECS service.
You may pass any of the arguments... | alibaba/footmark | footmark/ess/__init__.py | .py | 4063a5e7a8e0eb3b | 7.6 | 15 |
"""
Represents an ECS Instance
"""
from footmark.ess.essobject import TaggedESSObject
class ScalingConfiguration(TaggedESSObject):
"""
Represents an scaling configuration.
"""
def __init__(self, connection=None):
super(ScalingConfiguration, self).__init__(connection)
self.tags = {}
... | alibaba/footmark | footmark/ess/configuration.py | .py | 4eb9bc8f2feb5708 | 7.6 | 15 |
class ESSObject(object):
def __init__(self, connection=None):
self.connection = connection
if self.connection and hasattr(self.connection, 'region'):
self.region = connection.region
else:
self.region = None
class TaggedESSObject(ESSObject):
"""
Any ESS resou... | alibaba/footmark | footmark/ess/essobject.py | .py | 6205447bacaf09d2 | 7.6 | 15 |
"""
Represents an ECS Instance
"""
from footmark.ess.essobject import TaggedESSObject
class ScalingInstance(TaggedESSObject):
"""
Represents an scaling configuration.
"""
def __init__(self, connection=None):
super(ScalingInstance, self).__init__(connection)
self.tags = {}
def __r... | alibaba/footmark | footmark/ess/instance.py | .py | f01ab5a84838b5e0 | 7.6 | 15 |
# encoding: utf-8
"""
Represents a connection to the OSS service.
"""
from footmark.connection import ACSQueryConnection
import oss2
from footmark.exception import OSSResponseError
class OSSConnection(ACSQueryConnection):
DefaultRegionId = 'cn-hangzhou'
DefaultRegionName = '杭州'.encode("UTF-8")
DefaultCo... | alibaba/footmark | footmark/oss/connection.py | .py | dc88c803c1a9495c | 7.6 | 15 |
"""
This class encapsulates the provider-specific header differences.
"""
class Provider(object):
def __init__(self, name, access_key=None, secret_key=None, security_token=None, ecs_role_name=None):
self.access_key = access_key
self.secret_key = secret_key
self.security_token = security_to... | alibaba/footmark | footmark/provider.py | .py | d1baeaf864cf7531 | 7.6 | 15 |
import tensorflow as tf
# import keras # Remove direct keras import if not strictly needed for something tf.keras doesn't cover
from tensorflow.keras.losses import Huber
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, Callback # Changed to tensorflow.keras
import numpy as np
import sys
# Globa... | harveybc/feature-extractor | app/autoencoder_helper.py | .py | 256dc9fbfdc608b6 | 7.45 | 7 |
# config_handler.py
import json
import os
import sys
import requests
import numpy as np # Import numpy
import tensorflow as tf # For tf.print
import datetime # For NpEncoder
from app.config import DEFAULT_VALUES
from app.plugin_loader import load_plugin
def convert_numpy_types(obj):
"""
Recursively converts N... | harveybc/feature-extractor | app/config_handler.py | .py | a34bce4cdeff36f8 | 7.45 | 7 |
# config_merger.py
import sys
from app.config import DEFAULT_VALUES
def process_unknown_args(unknown_args):
return {unknown_args[i].lstrip('--'): unknown_args[i + 1] for i in range(0, len(unknown_args), 2)}
def convert_type(value):
try:
return int(value)
except ValueError:
try:
... | harveybc/feature-extractor | app/config_merger.py | .py | 27a2df382e86b2c1 | 7.45 | 7 |
import pandas as pd
from typing import Optional
from app.reconstruction import unwindow_data
import pandas as pd
from typing import Optional
import sys
def load_csv(file_path: str, headers: bool = False, max_rows: Optional[int] = None) -> pd.DataFrame:
"""
Loads a CSV file with optional row limiting and proc... | harveybc/feature-extractor | app/data_handler.py | .py | 729e70ef3e318460 | 7.45 | 7 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
plugin_loader.py
Module for loading plugins using the importlib.metadata entry points API updated for Python 3.12.
Provides functions to load a specific plugin and retrieve its parameters.
"""
from importlib.metadata import entry_points, EntryPoint
def load_plugin(p... | harveybc/feature-extractor | app/plugin_loader.py | .py | e527a22b44ee9cb2 | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Dense, Conv1D, UpSampling1D, BatchNormalization, Reshape, Concatenate, Flatten, Input
from keras.optimizers import Adam
from tensorflow.keras.initializers import GlorotUniform, HeNormal
from tensorflow.keras.losses import... | harveybc/feature-extractor | app/plugins/decoder_plugin_cnn_working.py | .py | a560456b24902208 | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Input, BatchNormalization
from keras.optimizers import Adam
from tensorflow.keras.initializers import GlorotUniform, HeNormal
from tensorflow.keras.callbacks import EarlyStopping
from... | harveybc/feature-extractor | app/plugins/encoder_plugin_cnn.py | .py | a651d9f08ec98f2c | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Input ,Dropout
from keras.optimizers import Adam
from tensorflow.keras.initializers import GlorotUniform, HeNormal
from keras.regularizers import l2
from keras.callbacks import Early... | harveybc/feature-extractor | app/plugins/encoder_plugin_lstm.py | .py | ac044cff18c4917a | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Input ,Dropout
from keras.optimizers import Adam
from tensorflow.keras.initializers import GlorotUniform, HeNormal
from keras.regularizers import l2
from keras.callbacks import Early... | harveybc/feature-extractor | app/plugins/encoder_plugin_transformer.py | .py | bc8968db7ab6cb80 | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Input ,Dropout
from keras.optimizers import Adam
from tensorflow.keras.initializers import GlorotUniform, HeNormal
from keras.regularizers import l2
from keras.callbacks import Early... | harveybc/feature-extractor | app/plugins/encoder_plugin_vae.py | .py | ef9e7b0b0eb31c25 | 7.45 | 7 |
import numpy as np
import pandas as pd
import argparse
import os
def generate_positional_encoding(num_positions, num_features):
"""
Generates a positional encoding matrix of size (num_positions, num_features).
Args:
num_positions (int): Number of positions in the time series (total length of t... | harveybc/feature-extractor | positional_encoding.py | .py | 186ba2083cdf1847 | 7.45 | 7 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import normaltest, shapiro, skew, kurtosis
import time
from app.data_handler import load_csv, write_csv
from app.config_handler import save_debug_info, remote_log
import warnings
from app.positional_encoding im... | harveybc/feature-eng | app/data_processor.py | .py | 5e8e30e9107acdc0 | 7.45 | 7 |
import pandas as pd
import time
from app.data_handler import load_csv, write_csv
from app.config_handler import save_debug_info, remote_log
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import normaltest, shapiro, skew, kurtosis, anderson
import numpy as np
import warnings
# Suppress the specif... | harveybc/feature-eng | app/data_processor_working classification.py | .py | 7dcb02cfed330d5b | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Input
from keras.optimizers import Adam
from tensorflow.keras.initializers import GlorotUniform, HeNormal
class Plugin:
"""
A predictor plugin using a convolutional neural ne... | harveybc/feature-eng | app/plugins/fft.py | .py | 31c6dd21982bb17b | 7.45 | 7 |
import numpy as np
from keras.models import Model, load_model, save_model
from keras.layers import Dense, Input, Dropout, Add, LayerNormalization, GlobalAveragePooling1D, Flatten
from keras.optimizers import Adam
from keras_multi_head import MultiHeadAttention
from tensorflow.keras.initializers import GlorotUniform, He... | harveybc/feature-eng | app/plugins/ssa.py | .py | 8fe30d4b2eb8396d | 7.45 | 7 |
#!/usr/bin/env python3
"""
Regime Detector Module
======================
Classifies each 4h bar into a market regime based on technical indicators.
V2 (Causal-Evidence Based):
Uses bb_position (CORE, causal score=5), atr_ratio (CORE, score=4),
and ema_alignment (LEADING, only positive Transfer Entropy) as primary
... | harveybc/feature-eng | app/regime_detector.py | .py | 6241ee3e3ba3c69c | 7.45 | 7 |
#!/usr/bin/env python3
"""
Generate labeled datasets for phase_1_b in the predictor repo.
Reads the raw 4h OHLC EURUSD data, runs the oracle label generator on each
phase_1 date range (d1-d6), and saves:
- base_d{n}.csv (OHLC + labels)
- normalization_config_a.json (label statistics, not needed for binary... | harveybc/feature-eng | generate_phase1b_labels.py | .py | 806a51634b57dcd4 | 7.45 | 7 |
#!/usr/bin/env python3
"""
Generate labeled datasets for phase_1_c (direction classification) in the
predictor repo.
Reads the raw 4h OHLC EURUSD data, runs the direction label generator on
each phase_1 date range (d1-d6), and saves:
- base_d{n}.csv (OHLC + direction labels)
- normalization_config_a.json (z-sco... | harveybc/feature-eng | generate_phase1c_labels.py | .py | 43daca351dbc98ce | 7.45 | 7 |
#!/usr/bin/env python3
"""
Transform phase_1_b base datasets into normalized datasets with derived features.
Reads base_d1..d6.csv (OHLC + oracle labels), computes:
- Technical indicators: ATR, RSI, MACD(3), ADX(3), Stochastic(2), CCI,
Williams %R, ROC, Bollinger Band Width
- Derived features: ATR_ratio (TP fe... | harveybc/feature-eng | normalize_phase1b.py | .py | 17a33c4470a3fc42 | 7.45 | 7 |
#!/usr/bin/env python3
"""
Transform phase_1_c base datasets into normalized datasets with derived features.
Reads base_d1..d6.csv (OHLC + direction labels), computes:
- Technical indicators: ATR, RSI, MACD(3), ADX(3), Stochastic(2), CCI,
Williams %R, ROC, Bollinger Band Width
- Derived features: ATR_ratio, BB... | harveybc/feature-eng | normalize_phase1c.py | .py | 67d0d1ba18e02823 | 7.45 | 7 |
# app/config_merger.py
import sys
from typing import List, Dict, Any
from app.config import DEFAULT_VALUES, ARGUMENT_MAPPING
from app.logger import get_logger
logger = get_logger(__name__)
def process_unknown_args(unknown_args: List[str]) -> Dict[str, Any]:
"""
Processes unknown command-line arguments into a... | harveybc/rl-optimizer | app/config_merger.py | .py | e513bd4aadf1ede4 | 7.45 | 7 |
# app/data_handler.py
import pandas as pd
from app.logger import get_logger
from app.reconstruction import unwindow_data # Assuming it's used elsewhere
logger = get_logger(__name__)
def load_csv(file_path: str, headers: bool = False) -> pd.DataFrame:
"""
Loads a CSV file into a pandas DataFrame with optiona... | harveybc/rl-optimizer | app/data_handler.py | .py | 5a5bb195a99d72ca | 7.45 | 7 |
# app/logger.py
import logging
import sys
from logging.handlers import RotatingFileHandler
def setup_logging(
log_level=logging.DEBUG,
log_format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
date_format="%Y-%m-%d %H:%M:%S",
log_file="app.log",
max_bytes=5*1024*1024, # 5 MB
backup_c... | harveybc/rl-optimizer | app/logger.py | .py | eb004b30d73358c5 | 7.45 | 7 |
import datetime
import numpy as np
import sys
class Plugin:
"""
A dummy agent plugin for making predefined actions based on dates.
"""
plugin_params = {
'buy_dates': [
'16/04/2010 20:00',
'20/04/2010 02:00',
'26/04/2010 00:00',
'30/04/2010 18:00'... | harveybc/rl-optimizer | app/plugins/agent_plugin_dummy_automation.py | .py | 60aa962d0c39219d | 7.45 | 7 |
# app/utils.py
import math
import pickle
import zlib
import logging
import numpy as np
import pandas as pd
from app.logger import get_logger
logger = get_logger(__name__)
def kolmogorov_complexity(genome_bytes: bytes, compression_level: int = 9) -> int:
"""
Estimates the Kolmogorov complexity of the given ge... | harveybc/rl-optimizer | app/utils.py | .py | fb83c1aa6c6ff2ea | 7.45 | 7 |
# Boss/star piece randomization data for open mode.
from enum import IntEnum
from randomizer.logic import utils
from randomizer.logic.patch import Patch
class Battlefields(IntEnum):
"""Enumeration for ID values for battlefields."""
Bowyer = 0x01
KingCalamari = 0x03
SunkenShip = 0x04
MolevilleMin... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/data/bosses.py | .py | 79a224a74b516128 | 7.63 | 17 |
# Data module for dialog data.
from randomizer.logic import utils
from randomizer.logic.patch import Patch
# This table isn't complete.
# And some of the single char replacements should be done via string.translate,
compression_table = [
('\n', '\x01'),
(' and ', '\x15'),
(' the', '\x0E'),
(' you', '\... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/data/dialogs.py | .py | d89cf70eaff7fd58 | 7.63 | 17 |
# Data module for minigame data.
from randomizer.logic import utils
from randomizer.logic.patch import Patch
# ******** Ball Solitaire
class BallSolitaireGame:
"""Class for ball solitaire minigame."""
class BallSpot:
"""Class for individual ball spot in the game."""
def __init__(self, has_... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/data/games.py | .py | 61adcbf7669f8542 | 7.63 | 17 |
# Data module for areas and location data and base classes for key item/chest shuffle..
from enum import Enum, auto
from inspect import isclass
from randomizer.data import items
from randomizer.logic import utils
from randomizer.logic.patch import Patch
class Area(Enum):
MariosPad = auto()
MushroomWay = aut... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/data/locations.py | .py | 25b3c6e094902e3c | 7.63 | 17 |
import random
from randomizer.data import dialogs
from . import flags
# There's a way to do perfect allocations with DYNAMIC PROGRAMMING,
# but I'm not doing that.
def allocate_string(string_length, free_list):
for base in sorted(free_list, key=lambda x: free_list[x]):
if free_list[base] >= string_length... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/logic/dialogs.py | .py | 85df653e90df3072 | 7.63 | 17 |
# enemy randomization logic.
import random
from functools import reduce
from randomizer.data import bosses, enemies
from randomizer.data.formations import FormationMember
from . import flags, utils
def _randomize_enemy_attack(attack):
"""Randomize a single enemy attack.
Args:
attack(randomizer.data... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/logic/enemies.py | .py | 663e8e9cdc090f4d | 7.63 | 17 |
from django.core.serializers.json import DjangoJSONEncoder
class Patch:
"""Class representing a patch for a specific seed that can be added to as we build it."""
def __init__(self):
self._data = {}
def __add__(self, other):
"""Add another patch to this patch and return a new Patch object... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/logic/patch.py | .py | 7ad883651fcbc950 | 7.63 | 17 |
# Spell randomization logic.
import random
from . import flags, utils
from randomizer.data import enemies
from randomizer.data import spells
def _randomize_spell(spell):
"""Perform randomization for this spell.
Args:
spell(randomizer.data.spells.Spell):
"""
spell.fp = utils.mutate_normal(s... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/logic/spells.py | .py | ecb59d1f1ba3fe63 | 7.63 | 17 |
# Common utilities for outputting binary data for the patches, and shuffling stat values.
import inspect
import random
import re
# Amount to boost very small values when shuffling to give a bit more range for very small values.
SMALL_BOOST_AMOUNT = 2.0
def isclass_or_instance(obj_or_cls, classinfo):
"""Helper f... | Super-Mario-RPG-Randomizer/smrpg_web_randomizer | randomizer/logic/utils.py | .py | b590f9a25b1c3b0a | 7.63 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.