Exemplo n.º 1
0
def CreateModelVariableEnum(enum_name, enum_desc, member_data):

    def getDesc(self):
        return self._enum_desc

    def getMemberDesc(self, name):
        return self._member_desc[name]

    values = OrderedDict()
    descriptions = OrderedDict()

    for name, value, desc in member_data:
        values[name] = value
        descriptions[name] = desc

    obj = IntEnum(enum_name, values)
    obj._enum_desc = enum_desc
    obj._member_desc = descriptions
    obj.getDesc = types.MethodType(getDesc, obj)
    obj.getMemberDesc = types.MethodType(getMemberDesc, obj)

    return obj
Exemplo n.º 2
0
class Weather(Producer):
    """Defines a simulated weather model"""

    status = IntEnum("status",
                     "sunny partly_cloudy cloudy windy precipitation",
                     start=0)

    rest_proxy_url = "http://rest-proxy:8082"

    key_schema = None
    value_schema = None

    winter_months = set((0, 1, 2, 3, 10, 11))
    summer_months = set((6, 7, 8))

    def __init__(self, month):
        super().__init__("com.udacity.weather",
                         key_schema=Weather.key_schema,
                         value_schema=Weather.value_schema,
                         num_partitions=6,
                         num_replicas=1)

        self.status = Weather.status.sunny
        self.temp = 70.0
        if month in Weather.winter_months:
            self.temp = 40.0
        elif month in Weather.summer_months:
            self.temp = 85.0

        if Weather.key_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_key.json"
                      ) as f:
                Weather.key_schema = json.load(f)

        if Weather.value_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_value.json"
                      ) as f:
                Weather.value_schema = json.load(f)

    def _set_weather(self, month):
        """Returns the current weather"""
        mode = 0.0
        if month in Weather.winter_months:
            mode = -1.0
        elif month in Weather.summer_months:
            mode = 1.0
        self.temp += min(max(-20.0, random.triangular(-10.0, 10.0, mode)),
                         100.0)
        self.status = random.choice(list(Weather.status))

    def run(self, month):
        self._set_weather(month)
        resp = requests.post(
            f"{rest_proxy_url}/topics/{self.topic_name}",
            headers={"Content-Type": "application/vnd.kafka.avro.v2+json"},
            data=json.dumps({
                "key_schema":
                json.dumps(Weather.key_schema),
                "value_schema":
                json.dumps(Weather.value_schema),
                "records": [{
                    "key": {
                        "timestamp": self.time_millis()
                    },
                    "value": {
                        "temperature": self.temp,
                        "status": self.status.name
                    }
                }]
            }),
        )
        resp.raise_for_status()

        logger.debug(
            "sent weather data to kafka, temp: %s, status: %s",
            self.temp,
            self.status.name,
        )
Exemplo n.º 3
0
from enum import IntEnum

KTHREAD_STATE = IntEnum(
    'KTHREAD_STATE',
    ('Initialized', 'Ready', 'Running', 'Standby', 'Terminated', 'Waiting',
     'Transition', 'DefferedReady', 'GateWaitObsolete',
     'WaitingForProcessInSwap', 'MaximumThreadState'),
    start=0)

KWAIT_REASON = IntEnum(
    'KWAIT_REASON',
    ('Executive', 'FreePage', 'PageIn', 'PoolAllocation', 'DelayExecution',
     'Suspended', 'UserRequest', 'WrExecutive', 'WrFreePage', 'WrPageIn',
     'WrPoolAllocation', 'WrDelayExecution', 'WrSuspended', 'WrUserRequest',
     'WrEventPair', 'WrQueue', 'WrLpcReceive', 'WrLpcReply', 'WrVirtualMemory',
     'WrPageOut', 'WrRendezvous', 'WrKeyedEvent', 'WrTerminated',
     'WrProcessInSwap', 'WrCpuRateControl', 'WrCalloutStack', 'WrKernel',
     'WrResource', 'WrPushLock', 'WrMutex', 'WrQuantumEnd', 'WrDispatchInt',
     'WrPreempted', 'WrYieldExecution', 'WrFastMutex', 'WrGuardedMutex',
     'WrRundown', 'WrAlertByThreadId', 'WrDeferredPreempt',
     'MaximumWaitReason'),
    start=0)
Exemplo n.º 4
0
def _create_int_enum(name, mappings):
    return IntEnum(name, {k.upper(): v for k, v in mappings.items()})
Exemplo n.º 5
0
from tkinter import *
from tkinter import ttk
from abc import ABC, abstractmethod
from functools import partial
from enum import Enum, IntEnum
from mywidgets import MyCombobox, TextEntry, MyLabel, ToolTip
import paths

EditableGroupAction = IntEnum('EditableGroupAction', 'new edit choose save')


