Exemple #1
0
 def create_table(cls, fail_silently=False):
     cls.__fields__ = list(cls.__schema__.keys())
     cls.Row = namedtuple(cls.__table__, cls.__fields__)
     try:
         os.makedirs("%s/%s" % (cls.__db__.name, cls.__table__))
     except OSError as e:
         if fail_silently:
             print(e)
         else:
             raise
    def __init__(self, seed, action_size):
        """
        initialize the replaybuffer
        :param seed: random seed for replaybuffer
        :param action_size: dimension of agent action
        """
        self.seed = random.seed(seed)
        self.action_size = action_size

        self.memory = deque(maxlen=BUFFER_SIZE)
        self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", 'done'])
    def _parse_args(self, args):
        # add optional args with defaults
        arg_dest = []
        arg_vals = []
        for opt in self.opt:
            arg_dest.append(opt.dest)
            arg_vals.append(opt.default)

        # parse all args
        parsed_pos = False
        while args or not parsed_pos:
            if args and args[0].startswith("-") and args[0] != "-" and args[0] != "--":
                # optional arg
                a = args.pop(0)
                if a in ("-h", "--help"):
                    self.usage(True)
                    sys.exit(0)
                found = False
                for i, opt in enumerate(self.opt):
                    if a == opt.name:
                        arg_vals[i] = opt.parse(args)
                        found = True
                        break
                if not found:
                    raise _ArgError("unknown option %s" % a)
            else:
                # positional arg
                if parsed_pos:
                    raise _ArgError("extra args: %s" % " ".join(args))
                for pos in self.pos:
                    arg_dest.append(pos.dest)
                    arg_vals.append(pos.parse(args))
                parsed_pos = True

        # build and return named tuple with arg values
        return namedtuple("args", arg_dest)(*arg_vals)
import bench
from _collections import namedtuple

T = namedtuple("Tup", "foo1 foo2 foo3 foo4 num")


def test(num):
    t = T(0, 0, 0, 0, 20000000)
    i = 0
    while i < t.num:
        i += 1


bench.run(test)
import bench
from _collections import namedtuple

T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"])

def test(num):
    t = T(0, 0, 0, 0, 20000000)
    i = 0
    while i < t.num:
        i += 1

bench.run(test)
import bench
from _collections import namedtuple

T = namedtuple("Tup", "foo1 foo2 foo3 foo4 num")

def test(num):
    t = T(0, 0, 0, 0, 20000000)
    i = 0
    while i < t.num:
        i += 1

bench.run(test)
Exemple #7
0
import bench
from _collections import namedtuple

T = namedtuple("Tup", "num bar")


def test(num):
    t = T(20000000, 0)
    i = 0
    while i < t.num:
        i += 1


bench.run(test)
Exemple #8
0
from _collections import namedtuple

a = namedtuple('courses', 'name, tech, place')
s = a('mahesh', 'python', 'delhi')
t = a._make(['neha', 'go', 'delhi'])

print(s)
print(t)

#####################################################################
from _collections import deque

a = ['e', 'd', 'u', 't', 'a', 'm', 'h']
d = deque(a)

d.appendleft('w')  #append at begining
d.append('w')  #append at last
print(d)

d.pop()  #pop from last
d.popleft()  #pop from start

print(d)

#####################################################################
from _collections import ChainMap

a = {1: 'Mahesh', 2: 'Python'}
a = {1: 'Neha', 2: 'GoLang'}

c = ChainMap(a, b)
import bench
from _collections import namedtuple

T = namedtuple("Tup", "num bar")


def test(num):
    t = T(20000000, 0)
    i = 0
    while i < t.num:
        i += 1


bench.run(test)
import bench
from _collections import namedtuple

T = namedtuple("Tup", ["num", "bar"])

def test(num):
    t = T(20000000, 0)
    i = 0
    while i < t.num:
        i += 1

bench.run(test)
Exemple #11
0
import bench
from _collections import namedtuple

T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"])


def test(num):
    t = T(0, 0, 0, 0, 20000000)
    i = 0
    while i < t.num:
        i += 1


bench.run(test)
Exemple #12
0
__all__ = ["open", "openfp", "Error"]

class Error(Exception):
    pass

WAVE_FORMAT_PCM = 0x0001

_array_fmts = None, 'b', 'h', None, 'i'

#import audioop
import struct
import sys
from chunk import Chunk
from _collections import namedtuple

_wave_params = namedtuple('_wave_params',
                     'nchannels sampwidth framerate nframes comptype compname')

