repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
dspasic/aws-cf-update-tags | cfut/update_tags.py | <filename>cfut/update_tags.py<gh_stars>1-10
#! /usr/bin/env python3
__author__ = '<NAME> <<EMAIL>>'
__doc__ = """Updating Tags for Existing CloudFormation Stacks
This script is iterating through all root stacks and updates the tags.
It uses the UsePreviousTemplate and UsePreviousValue for each parameter to
achieve ... |
vincentlux/TextBrewer | src/textbrewer/distiller_multiteacher.py | <reponame>vincentlux/TextBrewer
from .distiller_utils import *
from .distiller_basic import BasicDistiller
class MultiTeacherDistiller(BasicDistiller):
"""
Distills multiple teacher models (of the same tasks) into a student model. **It doesn't support intermediate feature matching**.
Args:
train_c... |
vincentlux/TextBrewer | setup.py | """
Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py
To create the package for pypi.
1. Change the version in __init__.py, setup.py as well as docs/source/conf.py.
2. Commit these changes with the message: "Release: VERSION"
3. Add a tag in git to mark the release: "git tag... |
vincentlux/TextBrewer | src/textbrewer/distillation.py | <reponame>vincentlux/TextBrewer
import torch
from collections import OrderedDict
from tqdm import tqdm
from torch import nn
try:
from tensorboardX import SummaryWriter
except ImportError:
from torch.utils.tensorboard import SummaryWriter
import os, random, json
import numpy as np
import logging
from typing impo... |
vincentlux/TextBrewer | src/textbrewer/distiller_general.py | <reponame>vincentlux/TextBrewer<filename>src/textbrewer/distiller_general.py
from .distiller_utils import *
from .distiller_basic import BasicDistiller
class GeneralDistiller(BasicDistiller):
"""
Supports intermediate features matching. **Recommended for single-teacher single-task distillation**.
Args:
... |
jstarsky/scraping-etsy | etsy/pipelines.py | <reponame>jstarsky/scraping-etsy<filename>etsy/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
# This Pipeline processes several items scraped.
class EtsyPipelin... |
jstarsky/scraping-etsy | etsy/spiders/search_products.py | # -*- coding: utf-8 -*-
#==============================================================================
#title :search_products.py
#description :A spider to scrape etsy.com products based on a search string.
#author :<NAME> (<EMAIL>)
#last Update :12-02-2019
#usage :scrapy crawl sea... |
litchiar/ArknightsAutoHelper | webgui2/worker.py | import logging
import sys
import threading
import multiprocessing
import queue as threading_Queue
import Arknights.helper
import config
from connector.ADBConnector import ADBConnector, ensure_adb_alive
from util.excutil import format_exception
from typing import Mapping
config.background = True
logger = logging.getLo... |
litchiar/ArknightsAutoHelper | addons/base.py | import random
from Arknights.helper import ArknightsHelper
from abc import ABC, abstractmethod
import time
import cv2
from PIL import Image
import numpy as np
from imgreco import util
def cv2pil(cv_img):
return Image.fromarray(cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB))
def pil2cv(pil_img):
return cv2.cvtCol... |
litchiar/ArknightsAutoHelper | imgreco/main.py | from fractions import Fraction
import numpy as np
from PIL import Image
from util.richlog import get_logger
from . import imgops
from . import resources
from . import util
logger = get_logger(__name__)
def check_main(img):
vw, vh = util.get_vwvh(img.size)
gear1 = img.crop((3.148 * vh, 2.037 * vh, 9.907 * v... |
litchiar/ArknightsAutoHelper | resources/recruit_database.py | recruit_database = [
('Lancet-2', 0, ['医疗干员', '远程位', '治疗', '支援机械']),
('Castle-3', 0, ['近卫干员', '近战位', '支援', '支援机械']),
('夜刀', 1, ['先锋干员', '近战位', '新手']),
('黑角', 1, ['重装干员', '近战位', '新手']),
('巡林者', 1, ['狙击干员', '远程位', '新手']),
('杜林', 1, ['术师干员', '远程位', '新手']),
('12F', 1, ['术师干员', '远程位', '新手']),
... |
frmdstryr/enaml-native-maps | src/googlemaps/android/android_map_view.py | """
Copyright (c) 2017-2018, <NAME>.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on Oct 10, 2017
@author: jrm
"""
from atom.api import Typed, Instance, Dict, Bool, set_default
from googlemaps.widgets.map_view import (
Prox... |
frmdstryr/enaml-native-maps | src/googlemaps/widgets/map_view.py | '''
Copyright (c) 2017, <NAME>.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on Oct 10, 2017
@author: jrm
'''
from atom.api import (
Atom, Typed, ForwardTyped, Unicode, Enum, Bool, Float, Tuple, Event,
ContainerList, obs... |
frmdstryr/enaml-native-maps | src/googlemaps/widgets/api.py | """
Copyright (c) 2017, <NAME>.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on Oct 10, 2017
@author
"""
from .map_view import MapView, MapMarker, MapPolygon, MapPolyline, MapCircle
def install():
from enamlnative.widgets... |
frmdstryr/enaml-native-maps | src/googlemaps/android/factories.py | <gh_stars>1-10
'''
Copyright (c) 2017, <NAME>.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on Oct 29, 2017
@author: jrm
'''
def map_marker_factory():
from .android_map_view import AndroidMapMarker
return AndroidMapMar... |
SansPapyrus683/stresst | stress/strs.py | <reponame>SansPapyrus683/stresst<gh_stars>0
import argparse
import os
import subprocess
def main():
prser = argparse.ArgumentParser(prog="stresst", description="stress test a program with multiple inputs")
prser.add_argument("file", metavar="prgm.py", type=str, nargs=1, help="program to test")
prser.add_a... |
SansPapyrus683/stresst | setup.py | from setuptools import setup, find_packages
long_description = open("README.md").read()
setup(
name='stresst',
version='0.0.3',
author='<NAME>',
author_email='',
url='https://ryanchou.dev',
description='Stress test your Python solutions!',
long_description=long_description,
long_descri... |
bgipson/ComplXML | ComplXML.py | #!/usr/bin/env python3
from tkinter import *
import tkinter.messagebox
import tkinter.filedialog
import traceback
#ComplXML - The LC-3 Test XML Maker
#Created by <NAME>
import os
class mainGUI:
def __init__(self,rootWin):
self.rootWin = rootWin
rootWin.title("ComplXML")
self.testCaseList = [... |
CityU-AIM-Group/SCAN | fcos_core/modeling/discriminator/con_fgbg.py | import torch
import torch.nn.functional as F
from torch import nn
from .layer import GradientReversal
class FCOSDiscriminator_con(nn.Module):
def __init__(self, with_GA=False, fusion_cfg ='concat', num_convs=4, in_channels=256, num_classes=2, grad_reverse_lambda=-1.0, grl_applied_domain='both', cfg = None,patch_s... |
CityU-AIM-Group/SCAN | fcos_core/modeling/rpn/fcos/condgraph.py | <reponame>CityU-AIM-Group/SCAN
# --------------------------------------------------------
# SCAN: Cross-domain Object Detection with Semantic Conditioned Adaptation (AAAI22 ORAL)
# Written by <NAME>
# This file covers the core operation on the feature maps for domain adaptation
# ---------------------------------------... |
CityU-AIM-Group/SCAN | fcos_core/engine/validation.py | <reponame>CityU-AIM-Group/SCAN<filename>fcos_core/engine/validation.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import time
import os
import torch
from tqdm import tqdm
from fcos_core.data.datasets.evaluation import validate
from ..utils.comm import is_main_process, get_w... |
CityU-AIM-Group/SCAN | fcos_core/modeling/rpn/fcos/loss.py | # --------------------------------------------------------
# SCAN: Cross-domain Object Detection with Semantic Conditioned Adaptation (AAAI22 ORAL)
# Modified by <NAME>
# This file contains specific functions for computing losses of FCOS
# This file covers the core operation for node sampling
# ------------------------... |
CityU-AIM-Group/SCAN | fcos_core/modeling/discriminator/fcos_head_discriminator_CA.py | <reponame>CityU-AIM-Group/SCAN
import torch
import torch.nn.functional as F
from torch import nn
from .layer import GradientReversal, FocalLoss
class FCOSDiscriminator_CA(nn.Module):
def __init__(self, num_convs=2, in_channels=256, grad_reverse_lambda=-1.0, center_aware_weight=0.0, center_aware_type='ca_loss', gr... |
CityU-AIM-Group/SCAN | fcos_core/engine/trainer.py | <filename>fcos_core/engine/trainer.py<gh_stars>1-10
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import datetime
import logging
import time
# import ipdb
import torch
import torch.distributed as dist
from fcos_core.utils.comm import get_world_size, is_pytorch_1_1_0_or_later
from fcos_core.ut... |
CityU-AIM-Group/SCAN | fcos_core/modeling/discriminator/fcos_head_discriminator_con.py | # --------------------------------------------------------
# SCAN: Cross-domain Object Detection with Semantic Conditioned Adaptation (AAAI22 ORAL)
# Written by <NAME>
# This file covers the Conditonal Kernel guided Alignment (CKA)
# --------------------------------------------------------
import torch
import torch.nn.... |
CityU-AIM-Group/SCAN | fcos_core/vis_tools.py | <gh_stars>1-10
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import ipdb
import time
class VIS_TOOLS():
def __init__(self,root='/home/wuyangli2/Pictures/visualization/vgg_cs/'):
self.root = ... |
Cefer01234/SongPlayRoBot | TamilBots/__main__.py | from config import OWNER_ID
from pyrogram.types.bots_and_keyboards import reply_keyboard_markup
from TamilBots.modules import *
from pyrogram import idle, filters
from pyrogram.types import InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardButton
from TamilBots import app, LOGGER
from TamilBots.TamilBots im... |
Cefer01234/SongPlayRoBot | config.py | import os
API_ID = int(os.getenv("2630368"))
API_HASH = os.getenv("658ba9e18a4fec6bc76e2f87734d5514"))
BOT_TOKEN = os.getenv("1970844353:<KEY>"))
DATABASE_URL = os.getenv("DATABASE_URL")
OWNER_ID = list({int(x) for x in os.environ.get("OWNER_ID", "").split()})
|
hugovk/python-quantities | quantities/umath.py | <gh_stars>0
import numpy as np
from .quantity import Quantity
from .units import dimensionless, radian, degree
from .decorators import with_doc
#__all__ = [
# 'exp', 'expm1', 'log', 'log10', 'log1p', 'log2'
#]
@with_doc(np.prod)
def prod(a, axis=None, dtype=None, out=None):
return a.prod(axis, dtype, out)
... |
hugovk/python-quantities | quantities/quantity.py | <reponame>hugovk/python-quantities<filename>quantities/quantity.py
"""
"""
import copy
from functools import wraps
import numpy as np
from . import markup
from .dimensionality import Dimensionality, p_dict
from .registry import unit_registry
from .decorators import with_doc
PREFERRED = [] # List of preferred quant... |
KarolisRam/MineRL2021-Research-baselines | standalone/Behavioural_cloning.py | """
A baseline solution using behavioural cloning in the research track of NeurIPS 2021 MineRL Diamond competition.
With default parameters it trains in 15-20 mins on a machine with a GeForce RTX 2080 Ti GPU.
It uses less than 16GB RAM, achieves an average reward of 1.8 and sometimes obtains cobblestone (35 total rewar... |
anthonykoch/SublimeTools | tests/test_EventEmitter.py | <gh_stars>0
import sublime
import sys
from unittest import TestCase
from unittest.mock import MagicMock
version = sublime.version()
from SublimeTools.EventEmitter import EventEmitter
class TestCase(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_event_emitter(self)... |
anthonykoch/SublimeTools | Settings.py | <reponame>anthonykoch/SublimeTools<filename>Settings.py<gh_stars>0
import sublime
class Settings(object):
"""
A wrapper for a sublime.Settings object. This class will automatically reload
the underlying settings object, creating a sort of live binding to what is
actually defined in the settings in that... |
anthonykoch/SublimeTools | tests/test_Settings.py | <filename>tests/test_Settings.py
import sublime
import sys
from unittesting import DeferrableTestCase
from unittest.mock import MagicMock
from SublimeTools.Settings import Settings
from SublimeTools.cuid import cuid
version = sublime.version()
settings_name = 'SublimeTools.sublime-settings'
class TestSettings(De... |
anthonykoch/SublimeTools | Utils.py | import sublime_plugin
import sublime
import string
import random
class Init(object):
""" A class that inits itself with whatever properties are give """
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
# https://stackoverflow.com/questions/295541... |
anthonykoch/SublimeTools | View.py | <reponame>anthonykoch/SublimeTools
import collections
import sublime
from sublime import Region
from .Utils import pluck
def is_length(value):
return isinstance(value, int) and value >= 0
class Position(object):
"""
Represents an AST position object.
Represents
"""
def __init__(self, sta... |
anthonykoch/SublimeTools | tests/test_View.py | import sublime
import sys
from sublime import Region
from unittesting import DeferrableTestCase
from unittest.mock import MagicMock
from SublimeTools.View import *
from SublimeTools.cuid import cuid
version = sublime.version()
views = []
invalid_points = [None, '', -1, float('nan'), {}, []]
class TestExec(Defer... |
anthonykoch/SublimeTools | Exec.py | import sublime
import os
from Default.exec import AsyncProcess
from .EventEmitter import EventEmitter
class ProcessListener(EventEmitter):
# """
# A listener for AsyncProcess, to be used in tangent with exec_cmd(), execjs(), and execjsfile().
# The handlers for on
# Example:
# listener = Pro... |
anthonykoch/SublimeTools | Logging.py |
DEBUG = 1 << 1
INFO = 1 << 2
WARNING = 1 << 3
ERROR = 1 << 4
CRITICAL = 1 << 5
DEFAULT_LEVELS = int('11111', 2)
class Logger(object):
"""
TODO: Figure out why the default logger doesn't work as expected
"""
def __init__(self, name="", level=DEFAULT_LEVELS):
self.level = level
self.nam... |
anthonykoch/SublimeTools | tests/test_Exec.py | import sublime
import sys
from unittesting import DeferrableTestCase
from unittest.mock import MagicMock
from SublimeTools.Exec import exec_cmd, execjsfile, ProcessListener
from SublimeTools.cuid import cuid
version = sublime.version()
class TestExec(DeferrableTestCase):
def setUp(self):
pass
de... |
Rahulgulia/greyatom-python-for-data-science | Project:-Loan-Approval-Analysis/code.py | # --------------
# Importing header files
import numpy as np
import pandas as pd
from scipy.stats import mode
import warnings
warnings.filterwarnings('ignore')
#Reading file
bank_data = pd.read_csv(path)
#Code starts here
bank = pd.DataFrame(bank_data)
categorical_var = bank.select_dtypes(include ... |
bhaveshAn/mycroft-business-news-read | __init__.py | <gh_stars>0
# TODO: Add an appropriate license to your skill before publishing. See
# the LICENSE file for more information.
# Below is the list of outside modules you'll be using in your skill.
# They might be built-in to Python, from mycroft-core or from external
# libraries. If you use an external library, be sur... |
JonasGovaerts/openshift-applier | build/script/namespace_applier.py | import git
import sys
import os
import time
import subprocess
import shutil
from datetime import datetime
def log(logMessage):
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print('{"timestamp":"'+dt_string+'","message":"'+logMessage+'"}')
def pause():
try:
log("sleeping for " + timer ... |
sysbot/route53manager | route53/views/zones.py | from boto.route53.exception import DNSServerError
from flask import Module
from flask import url_for, render_template, \
redirect, flash, request
from route53.forms import ZoneForm
from route53.connection import get_connection
from route53.xmltools import render_change_batch
zones = Module(__name__)
@zone... |
CBarraford/black | authority.py | # proof of authority
from ecdsa import VerifyingKey
import sys
import json
class Authority:
def __init__(self):
self.votes = []
def vote(self, vote):
# this is our first vote, no need to verify it
if len(self.votes) == 0:
self.votes.append(vote)
return True
... |
CBarraford/black | scripts/create_keys.py | <reponame>CBarraford/black
#!/usr/bin/env python
from ecdsa import SigningKey, VerifyingKey
sk = SigningKey.generate() # uses NIST192p
vk = sk.get_verifying_key()
vk_hex = bytearray(vk.to_string()).hex().upper()
sk_hex = bytearray(sk.to_string()).hex().upper()
print("Signature Key: %s" % sk_hex)
print("Verify Key: %... |
CBarraford/black | scripts/create_message.py | <filename>scripts/create_message.py
#!/usr/bin/env python
import sys
from ecdsa import SigningKey, VerifyingKey
if len(sys.argv) != 3:
print("Missing inputs. Pass sig key and message")
sys.exit(1)
sk = sys.argv[1]
message = sys.argv[2]
sk = SigningKey.from_string(bytearray.fromhex(sk))
vk = sk.get_verifyin... |
CBarraford/black | api.py | <gh_stars>0
import hashlib
import json
import sys
from time import time
import requests
from flask import Flask, jsonify, request
import black
import channel
import authority
app = Flask(__name__)
@app.route('/join', methods=['POST'])
def join_channel():
values = request.get_json()
required = ['remote_node... |
CBarraford/black | scripts/create_vote.py | <gh_stars>0
#!/usr/bin/env python
import sys
from ecdsa import SigningKey, VerifyingKey
if len(sys.argv) < 4:
print("Missing inputs. Pass signing key, vote (1|2), and last signature")
sys.exit(1)
sk = sys.argv[1]
vote = sys.argv[2]
last_sig = sys.argv[3]
recipient = sys.argv[4] or None
sk = SigningKey.from... |
CBarraford/black | black.py | <filename>black.py
import sys
from uuid import uuid4
import channel
import api
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# place to store all channels (blockchains)
# TODO: all uppercase usually mean immutable, but alas, this var is mutable :(
CHANNELS = {}
... |
CBarraford/black | channel.py | <reponame>CBarraford/black
import hashlib
import sys
from time import time
from urllib.parse import urlparse
import json
import requests
from ecdsa import VerifyingKey
import authority
class Channel:
def __init__(self, name):
self.name = name
self.created_at = time()
self.ref = hashlib.s... |
tmoer/a0c | src/network.py | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Neural network specification
@author: thomas
"""
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import random
from common.rl.make_game import check_space
from pdb import set_trace
class Model():
def __init_... |
tmoer/a0c | src/rl/atariwrapper.py | # -*- coding: utf-8 -*-
"""
Atari wrapper, based on https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py
@author: thomas
"""
import gym
from gym import spaces
from collections import deque
import numpy as np
from PIL import Image
class ClipRewardWrapper(gym.RewardWrapper):
def reward(... |
tmoer/a0c | src/rl/make_game.py | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Wrapper to generate the game environments
@author: thomas
"""
import gym
import numpy as np
from rl.rewardwrapper import RewardWrapper,PILCOWrapper,NormalizeWrapper
from rl.atariwrapper import AtariWrapper,ClipRewardWrapper
from rl.envs.chain import Chain, ChainOrdered
#from r... |
tmoer/a0c | src/rl/policies.py | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Various policies
@author: thomas
"""
import numpy as np
import logging
logger = logging.getLogger('root')
logger.propagate = False
def policy(policy,model,hps,seed,eval_on_mean_output=False,eval_on_mean_params=False):
''' wrapper policy function '''
pass
def thom... |
tmoer/a0c | src/rl/rewardwrapper.py | # -*- coding: utf-8 -*-
"""
Chain environment
@author: thomas
"""
import gym.spaces
import gym
import numpy as np
from gym import Wrapper
class NormalizeWrapper(object):
''' Heuristically normalizes the reward scale for CartPole and MountainCar '''
def __init__(self,name):
# n = length of chain
... |
tmoer/a0c | submit.py | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Wrapper for submit function
@author: thomas
"""
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
import argparse
from src.common.submit import submi... |
tmoer/a0c | src/mcts.py | <reponame>tmoer/a0c<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
MCTS with tree uncertainty
@author: <NAME>, Delft University of Technology
"""
import numpy as np
import random
import copy
import time
from pdb import set_trace
from common.putils import my_argmax, timing
def bring_Env_to_correct_state(Env,seed,a_his):
... |
tmoer/a0c | jobs/expand_jobs_over_games.py | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Expand a submission over games
@author: thomas
"""
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))
import os
import argparse
from common.visualize import mak... |
tmoer/a0c | src/rl/envs/chain.py | # -*- coding: utf-8 -*-
"""
Chain environment
@author: thomas
"""
import gym.spaces
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from rl.policies import get_net_mean, get_net_params, sample_sd, analytic_sd, thompson_policy, ucb_policy
import matplotlib.patches as patches
#plt.style.... |
tmoer/a0c | config/hps.py | # -*- coding: utf-8 -*-
"""
Default hyperparameter settings
@author: thomas
"""
from common.hps_setup import HParams
def override_hps_settings(hps):
''' some more global modifications to multiple settings based on 1 indicator '''
if hps.mode == 'off':
pass
return hps
def get_hps():
''' Hyp... |
tmoer/a0c | agent.py | # -*- coding: utf-8 -*-
"""
Chain experiments
@author: thomas
"""
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
global mpl
import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import os
import time
from te... |
frknayk/Q-Iteration | q_learn_train_bin_2.py | <gh_stars>0
import gym
import numpy as np
import random
from math import pow
from math import sqrt
from math import exp
import pandas
import matplotlib.pyplot as plt
class QLearn:
def __init__(self, actions, epsilon, alpha, gamma):
# Defining Q table as dictionary,
# provides us to empt... |
frknayk/Q-Iteration | q_learn_inference_bin.py | <reponame>frknayk/Q-Iteration
import numpy as np
import matplotlib.pyplot as plt
cartPos = np.load('CartPosByTime.npy')
PoleAngle = np.load('AngularPosByTime.npy')
control_vals = np.load('ControlSignalByTime.npy')
# Plotting
plt.figure(1)
plt.plot(cartPos, label='Cart Position')
plt.plot(PoleAngle, label='A... |
pvsfair/architecture-patterns-python | app/infrastructure/repository.py | <gh_stars>0
from typing import List, Set
from app.domain.models.Batch import Batch
from .abstract_repository import AbstractRepository
class SqlAlchemyRepository(AbstractRepository):
def __init__(self, session) -> None:
self.session = session
def add(self, batch: Batch):
self.session.add(batc... |
pvsfair/architecture-patterns-python | app/infrastructure/orm.py | from sqlalchemy import (
Table,
MetaData,
Column,
Integer,
String,
Date,
ForeignKey,
)
from sqlalchemy.orm import mapper, relationship
from app.domain.models.OrderLine import OrderLine
from app.domain.models.Batch import Batch
metadata = MetaData()
order_lines = Table(
"order_lines",
... |
pvsfair/architecture-patterns-python | app/domain/models/OrderLine.py | from dataclasses import dataclass
@dataclass(unsafe_hash=True)
class OrderLine:
orderid: str
sku: str
qty: int
|
pvsfair/architecture-patterns-python | app/domain/exeptions.py | <gh_stars>0
class OutOfStock(Exception):
pass
|
pvsfair/architecture-patterns-python | app/domain/models/allocate.py | from app.domain.exeptions import OutOfStock
from app.domain.models.OrderLine import OrderLine
from app.domain.models.Batch import Batch
from typing import List
def allocate(line: OrderLine, batches: List[Batch]) -> str:
try:
batch = next(b for b in sorted(batches) if b.can_allocate(line))
except StopI... |
pvsfair/architecture-patterns-python | app/infrastructure/abstract_repository.py | from abc import ABC, abstractmethod
from typing import List
from app.domain.models.Batch import Batch
class AbstractRepository(ABC):
@abstractmethod
def add(self, batch: Batch):
raise NotImplementedError
@abstractmethod
def get(self, reference) -> Batch:
raise NotImplementedError
... |
pvsfair/architecture-patterns-python | app/tests/unit/test_batch.py | <filename>app/tests/unit/test_batch.py
from datetime import date
from app.domain.models.Batch import Batch
from app.domain.models.OrderLine import OrderLine
def make_batch_and_line(sku, batch_qty, line_qty):
return (
Batch("batch-001", sku, qty=batch_qty, eta=date.today()),
OrderLine("order-123", ... |
hobbyelektroniker/Micropython-Grundlagen | 003_Textformatierung/Code/textformatierung4.py | '''
Micropython mit ESP32
<NAME>
Version 1.00, 17.10.2019
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
text = "Das Resultat von {Rechnung} ist {Resultat}"
print(text.format(Rechnun... |
hobbyelektroniker/Micropython-Grundlagen | 011_Globale und lokale Variablen/Code/global1.py | a = "Die Zahl lautet"
b = 5
def ausgabe1():
print("*** Ausgabe 1 ***")
print(a,b)
print()
def ausgabe2():
print("*** Ausgabe 2 ***")
a = "Eine andere Zahl:"
b = 7
print(a,b)
print()
print("Globale Werte: a = {}, b = {}".format(a,b))
ausgabe1()
print("Globale Werte: a = {}, b = {}".for... |
hobbyelektroniker/Micropython-Grundlagen | 012_Micropython, ESP32 und das Multitasking/Code/Blink4.py | <reponame>hobbyelektroniker/Micropython-Grundlagen<filename>012_Micropython, ESP32 und das Multitasking/Code/Blink4.py
# Gleichzeitiger Blink mit Argumenten
# mit Multithreading
from machine import Pin
import time
import _thread
rot = Pin(33, Pin.OUT)
gruen = Pin(25, Pin.OUT)
gelb = Pin(32, Pin.OUT)
anzahl = 10
de... |
hobbyelektroniker/Micropython-Grundlagen | 013_Klassen in Micropython/Code/quadrat_klasse.py | '''
Objektorientiert Programmierung
Eine Klasse für ein Quadrat
Version 1.00, 27.02.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
# Quadrat
import math
from bewegt_klasse impo... |
hobbyelektroniker/Micropython-Grundlagen | 011_Globale und lokale Variablen/Code/global4.py |
def ausgabe3(a,b,c):
print("*** Ausgabe 3 ***")
a = "Eine andere Zahl:"
b = 7
c[1] = 2
c = [1,7,4,6,5]
c[2] = 12
print(a,b,c)
print()
a = "Die Zahl lautet"
b = 5
c = [1,3,5]
print("Globale Werte: a = {}, b = {}, c = {}".format(a,b,c))
ausgabe3(a,b,c)
print("Globale Werte: a = {}, b =... |
hobbyelektroniker/Micropython-Grundlagen | 009_Bedingungen und Schleifen/Code/while1.py | <reponame>hobbyelektroniker/Micropython-Grundlagen
x = 0
while x < 6:
x += 1
y = 2 * x
print(x,y)
print("-------")
x = 0
while x < 6:
x += 1
y = 2 * x
print(x,y)
if (x == 3): break
print("-------")
x = 0
while True:
x += 1
y = 2 * x
print(x,y)
if (x > 5): break
print("---... |
hobbyelektroniker/Micropython-Grundlagen | 012_Micropython, ESP32 und das Multitasking/Code/Blink1.py | <reponame>hobbyelektroniker/Micropython-Grundlagen
# Einfacher Blink
# ohne Multithreading
from machine import Pin
import time
rot = Pin(33, Pin.OUT)
gruen = Pin(25, Pin.OUT)
gelb = Pin(32, Pin.OUT)
anzahl = 5
def blink_rot():
for i in range(anzahl):
rot.on()
time.sleep(1)
rot.off()
... |
hobbyelektroniker/Micropython-Grundlagen | 010_Funktionen/Code/func1.py | def flaeche(a, b):
rechtecksflaeche = a * b # Rechteck mit den Seiten a und b
dreiecksflaeche = a * b / 2 # Dreieck mit Grundlinie a und Höhe b
return rechtecksflaeche, dreiecksflaeche
a = 3
b = 5
resultat = flaeche(a,b) # Gibt Tupel zurück
print(resultat)
print(resultat[1])
rechteck, dreieck ... |
hobbyelektroniker/Micropython-Grundlagen | 014_Klassen in Micropython 2/Code/demo.py | '''
Objektorientiert Programmierung
Eine Demo mit mehreren Objekten
Version 1.0, 15.03.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
from tkinter import *
from kreis_klasse im... |
hobbyelektroniker/Micropython-Grundlagen | 013_Klassen in Micropython/Code/Objekte3.py | '''
Objektorientiert Programmierung
Ein bewegtes Objekt
Version 1.00, 27.02.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
from tkinter import *
from kreis_klasse import KreisV... |
hobbyelektroniker/Micropython-Grundlagen | 005_Mengentypen - Set/Code/sets.py | <filename>005_Mengentypen - Set/Code/sets.py
# Ein Set mit vorgegebenen Werten erzeugen
set1 = {"Hallo",3,1.25,"Welt"}
print(set1)
# Ein leeres Set erzeugen
set2 = set()
print(set2)
# Elemente zum Set hinzufügen
set2.add("neu")
set2.add("Hallo")
set2.add(5)
print(set2)
# Ein Set aus einem anderen Set erzeugen
set3 =... |
hobbyelektroniker/Micropython-Grundlagen | 003_Textformatierung/Code/textformatierung2.py | '''
Micropython mit ESP32
Ganze Zahlen
Version 1.00, 17.10.2019
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
zahlen = [2,235,15,8,-12]
for zahl in zahlen:
print(zahl)
print()
... |
hobbyelektroniker/Micropython-Grundlagen | 001_Einleitung und erste Schritte/Code/hallo.py | # Hallo!
namen = ("Max","Peter","Monika","Petra")
def sage_hallo(name):
print("Hallo " + name)
for name in namen:
sage_hallo(name)
print("Das war's!")
|
hobbyelektroniker/Micropython-Grundlagen | 012_Micropython, ESP32 und das Multitasking/Code/Blink2.py | <gh_stars>1-10
# Einfacher Blink mit Argumenten
# ohne Multithreading
from machine import Pin
import time
rot = Pin(33, Pin.OUT)
gruen = Pin(25, Pin.OUT)
gelb = Pin(32, Pin.OUT)
anzahl = 5
def blink(led,pause):
for i in range(anzahl):
led.on()
time.sleep(pause)
led.off()
time.sle... |
hobbyelektroniker/Micropython-Grundlagen | 014_Klassen in Micropython 2/Code/Objekte2.py | <gh_stars>1-10
'''
Objektorientiert Programmierung
Kreis und Quadrat
Version 1.00, 27.02.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
from tkinter import *
from kreis_klasse ... |
hobbyelektroniker/Micropython-Grundlagen | 010_Funktionen/Code/func4.py | <gh_stars>1-10
import math
def flaeche(r=None,d=None,g=None,h=None,a=None,b=None):
if r:
return r**2 * math.pi
elif d:
return d**2 * math.pi / 4
elif g and h:
return g * h / 2
elif a:
if not b: b = a
return a * b
else:
return None
print(flae... |
hobbyelektroniker/Micropython-Grundlagen | 010_Funktionen/Code/func3.py | import math
def flaeche(r=None,d=None):
if r:
# if r and not d:
return r**2 * math.pi
elif d:
# elif d and not r:
return d**2 * math.pi / 4
else:
return None
print(flaeche(3))
print(flaeche(r=3))
print(flaeche(d=3))
print(flaeche(3,4))
|
hobbyelektroniker/Micropython-Grundlagen | 008_Mengentypen - Dictionary/Code/dictionaries2.py | <reponame>hobbyelektroniker/Micropython-Grundlagen<filename>008_Mengentypen - Dictionary/Code/dictionaries2.py
# Ein Dictionary mit vorgegebenen Werten erzeugen
dict1 = {
"land": "Schweiz",
"ort": "Bern",
"einwohner": 140000
}
print(dict1)
print()
# Dictionary vollständig löschen
dict2 = dict1.copy()
#del ... |
hobbyelektroniker/Micropython-Grundlagen | 014_Klassen in Micropython 2/Code/kreis_klasse.py | '''
Objektorientiert Programmierung
Eine Kreisklasse
Version 1.10, 15.03.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
# Kreis
from bewegt_klasse import BewegtesObjektV3 as Be... |
hobbyelektroniker/Micropython-Grundlagen | 012_Micropython, ESP32 und das Multitasking/Code/Blink5.py | # Wann wird ein Thread beendet
# und welche Threads sind noch vorhanden
from machine import Pin
import time
import _thread
rot = Pin(33, Pin.OUT)
gruen = Pin(25, Pin.OUT)
gelb = Pin(32, Pin.OUT)
anzahl = 10
thread_list = set() # Liste der aktiven Threads
def blink(name, led, pause):
# Hier startet der Thread
... |
hobbyelektroniker/Micropython-Grundlagen | 010_Funktionen/Code/func2.py | <gh_stars>1-10
def laenge(a, b, *args):
print()
print(args)
total = a+b
for i in args:
total += i
return total
print(laenge(2,3))
print(laenge(2,3,4,10)) |
hobbyelektroniker/Micropython-Grundlagen | 006_Mengentypen - Tuple/Code/tuples.py | # Ein Tuple mit vorgegebenen Werten erzeugen
tup1 = ("Hallo",3,1.25,"Welt",2,3,4,5)
print(tup1)
print()
# Leeres Tuple erzeugen
tup2 = tuple() # macht nicht viel Sinn !!!
print(tup2)
print()
# Aus anderen Collections erzeugen
set1 = {"Hallo",3,1.25,"Welt"}
tup2 = ("Hallo",3,"Jahr 2020",5)
tup1 = tuple(set1)
print(tu... |
hobbyelektroniker/Micropython-Grundlagen | 013_Klassen in Micropython/Code/Objekte1.py | '''
Objektorientiert Programmierung
Ein einfacher Kreis
Version 1.00, 27.02.2021
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
from tkinter import *
from kreis_klasse import KreisV... |
hobbyelektroniker/Micropython-Grundlagen | 004_Einfache Datentypen/Code/einfache_datentypen.py | '''
Micropython Grundlagen
Einfache Datentypen
Version 1.00, 15.12.2019
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
ganze_zahl = 10
dezimalzahl = 5.75
zeichen = 'A'
komplexe_zahl ... |
hobbyelektroniker/Micropython-Grundlagen | 009_Bedingungen und Schleifen/Code/Entscheidungen1.py | <filename>009_Bedingungen und Schleifen/Code/Entscheidungen1.py<gh_stars>1-10
x = 4
print("Die Zahl {}".format(x))
if x < 5:
print(" ist kleiner als 5")
print("-------")
x = 6
print("Die Zahl {}".format(x))
if x < 5:
print(" ist kleiner als 5")
else:
print(" ist grösser als 5")
print("------... |
hobbyelektroniker/Micropython-Grundlagen | 009_Bedingungen und Schleifen/Code/for1.py | <reponame>hobbyelektroniker/Micropython-Grundlagen<filename>009_Bedingungen und Schleifen/Code/for1.py<gh_stars>1-10
menge = (1,3,2,5,3) # Tupel
for x in menge:
print(x)
print("----------")
menge = {1,3,2,5,3} # Set
for x in menge:
print(x)
print("----------")
menge = [1,3,2,5,3] # List
for x in men... |
hobbyelektroniker/Micropython-Grundlagen | 010_Funktionen/Code/func5.py | import math
def flaeche(**kwargs):
print()
print(kwargs)
if "r" in kwargs:
return kwargs["r"]**2 * math.pi
elif "d" in kwargs:
return kwargs["d"]**2 * math.pi / 4
elif "g" in kwargs and "h" in kwargs:
return kwargs["g"] * kwargs["h"] / 2
elif "a" in kwargs:
a = k... |
hobbyelektroniker/Micropython-Grundlagen | 003_Textformatierung/Code/textformatierung3.py | <gh_stars>1-10
'''
Micropython mit ESP32
Floats
Version 1.00, 17.10.2019
Der Hobbyelektroniker
https://community.hobbyelektroniker.ch
https://www.youtube.com/c/HobbyelektronikerCh
Der Code kann mit Quellenangabe frei verwendet werden.
'''
zahlen = [2.5,235.25,15.3,8.735,-12.37]
for zahl in zahlen:
... |
hobbyelektroniker/Micropython-Grundlagen | 008_Mengentypen - Dictionary/Code/dictionaries1.py | # Ein Dictionary mit vorgegebenen Werten erzeugen
dict1 = {
"land": "Schweiz",
"ort": "Bern",
"einwohner": 140000
}
print(dict1)
print()
# Leeres Dictionary erzeugen
dict2 = dict()
print(dict2)
print()
# Aus einem anderen Dictionary erzeugen
dict3 = dict1.copy()
print(dict3)
print()
dict4 = dict(dict1)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.