class EditSaveFunctionBar(ttk.Frame):
    """
    Class provides a ttk.Frame containing 4 Buttons choose, edit, new, save
    """
    def __init__(self, parent, callback):
        ttk.Frame.__init__(self, parent)
        self._callback = callback
        self._createButtons()

    def _createButtons(self):
        # Button style
        s = ttk.Style()
        s.theme_use('clam')
        s.configure("My.TButton", padding=0, relief="flat", borderwidth=1)

        imagepath = paths.getMyWidgetsImagePath()
        # Button "Choose"
        self.dropdownpng = PhotoImage(file=imagepath + "/dropdown_22x22.png")
        self.chooseBtn = ttk.Button(
            self,
Exemplo n.º 6
0
class TimeSimulation:
    weekdays = IntEnum("weekdays", "mon tue wed thu fri sat sun", start=0)
    ten_min_frequency = datetime.timedelta(minutes=10)

    def __init__(self, sleep_seconds=5, time_step=None, schedule=None):
        """Initializes the time simulation"""
        self.sleep_seconds = sleep_seconds
        self.time_step = time_step
        if self.time_step is None:
            self.time_step = datetime.timedelta(minutes=self.sleep_seconds)

        # Read data from disk
        self.raw_df = pd.read_csv(
            f"{Path(__file__).parents[0]}/data/cta_stations.csv").sort_values(
                "order")

        # Define the train schedule (same for all trains)
        self.schedule = schedule
        if schedule is None:
            self.schedule = {
                TimeSimulation.weekdays.mon: {
                    0: TimeSimulation.ten_min_frequency
                },
                TimeSimulation.weekdays.tue: {
                    0: TimeSimulation.ten_min_frequency
                },
                TimeSimulation.weekdays.wed: {
                    0: TimeSimulation.ten_min_frequency
                },
                TimeSimulation.weekdays.thu: {
                    0: TimeSimulation.ten_min_frequency
                },
                TimeSimulation.weekdays.fri: {
                    0: TimeSimulation.ten_min_frequency
                },
                TimeSimulation.weekdays.sat: {
                    0: TimeSimulation.ten_min_frequency
                },
                TimeSimulation.weekdays.sun: {
                    0: TimeSimulation.ten_min_frequency
                },
            }

        self.train_lines = []
        self.train_lines = [
            Line(Line.colors.blue, self.raw_df[self.raw_df["blue"]]),
            Line(Line.colors.red, self.raw_df[self.raw_df["red"]]),
            Line(Line.colors.green, self.raw_df[self.raw_df["green"]]),
        ]

    def run(self):
        curr_time = datetime.datetime.utcnow().replace(hour=0,
                                                       minute=0,
                                                       second=0,
                                                       microsecond=0)
        logger.info("Beginning simulation, press Ctrl+C to exit at any time")
        logger.info("loading kafka connect jdbc source connector")
        configure_connector()

        logger.info("beginning cta train simulation")
        weather = Weather(curr_time.month)
        try:
            while True:
                logger.debug("simulation running: %s", curr_time.isoformat())
                # Send weather on the top of the hour
                if curr_time.minute == 0:
                    weather.run(curr_time.month)
                _ = [
                    line.run(curr_time, self.time_step)
                    for line in self.train_lines
                ]
                curr_time = curr_time + self.time_step
                time.sleep(self.sleep_seconds)
        except KeyboardInterrupt as e:
            logger.info("Shutting down")
            _ = [line.close() for line in self.train_lines]
Exemplo n.º 7
0
 def __str__(self):
     rank_string = IntEnum.__str__(self)
     rank_split = rank_string.partition(".")
     return rank_split[2]
Exemplo n.º 8
0
except ImportError:
    errno = None
EBADF = getattr(errno, "EBADF", 9)
EAGAIN = getattr(errno, "EAGAIN", 11)
EWOULDBLOCK = getattr(errno, "EWOULDBLOCK", 11)

__all__ = ["fromfd", "getfqdn", "create_connection", "AddressFamily", "SocketKind"]
__all__.extend(os._get_exports_list(_socket))

# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
# nicer string representations.
# Note that _socket only knows about the integer values. The public interface
# in this module understands the enums and translates them back from integers
# where needed (e.g. .family property of a socket object).

IntEnum._convert("AddressFamily", __name__, lambda C: C.isupper() and C.startswith("AF_"))

IntEnum._convert("SocketKind", __name__, lambda C: C.isupper() and C.startswith("SOCK_"))

IntFlag._convert("MsgFlag", __name__, lambda C: C.isupper() and C.startswith("MSG_"))

IntFlag._convert("AddressInfo", __name__, lambda C: C.isupper() and C.startswith("AI_"))

_LOCALHOST = "127.0.0.1"
_LOCALHOST_V6 = "::1"


def _intenum_converter(value, enum_klass):
    """Convert a numeric family value to an IntEnum member.

    If it's not a known member, return the numeric value itself.
Exemplo n.º 9
0
import howToImportOwnModule
import math

from enum import IntEnum

FigureFields = IntEnum('FigureFields',
                       'Rectangle Square Triangle Trapezoidal Wheels')

choice = int(
    input('''You want to calculate fild of:
1 - rectangle area
2 - square area
3 - triangle area
4 - trapezoidal area
5 - wheels area
'''))
if (choice == FigureFields.Rectangle):
    a = int(input('the length of the first side: '))
    b = int(input('length of the other side: '))
    print('Rectangle area =', howToImportOwnModule.rectangleArea(a, b))
elif (choice == FigureFields.Square):
    a = int(input('side length: '))
    print('Square area =', howToImportOwnModule.squareArea(a))
elif (choice == FigureFields.Triangle):
    a = int(input('triangle base: '))
    h = int(input('triangle height: '))
    print('Triangle area =', howToImportOwnModule.triangleArea(a, h))
elif (choice == FigureFields.Trapezoidal):
    a = int(input('shorter base length: '))
    b = int(input('length of the longer base: '))
    h = int(input('trapezoidal height: '))
Exemplo n.º 10
0
# (C,G,T), (C,G,A), (C,T,A), (C,T,G), (C,A,G), (C,A,T)
# etc.


FOR X IN POSSIBLEVALS PRODUCES: 4^2 RESULTS
('A', 'A', 'A'), ('A', 'A', 'C'), ('A', 'A', 'G'), ('A', 'A', 'T'), ('A', 'C', 'A'), ('A', 'C', 'C'), ('A', 'C', 'G'), 
('A', 'C', 'T'), ('A', 'G', 'A'), ('A', 'G', 'C'), ('A', 'G', 'G'), ('A', 'G', 'T'), ('A', 'T', 'A'), ('A', 'T', 'C'), 
('A', 'T', 'G'), ('A', 'T', 'T')

print(codons)
"""

from enum import IntEnum
from typing import Tuple, List

Nucleotide: IntEnum = IntEnum('Nucleotide', ('A', 'C', 'G', 'T'))
# IntEnum gives us comparison operators 'for free', such as <, >=, and so on...
# This is necessary for the search algorithms I'll be using to work

# Codons can be defined as a tuple of three nucleotides
Codon = Tuple[Nucleotide, Nucleotide, Nucleotide]  # type alias for codons
# A gene may be defined as a list of codons
Gene = List[Codon]  # tye alias for genes

# genes on the internet will be in a file format that contains a giant string representing all the nucleotides in the gene's sequence.

# let's define an imaginary gene
gene_str: str = "ACGTGGCTCTCTAACGTACGTACGTACGGGGTTTATATATACCCTAGGACTCCCTTT"

# We also need a utility function to convert a str into a Gene
Exemplo n.º 11
0
            current = (self.ref_qsparams[i] for i in range(i1, i2))
            target = (case_qsparams[j] for j in range(j1, j2))

            for _, cur, targ in zip(_alt_range(i1, i2, j1, j2), current,
                                    target):
                if cur[0] == targ[0]:
                    yield {'field': cur[0], 'chg': cur[1], 'to': targ[1]}
                else:
                    yield {'field': cur[0], 'del': cur[1]}
                    yield {'field': targ[0], 'add': targ[1]}
            for field, value in current:
                yield {'field': field, 'del': value}
            for field, value in target:
                yield {'field': field, 'add': value}


JSON_TYPES = (type(None), str, int, float, list, dict
              )  # list and dict must be the last two, in that order
JsonType = IntEnum('JsonType', list(t.__name__ for t in JSON_TYPES))
JsonType.is_collection = property(lambda self: self >= self.list)
JsonType.construct = lambda self: JSON_TYPES[self.value - 1]()
lookup_json_type = dict(zip(JSON_TYPES, JsonType)).get


def _is_jsonic_body(body):
    return not isinstance(body, (str, bytes))


def _alt_range(i1, i2, j1, j2):
    return range(min(i2 - i1, j2 - j1))
Exemplo n.º 12
0
#!/usr/bin/env python3.7
from enum import Enum, IntEnum
import time

enum = Enum('Menu', 'Pizza Lasagna Spaghetti')
enum3 = IntEnum('Menu', 'Pizza Lasagna Spaghetti')
choice = input("""
        Co zjesz?:
        1. Pizza
        2. Lasagna
        3. Spaghetti
        """)

start = time.perf_counter()

if int(choice) == enum.Pizza.value:
    print("Pizza time!")

if int(choice) == enum3.Pizza:
    print("Pizza time!")

end = time.perf_counter()

time = end - start
print("Time: ", time)
Exemplo n.º 13
0
class Ventilator:
    from enum import IntEnum, Enum
    parameters = IntEnum(
        'parameters',
        ['time', 'pressure', 'flow', 'volume', 'p_alv', 'peak_flow'])
    phase = Enum('phase', ['inspiratory', 'expiratory', 'inspiratory_pause'])
    settings = Enum('settings', [
        'respiratory_rate', 'peep', 'inspiratory_pause', 'flow', 'rise_time',
        'flow_pattern', 'volume_target', 'pressure_target', 'inspiratory_time',
        'flow_trigger'
    ])

    CLOSE_ENOUGH = 0.001

    global_defaults = {
        settings.respiratory_rate: 10,
        settings.peep: 0,
        settings.inspiratory_pause: 0,
        settings.rise_time: 0
    }
    mode_defaults = {}

    def __init__(self, patient):
        self.patient = None
        self.setOutputLength(10)
        self.current_settings = {}

        if patient is None:
            patient = Patient()
        self.patient = patient
        self.patient.veilator = self

    def __getitem__(self, key):
        if self.settings[key] in self.current_settings:
            return self.current_settings[self.settings[key]]

        if self.settings[key] in self.mode_defaults:
            return self.mode_defaults[self.settings[key]]

        return self.global_defaults[self.settings[key]]

    def __setitem__(self, key, value):
        self.current_settings[self.settings[key]] = value

    def setOutputLength(self, length):
        self.output_length = length
        self.output = np.full((self.output_length, len(self.parameters)),
                              np.nan)
        self.output[0, :] = 0

    def simulate(self, time_length, time_step):
        self.setOutputLength(int(np.ceil(1 / time_step) + 1) * time_length)
        self.patient.setPeepHint(self['peep'])
        self.record({'pressure': self['peep'], 'p_alv': self['peep']})

    def tick(self):
        self.output = np.roll(self.output, 1, axis=0)

    def record(self, values):
        for key in values:
            self.output[0, self.parameters[key] - 1] = values[key]

    def data(self, key):
        return np.flip(self.output[:, self.parameters[key] - 1])

    def plot(self, keys, axis=None, scalefactor=1, zeroline=True):
        if isinstance(keys, str):
            keys = [keys]

        if axis is None:
            axis = plt.gca()

        for key in keys:
            axis.plot(self.data('time'),
                      self.data(key) * scalefactor,
                      label=key)
        axis.legend()

        if zeroline:
            axis.axhline(0, color='black')
        return axis
Exemplo n.º 14
0
        if isinstance(eachItem, str):
            print("float('{}') = {}".format(eachItem, float(eachItem)))
        else:
            print("float({}) = {}".format(eachItem, float(eachItem)))
    except Exception as ex:
        print("float({}) = {}".format(eachItem, ex))

#check for 1/0
try:
    print("float(1/0) = {}".format(float(1 / 0)))
except Exception as ex:
    print("float(1/0) = {}".format(ex))

from enum import IntEnum

Menu_Figury = IntEnum('Menu_Figury', "Prostokat Kwadrat Trojkat Trapez Kolo")


def wybierz_figure(lp):
    #wstepne informacje
    lp = input("wybierz figure, wpisz\n\
1 - prostokat\n2 - kwadrat\n3 - trojkat\n4 - trapez\n5 - kolo:\n")
    #w razie bledu

    while lp.isdigit() == False:
        lp = input("wybierz figure, wpisz\n\
1 - prostokat\n2 - kwadrat\n3 - trojkat\n4 - trapez\n5 - kolo:\n")


#gdy poprawne
    lp = int(lp)
Exemplo n.º 15
0
class FileActionPacket(ServicePacket):
    Action = IntEnum ('Action',
        [], start = 0)
    action : Codec.uint8_t
    filename : Codec.cstring
Exemplo n.º 16
0
	def __eq__(self, other):
		return False if type(self) != type(other) else IntEnum.__eq__(self, other)
Exemplo n.º 17
0
import numpy as np
from matplotlib import pyplot as plt
import sys
sys.path.append('..')
from datetime import datetime
from scipy.signal import savgol_filter
from scipy import optimize
from enum import IntEnum
import copy
from scripts.mapping import R0s_mapping, GR_mapping

compartments = ['S', 'E1', 'E2', 'E3', 'I', 'H', 'C', 'D', 'R', 'T', 'NUM']
Sub = IntEnum('Sub', compartments, start=0)

def empty_data_list():
    """
    Base data structure, a list containing vectors of data
    """
    return [np.array([]) if (i == Sub.D or i == Sub.T) else None for i in range(Sub.NUM)]

def smooth(data, as_int=False, nb_pts=9, order=3):
    """
    Smooth data using a savgol filter ignoring the nan values. The missing data points stay nans
    """
    smoothed = copy.deepcopy(data)
    for ii in [Sub.T, Sub.D, Sub.H, Sub.C]:
        if smoothed[ii] is not None:
            good_idx = ~np.isnan(smoothed[ii])
            np.put(smoothed[ii], np.where(good_idx)[0],
                    savgol_filter(smoothed[ii][good_idx], nb_pts, order,
                                  mode="interp" if np.sum(good_idx)>nb_pts else "mirror"))
Exemplo n.º 18
0
EBADF = getattr(errno, 'EBADF', 9)
EAGAIN = getattr(errno, 'EAGAIN', 11)
EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)