class Wave_read:
    """Variables used in this class:

    These variables are available to the user though appropriate
    methods of this class:
    _file -- the open file with methods read(), close(), and seek()
              set through the __init__() method
    _nchannels -- the number of audio channels
              available through the getnchannels() method
    _nframes -- the number of audio frames
              available through the getnframes() method
    _sampwidth -- the number of bytes per audio sample
              available through the getsampwidth() method
    _framerate -- the sampling frequency
Exemple #13
0
class WS2812(SubscriptableForPixel):
    # Driver for WS2812 RGB LEDs. May be used for controlling single LED or chain
    # of LEDs.
    #
    # Examples of use:
    #
    #    chain = WS2812(spi_bus=1, led_count=4)
    #    i = 0
    #    for pixel in chain:
    #        pixel.r = i
    #        pixel.g = i + 1
    #        pixel.b = i + 2
    #        i += 3
    #    chain.sync()
    #
    #    chain = WS2812(spi_bus=1, led_count=4)
    #    data = [
    #        (255, 0, 0),    # red
    #        (0, 255, 0),    # green
    #        (0, 0, 255),    # blue
    #        (85, 85, 85),   # white
    #    ]
    #    chain.show(data)
    #
    # Version: 1.5

    buf_bytes = (0x11, 0x13, 0x31, 0x33)
    ReadOnlyPixel = namedtuple('Pixel', 'r g b')

    def __init__(self, spi_bus=1, led_count=1, intensity=1, mem=PREALLOCATE):
        #Params:
        # spi_bus = SPI bus ID (1 or 2)
        # led_count = count of LEDs
        # intensity = light intensity (float up to 1)
        # mem = how stingy to be with memory (comes at a speed & GC cost)
        self.led_count = led_count
        self.intensity = intensity  # FIXME: intensity is ignored
        self.mem = mem
        # 0 prealloc
        # 1 cache
        # 2 create Pixel each time

        # prepare SPI data buffer (4 bytes for each color for each pixel,
        # with an additional zero byte at the end to make sure the data line
        # comes to rest low)
        self.buf = bytearray(4 * 3 * led_count + 1)

        if mem <= CACHE:
            # Prepare a cache by index of Pixel objects
            self.pixels = pixels = [None] * led_count
            if mem == PREALLOCATE:  # Pre-allocate the pixels
                for i in range(led_count):
                    pixels[i] = Pixel(self.buf, 3 * i)

        # OBSOLETE
        #self.bits = array('L', range(256))
        #bb = bytearray_at(addressof(self.bits), 4*256)
        #mask = 0x03
        #buf_bytes = self.buf_bytes
        #for i in range(256):
        #    index = 4*i
        #    bb[index] = buf_bytes[i >> 6 & 0x03]
        #    bb[index+1] = buf_bytes[i >> 4 & 0x03]
        #    bb[index+2] = buf_bytes[i >> 2 & 0x03]
        #    bb[index+3] = buf_bytes[i & 0x03]

        # SPI init
        self.spi = pyb.SPI(spi_bus,
                           pyb.SPI.MASTER,
                           baudrate=3200000,
                           polarity=0,
                           phase=1)

        # turn LEDs off
        self.show([])

    def __len__(self):
        return self.led_count

    def get_led_values(self, index, rgb=None):
        # The asm function is unguarded as to index, so enforce here
        if index >= self.led_count or index < -self.led_count:
            raise IndexError("tried to get values at", index)
        ix = index * 3
        return self.ReadOnlyPixel(_get(self.buf, ix+1), \
                                  _get(self.buf, ix+0), \
                                  _get(self.buf, ix+2))

    def show(self, data):
        # Show RGB data on LEDs. Expected data = [(R, G, B), ...] where R, G and B
        # are intensities of colors in range from 0 to 255. One RGB tuple for each
        # LED. Count of tuples may be less than count of connected LEDs.
        self.fill_buf(data)
        self.send_buf()

    def send_buf(self):
        #Send buffer over SPI.
        self.spi.send(self.buf)

    def sync(self, to=None):
        if to is None:
            self.spi.send(self.buf)
        else:
            short_buf = bytearray_at(addressof(self.buf),
                                     3 * 4 * to + 1)  # extra byte
            t = short_buf[-1]
            short_buf[-1] = 0
            self.spi.send(short_buf)
            short_buf[-1] = t

    _ubb = bytearray(3)

    def update_buf(self, data, where=0):
        # Fill a part of the buffer with RGB data.
        # Returns the index of the first unfilled LED
        # data is an iterable that returns an iterable
        # e.g. [(1,2,3), (4,5,6)]
        # or some generator of tuples or generators
        set_led = self.set_led
        b = self._ubb
        for d in data:
            if not isinstance(d, bytearray):
                b[0], b[1], b[2] = d
                d = b
            set_led(where, d)
            where += 1
        return where

    def fill_buf(self, data):
        # Fill buffer with RGB data.
        # All LEDs after the data are turned off.
        end = self.update_buf(data)

        # turn off the rest of the LEDs
        #b = self.buf
        #for i in range(4*3*end, 4*3*self.led_count):
        #    b[i] = 0x11   # off
        _clearLEDs(self.buf, end, self.led_count - end)