__all__ = ["fromfd", "getfqdn", "create_connection",
        "AddressFamily", "SocketKind"]
__all__.extend(os._get_exports_list(_socket))

# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
# nicer string representations.
# Note that _socket only knows about the integer values. The public interface
# in this module understands the enums and translates them back from integers
# where needed (e.g. .family property of a socket object).

IntEnum._convert(
        'AddressFamily',
        __name__,
        lambda C: C.isupper() and C.startswith('AF_'))

IntEnum._convert(
        'SocketKind',
        __name__,
        lambda C: C.isupper() and C.startswith('SOCK_'))

IntFlag._convert(
        'MsgFlag',
        __name__,
        lambda C: C.isupper() and C.startswith('MSG_'))

IntFlag._convert(
        'AddressInfo',
        __name__,
Exemplo n.º 19
0
from _socket import *
import os, sys, io, selectors
from enum import IntEnum, IntFlag
try:
    import errno
except ImportError:
    errno = None

EBADF = getattr(errno, 'EBADF', 9)
EAGAIN = getattr(errno, 'EAGAIN', 11)
EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
__all__ = [
    'fromfd', 'getfqdn', 'create_connection', 'AddressFamily', 'SocketKind'
]
__all__.extend(os._get_exports_list(_socket))
IntEnum._convert('AddressFamily', __name__,
                 lambda C: C.isupper() and C.startswith('AF_'))
IntEnum._convert('SocketKind', __name__,
                 lambda C: C.isupper() and C.startswith('SOCK_'))
IntFlag._convert('MsgFlag', __name__,
                 lambda C: C.isupper() and C.startswith('MSG_'))
IntFlag._convert('AddressInfo', __name__,
                 lambda C: C.isupper() and C.startswith('AI_'))
_LOCALHOST = '127.0.0.1'
_LOCALHOST_V6 = '::1'


def _intenum_converter(value, enum_klass):
    """Convert a numeric family value to an IntEnum member.

    If it's not a known member, return the numeric value itself.
    """
Exemplo n.º 20
0
            self.X = PointReel(coef, 0.0)
            self.Y = PointReel(coef / 2, -coef / 2)
            self.Z = PointReel(0.0, -coef)
        if (orig == None):
            self.O = PointImage(ecr.Largeur // 2, ecr.Hauteur // 2)
        else:
            self.O = orig


################################################################################

################################################################################
# Listes des actions d'affichage prévues et à effectuer
################################################################################
Actions = IntEnum(
    'CUBE TRIANGLES FUSEAU1 FUSEAU2 FUSEAU3 FUSEAU4 FONCTION PARAM BEZIER HORLOGE ISO TRISPLEINS'
)
Afaire = [
    Actions.CUBE, Actions.TRIANGLES, Actions.FUSEAU1, Actions.FUSEAU2,
    Actions.FUSEAU3, Actions.FUSEAU4, Actions.FONCTION, Actions.PARAM,
    Actions.BEZIER, Actions.HORLOGE, Actions.ISO, Actions.TRISPLEINS
]
action = 0  # Numéro de l'action courante (à partir de 0) dans la liste des actions Afaire
################################################################################

################################################################################
# Informations diverses sur l'état d'affichage
################################################################################
fond = Couleur(0, 0, 0)  # Couleur de fond (noir)
fini = False  # Indique si le programme est terminé ou non
dejaFait = False  # Indique si dessin est déjà fait ou non
Exemplo n.º 21
0
 def __init__(self, filename):
     super().__init__(filename, buffer_size=16)
     self.Type = IntEnum('Type',
                         {'DATA': 0, 'HEADER': -1, 'FOOTER': -102})
     self.current_channel = 0
     self.number_channels = 0
#impletation of linear search alogrithm
#only for illustration as sequence types like List, Tuple, Range
# all implements the __contains__() and
# allows to search simply by using 'in' operator
from enum import IntEnum
from typing import List, Tuple

Nucleotide: IntEnum = IntEnum(
    'Nucleotide',
    ('A', 'C', 'G', 'T'))  #IntEnum gives us the comparsion operators
#codons are defined as triplets of nucleotides
Codon = Tuple[Nucleotide, Nucleotide, Nucleotide]
#genes are list of codons
Genes = List[Codon]

gene_str: str = "ACGTGGCTCTCTAACGTACGTACGTACGGGGTTTATATATACCCTAGGACTCCCTTTGTC"


def string_to_gene(s: str) -> Genes:
    genes: Genes = []
    for i in range(0, len(s), 3):
        if (i + 2) > len(s):
            return genes
        codon: Codon = (Nucleotide[s[i]], Nucleotide[s[i + 1]],
                        Nucleotide[s[i + 2]])
        genes.append(codon)
    return genes


def linear_search(g: Genes, c: Codon) -> bool:
    for codon in g:
import numpy as np

import tensorflow as tf
from libs.tools import img
from libs.bbox import bbox
from config import cfgs

from tensorflow.python.ops import control_flow_ops
from tensorflow.python.framework import tensor_shape
import cv2

slim = tf.contrib.slim

# Resizing strategies.
Resize = IntEnum('Resize', ('NONE',                # Nothing!
                            'CENTRAL_CROP',        # Crop (and pad if necessary).
                            'PAD_AND_RESIZE',      # Pad, and resize to output shape.
                            'WARP_RESIZE'))        # Warp resize.
_R_MEAN, _G_MEAN, _B_MEAN = cfgs.rgb_mean
MAX_EXPAND_SCALE = cfgs.max_expand_scale
LABEL_IGNORE = -1
USING_SHORTER_SIDE_FILTERING = True
USE_ROT_90 = True
USE_ROT_RANDOM = True
MIN_LENGHT_OF_SIDE = cfgs.min_lenght_of_side
AREA_RANGE = cfgs.crop_area_range
# ***************************************************************************
# NOTE function tools
# ***************************************************************************
def _assert(cond, ex_type, msg):
    """A polymorphic assert, works with tensors and boolean expressions.
    If `cond` is not a tensor, behave like an ordinary assert statement, except
Exemplo n.º 24
0
    def test_compound_enum_array_min(self):
        import vsc 

#        level_list = [('level_'+str(level), auto()) for level in range(3)]
#        level_e = Enum('level', dict(level_list))

        level_list = [('level_'+str(level), auto()) for level in range(3)]
        level_e = IntEnum('level', dict(level_list))
        level_list = [('level_'+str(level), auto()) for level in range(3)]
#         class level_e(Enum):
#             level_0 = 0
#             level_1 = 1
#             level_2 = 2

        @vsc.randobj
        class Parent:
            def __init__(self):
                self.id = 0
                self.c1 = vsc.rand_list_t(vsc.attr(Child1()))
                for i in range(1):    
                    self.c1.append(vsc.attr(Child1()))

                self.c2 = vsc.rand_list_t(vsc.attr(Child2()))
                for i in range(1):
                    self.c2.append(vsc.attr(Child2()))

                self.val = vsc.rand_uint16_t(5)

            @vsc.constraint
            def enum_inter_class(self):
                # Does not work
                self.c1[0].a[0].enum_test == level_e.level_2

                with vsc.if_then(self.c1[0].a[0].enum_test == level_e.level_0):
                    self.c2[0].x[0].value == 1
                with vsc.else_if(self.c1[0].a[0].enum_test == level_e.level_1):
                    self.c2[0].x[0].value == 2
                with vsc.else_then:
                    self.c2[0].x[0].value == 3
        
        @vsc.randobj
        class Field():
            def __init__(self, name, def_value):
                self.name = name
                self.enum_test = vsc.rand_enum_t(level_e)
#                self.enum_test = vsc.rand_int32_t()
                self.value = vsc.rand_uint8_t(def_value)


        @vsc.randobj
        class Child1:
            def __init__(self):
                self.a = vsc.rand_list_t(vsc.attr(Field('a', 10)))
                for i in range(2):    
                    self.a.append(vsc.attr(Field('a', 10)))

                self.b = vsc.rand_list_t(vsc.attr(Field('b', 10)))
                for i in range(2):    
                    self.b.append(vsc.attr(Field('b', 10)))

                #self.enum_test = vsc.rand_enum_t(level_e)

            @vsc.constraint
            def test_c(self):
                self.a[0].value < self.a[1].value

        @vsc.randobj
        class Child2:
            def __init__(self):
                self.x = vsc.rand_list_t(vsc.attr(Field('x', 10)))
                for i in range(2):
                    self.x.append(vsc.attr(Field('x', 10)))

                self.y = vsc.rand_list_t(vsc.attr(Field('y', 10)))
                for i in range(2):
                    self.y.append(vsc.attr(Field('y', 10)))
    
            @vsc.constraint
            def test_c(self):
                self.x[0].value < self.x[1].value

        inst=Parent()
        inst.randomize(debug=0)

        inst.randomize()
        self.assertEqual(inst.c1[0].a[0].enum_test, level_e.level_2)
        self.assertEqual(inst.c2[0].x[0].value, 3)
Exemplo n.º 25
0
class Line:
    """Contains Chicago Transit Authority (CTA) Elevated Loop Train ("L") Station Data"""

    colors = IntEnum("colors", "blue green red", start=0)
    num_directions = 2

    def __init__(self, color, station_data, num_trains=10):
        self.color = color
        self.num_trains = num_trains
        # logger.info(f"{self.color}\n{self.num_trains}")
        self.stations = self._build_line_data(station_data)
        # We must always discount the terminal station at the end of each direction
        self.num_stations = len(self.stations) - 1
        logger.info(f"\nNumber of stations: {self.num_stations}")
        logger.info("Running _build_trains() function ")
        self.trains = self._build_trains()

    def _build_line_data(self, station_df):
        """Constructs all stations on the line"""
        stations = station_df["station_name"].unique()

        logger.info(f"\nunique statns: {stations}")

        station_data = station_df[station_df["station_name"] == stations[0]]

        # logger.info(f"{station_data}")
        line = [
            Station(station_data["station_id"].unique()[0], stations[0],
                    self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(
                station_data["station_id"].unique()[0],
                station,
                self.color,
                prev_station,
            )
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(new_station)
        return line

    def _build_trains(self):
        """Constructs and assigns train objects to stations"""
        trains = []
        curr_loc = 0
        b_dir = True
        for train_id in range(self.num_trains):
            tid = str(train_id).zfill(3)
            logger.info(f"train id: {tid}")
            logger.info(f"Debug for what is this : {self.color.name[0]}")
            train = Train(f"{self.color.name[0].upper()}L{tid}",
                          Train.status.in_service)
            trains.append(train)

            if b_dir:
                self.stations[curr_loc].arrive_b(train, None, None)
            else:
                self.stations[curr_loc].arrive_a(train, None, None)
            curr_loc, b_dir = self._get_next_idx(curr_loc, b_dir)

        return trains

    def run(self, timestamp, time_step):
        """Advances trains between stations in the simulation. Runs turnstiles."""
        self._advance_turnstiles(timestamp, time_step)
        self._advance_trains()

    def close(self):
        """Called to stop the simulation"""
        _ = [station.close() for station in self.stations]

    def _advance_turnstiles(self, timestamp, time_step):
        """Advances the turnstiles in the simulation"""
        _ = [
            station.turnstile.run(timestamp, time_step)
            for station in self.stations
        ]

    def _advance_trains(self):
        """Advances trains between stations in the simulation"""
        # Find the first b train
        curr_train, curr_index, b_direction = self._next_train()
        self.stations[curr_index].b_train = None

        trains_advanced = 0
        while trains_advanced < self.num_trains - 1:
            # The train departs the current station
            if b_direction is True:
                self.stations[curr_index].b_train = None
            else:
                self.stations[curr_index].a_train = None

            prev_station = self.stations[curr_index].station_id
            prev_dir = "b" if b_direction else "a"

            # Advance this train to the next station
            curr_index, b_direction = self._get_next_idx(curr_index,
                                                         b_direction,
                                                         step_size=1)
            if b_direction is True:
                self.stations[curr_index].arrive_b(curr_train, prev_station,
                                                   prev_dir)
            else:
                self.stations[curr_index].arrive_a(curr_train, prev_station,
                                                   prev_dir)

            # Find the next train to advance
            move = 1 if b_direction else -1
            next_train, curr_index, b_direction = self._next_train(
                curr_index + move, b_direction)
            if b_direction is True:
                curr_train = self.stations[curr_index].b_train
            else:
                curr_train = self.stations[curr_index].a_train

            curr_train = next_train
            trains_advanced += 1

        # The last train departs the current station
        if b_direction is True:
            self.stations[curr_index].b_train = None
        else:
            self.stations[curr_index].a_train = None

        # Advance last train to the next station
        prev_station = self.stations[curr_index].station_id
        prev_dir = "b" if b_direction else "a"
        curr_index, b_direction = self._get_next_idx(curr_index,
                                                     b_direction,
                                                     step_size=1)
        if b_direction is True:
            self.stations[curr_index].arrive_b(curr_train, prev_station,
                                               prev_dir)
        else:
            self.stations[curr_index].arrive_a(curr_train, prev_station,
                                               prev_dir)

    def _next_train(self, start_index=0, b_direction=True, step_size=1):
        """Given a starting index, finds the next train in either direction"""
        if b_direction is True:
            curr_index = self._next_train_b(start_index, step_size)

            if curr_index == -1:
                curr_index = self._next_train_a(
                    len(self.stations) - 1, step_size)
                b_direction = False
        else:
            curr_index = self._next_train_a(start_index, step_size)

            if curr_index == -1:
                curr_index = self._next_train_b(0, step_size)
                b_direction = True

        if b_direction is True:
            return self.stations[curr_index].b_train, curr_index, True
        return self.stations[curr_index].a_train, curr_index, False

    def _next_train_b(self, start_index, step_size):
        """Finds the next train in the b direction, if any"""
        for i in range(start_index, len(self.stations), step_size):
            if self.stations[i].b_train is not None:
                return i
        return -1

    def _next_train_a(self, start_index, step_size):
        """Finds the next train in the a direction, if any"""
        for i in range(start_index, 0, -step_size):
            if self.stations[i].a_train is not None:
                return i
        return -1

    def _get_next_idx(self, curr_index, b_direction, step_size=None):
        """Calculates the next station index. Returns next index and if it is b direction"""
        if step_size is None:
            step_size = int(
                (self.num_stations * Line.num_directions) / self.num_trains)
        if b_direction is True:
            next_index = curr_index + step_size
            if next_index < self.num_stations:
                return next_index, True
            else:
                return self.num_stations - (next_index %
                                            self.num_stations), False
        else:
            next_index = curr_index - step_size
            if next_index > 0:
                return next_index, False
            else:
                return abs(next_index), True

    def __str__(self):
        return "\n".join(str(station) for station in self.stations)

    def __repr__(self):
        return str(self)
Exemplo n.º 26
0
    )
from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
try:
    from _ssl import RAND_egd
except ImportError:
    # LibreSSL does not provide RAND_egd
    pass


from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
from _ssl import _OPENSSL_API_VERSION


_IntEnum._convert(
    '_SSLMethod', __name__,
    lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
    source=_ssl)

_IntFlag._convert(
    'Options', __name__,
    lambda name: name.startswith('OP_'),
    source=_ssl)

_IntEnum._convert(
    'AlertDescription', __name__,
    lambda name: name.startswith('ALERT_DESCRIPTION_'),
    source=_ssl)

_IntEnum._convert(
    'SSLErrorNumber', __name__,
    lambda name: name.startswith('SSL_ERROR_'),
Exemplo n.º 27
0
class Weather(Producer):
    """Defines a simulated weather model"""

    status = IntEnum("status",
                     "sunny partly_cloudy cloudy windy precipitation",
                     start=0)

    rest_proxy_url = REST_PROXY_URL

    key_schema = None
    value_schema = None

    winter_months = set((0, 1, 2, 3, 10, 11))
    summer_months = set((6, 7, 8))

    def __init__(self, month):
        #
        #
        # TODO: Complete the below by deciding on a topic name, number of partitions, and number of
        # replicas
        #
        #
        self.topic_name = WEATHER_TOPIC_NAME

        super().__init__(
            self.topic_name,  # TODO: Come up with a better topic name
            key_schema=Weather.key_schema,
            value_schema=Weather.value_schema,
            num_partitions=NUM_PARTITIONS_PER_TOPIC,
            num_replicas=NUM_REPLICAS_PER_TOPIC)

        self.status = Weather.status.sunny
        self.temp = 70.0
        if month in Weather.winter_months:
            self.temp = 40.0
        elif month in Weather.summer_months:
            self.temp = 85.0

        if Weather.key_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_key.json"
                      ) as f:
                Weather.key_schema = json.load(f)

        #
        # TODO: Define this value schema in `schemas/weather_value.json
        #
        if Weather.value_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_value.json"
                      ) as f:
                Weather.value_schema = json.load(f)

    def _set_weather(self, month):
        """Returns the current weather"""
        mode = 0.0
        if month in Weather.winter_months:
            mode = -1.0
        elif month in Weather.summer_months:
            mode = 1.0
        self.temp += min(max(-20.0, random.triangular(-10.0, 10.0, mode)),
                         100.0)
        self.status = random.choice(list(Weather.status))

    def run(self, month):
        self._set_weather(month)

        #
        #
        # TODO: Complete the function by posting a weather event to REST Proxy. Make sure to
        # specify the Avro schemas and verify that you are using the correct Content-Type header.
        #
        #
        resp = requests.post(
            #
            #
            # TODO: What URL should be POSTed to?
            #
            #
            f"{Weather.rest_proxy_url}/topics/{self.topic_name}",  # TODO
            #
            #
            # TODO: What Headers need to bet set?
            #
            #
            headers={"Content-Type": "application/vnd.kafka.avro.v2+json"},
            data=json.dumps({
                "key_schema":
                json.dumps(Weather.key_schema),
                "value_schema":
                json.dumps(Weather.value_schema),
                "records": [{
                    "value": {
                        "status": self.status.name,
                        "temperature": self.temp
                    },
                    "key": {
                        "timestamp": self.time_millis()
                    }
                }]

                #
                #
                # TODO: Provide key schema, value schema, and records
                #
                #
            }),
        )
        resp.raise_for_status()

        logger.info(
            "sent weather data to kafka, temp: %s, status: %s",
            self.temp,
            self.status.name,
        )
Exemplo n.º 28
0
Arquivo: util.py Projeto: sahwar/warp
import socket
import gettext
import math
import os

from gi.repository import GLib, Gtk, Gdk, GObject, GdkPixbuf, Gio

import prefs

_ = gettext.gettext

CHUNK_SIZE = 1024 * 1024
PROGRESS_UPDATE_FREQ = 2 * 1000 * 1000

from enum import IntEnum
TransferDirection = IntEnum('TransferDirection', 'TO_REMOTE_MACHINE \
                                                  FROM_REMOTE_MACHINE')

FileType = IntEnum('FileType', 'REGULAR \
                                DIRECTORY \
                                SYMBOLIC_LINK')

# Online - all ok
# Offline - no presence at all
# Init connecting - we've just discovered you
# Unreachable - we've either tried and failed after initial discovery, or something went wrong during the session

RemoteStatus = IntEnum('RemoteStatus', 'ONLINE \
                                        OFFLINE \
                                        INIT_CONNECTING \
                                        UNREACHABLE')
Exemplo n.º 29
0
from enum import IntEnum
from typing import Tuple, List

# define types and variables

Nucleotide: IntEnum = IntEnum('Nucleotide', ('A', 'C', 'G', 'T'))

DaysofWeek: IntEnum = IntEnum('DaysofWeek', ('Mon', 'Tue'))

myDay: DaysofWeek = DaysofWeek.Mon

Codon = Tuple[Nucleotide, Nucleotide, Nucleotide]  # type alias for codons
Gene = List[Codon]  # type alias for genes

#Â our initial gene to search within
gene_str: str = "TGGCTCTCTAACGTACGTACGTACGGGGTTTATATATACCCTAGGACTCCCTTTACG"


# function definitions
def string_to_gene(s: str) -> Gene:
    gene: Gene = []
    for i in range(0, len(s), 3):
        if (i + 2) >= len(s):  # don't run off end!
            return gene
        #  initialize codon out of three nucleotides
        codon: Codon = (Nucleotide[s[i]], Nucleotide[s[i + 1]],
                        Nucleotide[s[i + 2]])
        gene.append(codon)  # add codon to gene
    return gene

Exemplo n.º 30
0
import time

from SerialPacketStream import Service, ServicePacket, ServicePacketListener, RawDataPacket, FramePacket
import SerialPacketStream.Codec as Codec

import logging
logger = logging.getLogger('default')

PacketCode = IntEnum('ActionCode',
    ['QUERY',
     'ACTION',
     'ACTION_RESPONSE',
     'OPEN',
     'CLOSE',
     'WRITE',
     'ABORT',
     'REQUEST',
     'LIST',
     'CD',
     'PWD',
     'FILE',
     'MOUNT',
     'UNMOUNT'], start = 0)


class QueryPacket(ServicePacket):
    packet_id = PacketCode.QUERY

    version_major : Codec.uint16_t
    version_minor : Codec.uint16_t
    version_patch : Codec.uint16_t
Exemplo n.º 31
0
class Weather(Producer):
    """Defines a simulated weather model"""

    status = IntEnum(
        "status", "sunny partly_cloudy cloudy windy precipitation", start=0
    )

    rest_proxy_url = "http://localhost:8082"

    winter_months = set((0, 1, 2, 3, 10, 11))
    summer_months = set((6, 7, 8))
    
    key_schema = None
    value_schema = None
    
    topic_name = "weather_updates"

    def __init__(self, month):
        super().__init__(
            Weather.topic_name,
            key_schema=Weather.key_schema,
            value_schema=Weather.value_schema,
            num_partitions=3,
            num_replicas=2,
        )

        self.status = Weather.status.sunny
        self.temp = 70.0
        if month in Weather.winter_months:
            self.temp = 40.0
        elif month in Weather.summer_months:
            self.temp = 85.0

        if Weather.key_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_key.json") as f:
                Weather.key_schema = json.load(f)

        if Weather.value_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_value.json") as f:
                Weather.value_schema = json.load(f)


    def _set_weather(self, month):
        """Returns the current weather"""
        mode = 0.0
        if month in Weather.winter_months:
            mode = -1.0
        elif month in Weather.summer_months:
            mode = 1.0
        self.temp += min(max(-20.0, random.triangular(-10.0, 10.0, mode)), 100.0)
        self.status = random.choice(list(Weather.status))

    def run(self, month):
        self._set_weather(month)
#         print(f"Skipping the Weather.py for now!")
              
        resp = requests.post(
           f"{Weather.rest_proxy_url}/topics/{Weather.topic_name}",
           headers={"Content-Type": "application/vnd.kafka.avro.v2+json"},
           data=json.dumps(
                {
                    "key_schema": json.dumps(Weather.key_schema),
                    "value_schema": json.dumps(Weather.value_schema),
                    "records": [
                        {
                            "key": {"timestamp": self.time_millis()},
                            "value": {
                                "temperature": self.temp,
                                "status": self.status.name,
                            },
                        }
                    ],
                }
            )
        )
        

        try:
            resp.raise_for_status()
        except:
            logging.critical(f"Failed to send data to REST Proxy: {json.dumps(resp.json(), indent=2)}")


        logger.debug(
            "sent weather data to kafka, temp: %s, status: %s",
            self.temp,
            self.status.name,
        )
Exemplo n.º 32
0
from enum import IntEnum

Location = IntEnum(
    "Location",
    [
        "Lineup",
        "Rotation",
        "Shadow Lineup",
        "Shadow Rotation",
    ],
    start=0,
)

ModColor = IntEnum(
    "ModColor",
    [
        "#dbbc0b",
        "#c2157a",
        "#0a78a3",
        "#639e47",
    ],
    start=0,
)
Exemplo n.º 33
0
from enum import IntEnum

# Represents the names of a piece
PieceNames = ["p", "n", "b", "r", "q", "k", "-"]

# Represents a square on the board.
Square = IntEnum('Square',
    ["a1", "b1", "c1", "d1", "e1",
    "a2", "b2", "c2", "d2", "e2",
    "a3", "b3", "c3", "d3", "e3",
    "a4", "b4", "c4", "d4", "e4",
    "a5", "b5", "c5", "d5", "e5"], start=0)

# Represents the different colors pieces can have.
Color = IntEnum('Color',  
    ["White", "Black", "NONE"], start=0)

# Represents the different pieces on the board.
Piece = IntEnum('Piece',  
    ["Pawn", "Knight", "Bishop", "Rook", "Queen", "King", "NONE"], start=0)

# Represents the possible categories a given move could fall into
class Flags(IntEnum):
    Quiet = 0,
    Capture = 4,
    KnightProm = 8,
    BishopProm = 9,
    RookProm = 10,
    QueenProm = 11,
    KnightPromCap = 12,
    BishopPromCap = 13,
Exemplo n.º 34
0
Arquivo: ssl.py Projeto: 3lnc/cpython
    )
from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
try:
    from _ssl import RAND_egd
except ImportError:
    # LibreSSL does not provide RAND_egd
    pass


from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
from _ssl import _OPENSSL_API_VERSION


_IntEnum._convert(
    '_SSLMethod', __name__,
    lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
    source=_ssl)

_IntFlag._convert(
    'Options', __name__,
    lambda name: name.startswith('OP_'),
    source=_ssl)

_IntEnum._convert(
    'AlertDescription', __name__,
    lambda name: name.startswith('ALERT_DESCRIPTION_'),
    source=_ssl)

_IntEnum._convert(
    'SSLErrorNumber', __name__,
    lambda name: name.startswith('SSL_ERROR_'),
Exemplo n.º 35
0
class Weather(Producer):
    """Defines a simulated weather model"""

    status = IntEnum("status",
                     "sunny partly_cloudy cloudy windy precipitation",
                     start=0)

    encoder.FLOAT_REPR = lambda o: format(o, '.2f')

    key_schema = None
    value_schema = None

    winter_months = set((0, 1, 2, 3, 10, 11))
    summer_months = set((6, 7, 8))

    # instance variables
    # self.status
    # self.temp

    def __init__(self, month):
        if Weather.key_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_key.json"
                      ) as f:
                Weather.key_schema = json.load(f)
        if Weather.value_schema is None:
            with open(f"{Path(__file__).parents[0]}/schemas/weather_value.json"
                      ) as f:
                Weather.value_schema = json.load(f)

        super().__init__(
            topic_name=CTAConstants.WEATHER_TOPIC_NAME,
            key_schema=Weather.key_schema,
            value_schema=Weather.value_schema,
            num_partitions=1,
            num_replicas=1,
        )

        self.status = Weather.status.sunny
        self.temp = 70.0
        if month in Weather.winter_months:
            self.temp = 40.0
        elif month in Weather.summer_months:
            self.temp = 85.0

    def _set_weather(self, month):
        """Returns the current weather"""
        mode = 0.0
        if month in Weather.winter_months:
            mode = -1.0
        elif month in Weather.summer_months:
            mode = 1.0
        self.temp += min(max(-20.0, random.triangular(-10.0, 10.0, mode)),
                         100.0)
        self.status = random.choice(list(Weather.status))

    def run(self, month):
        self._set_weather(month)

        logger.debug("weather kafka proxy integration")

        headers = {"Content-Type": "application/vnd.kafka.avro.v2+json"}

        data = {
            "key_schema":
            json.dumps(Weather.key_schema),
            "value_schema":
            json.dumps(Weather.value_schema),
            "records": [{
                "value": {
                    "temperature": float(self.temp),
                    "status": self.status.name
                },
                "key": {
                    "timestamp": self.time_millis()
                }
            }]
        }

        print(
            f"{CTAConstants.REST_PROXY_HOST}topics/{CTAConstants.WEATHER_TOPIC_NAME}"
        )
        resp = requests.post(
            f"{CTAConstants.REST_PROXY_HOST}topics/{CTAConstants.WEATHER_TOPIC_NAME}",
            data=json.dumps(data),
            headers=headers,
        )

        try:
            resp.raise_for_status()
        except:
            logger.error(
                f"Failed to send data to REST Proxy {json.dumps(resp.json(), indent=2)}"
            )

        logger.debug(
            f"Sent data to REST Proxy {json.dumps(resp.json(), indent=2)}")

        logger.debug(
            "sent weather data to kafka, temp: %s, status: %s",
            self.temp,
            self.status.name,
        )
Exemplo n.º 36
0
def _import_symbols(prefix):
    for n in dir(_ssl):
        if n.startswith(prefix):
            globals()[n] = getattr(_ssl, n)

_import_symbols('OP_')
_import_symbols('ALERT_DESCRIPTION_')
_import_symbols('SSL_ERROR_')
_import_symbols('VERIFY_')

from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN

from _ssl import _OPENSSL_API_VERSION

_IntEnum._convert(
        '_SSLMethod', __name__,
        lambda name: name.startswith('PROTOCOL_'),
        source=_ssl)

_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}

try:
    _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
except NameError:
    _SSLv2_IF_EXISTS = None

if sys.platform == "win32":
    from _ssl import enum_certificates, enum_crls

from socket import socket, AF_INET, SOCK_STREAM, create_connection
from socket import SOL_SOCKET, SO_TYPE
import base64        # for DER-to-PEM translation
Exemplo n.º 37
0
def quads_value(cards):
    quads = [v for (v, c) in card_value_counts(cards).iteritems() if c == 4]
    return max(quads) if quads else None


def is_straight_flush(cards):
    return is_flush(cards) and is_straight(cards)


def is_royal_flush(cards):
    return is_straight_flush(cards) and min(card_values(cards)) == 10


Hand = IntEnum(
    'Hand',
    'Nothing Pair TwoPair Trips Straight Flush FullHouse Quads StraightFlush RoyalFlush'
)


def classify_hand(cards):
    def any_length(cards):
        if is_trips(cards): return Hand.Trips
        elif is_two_pair(cards): return Hand.TwoPair
        elif is_pair(cards): return Hand.Pair
        else: return Hand.Nothing

    if len(cards) == 5:
        if is_royal_flush(cards): return Hand.RoyalFlush
        elif is_straight_flush(cards): return Hand.StraightFlush
        elif is_quads(cards): return Hand.Quads
        elif is_full_house(cards): return Hand.FullHouse
Exemplo n.º 38
0
import _signal
from _signal import *
from functools import wraps as _wraps
from enum import IntEnum as _IntEnum

_globals = globals()

_IntEnum._convert(
        'Signals', __name__,
        lambda name:
            name.isupper()
            and (name.startswith('SIG') and not name.startswith('SIG_'))
            or name.startswith('CTRL_'))

_IntEnum._convert(
        'Handlers', __name__,
        lambda name: name in ('SIG_DFL', 'SIG_IGN'))

if 'pthread_sigmask' in _globals:
    _IntEnum._convert(
            'Sigmasks', __name__,
            lambda name: name in ('SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'))


def _int_to_enum(value, enum_klass):
    """Convert a numeric value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    """
    try:
        return enum_klass(value)
    except ValueError:
Exemplo n.º 39
0
 def __str__(self):
     suit_string = IntEnum.__str__(self)
     suit_split = suit_string.partition(".")
     return suit_split[2]