Beispiel #1
0
 def __init__(self):
     self.i3 = i3ipc.Connection()
     self.i3.on('window::focus', self.on_window_focus)
     self.i3.on('key_release', self.on_key_release)
     self.listening_socket = socket.socket(socket.AF_UNIX,
                                           socket.SOCK_STREAM)
     if os.path.exists(SOCKET_FILE):
         os.remove(SOCKET_FILE)
     self.listening_socket.bind(SOCKET_FILE)
     self.listening_socket.listen(1)
     self.cycler = Cycler(MAX_WIN_HISTORY)
Beispiel #2
0
from cycler import Cycler
import time

c = Cycler()
print("Serial open: {0}".format(c.portOpen))
c.run_program('"PFUNKEL1"')
print(c.get_run()[0])
print(c.get_run('stepNum'))
print(c.send('PROCEED\r\n'))
print(c.get_run('stepNum'))
print(c.send('PROCEED\r\n'))
print(c.get_run('stepNum'))
print('Busy? {0}'.format(c.check_busy()))
#print(c.get_run('vesselType'))
#print(c.get_run('vesselVol'))
#c.set_calc()
#print(c.get_run('vesselType'))
#print(c.get_run('vesselVol'))
#resp=c.run_program('"TEST"')
#print(c.get_run('targetTemp'))
#print(c.get_run('blockTemp'))
#c.incubate(10,True)
#print(c.get_run('targetTemp'))
#print(c.get_run('blockTemp'))
#c.cancel()
#print(c.get_run())
#print(c.get_run('vesselType'))
#print(c.get_run('vesselVol'))
#for key,val in c._runQ.items():
#    print(key)
#    print(c.get_run(key))
Beispiel #3
0
def cycler(*args, **kwargs):
    """
    Creates a :class:`cycler.Cycler` object much like :func:`cycler.cycler`,
    but includes input validation.

    cyl(arg)
    cyl(label, itr)
    cyl(label1=itr1[, label2=itr2[, ...]])

    Form 1 simply copies a given `Cycler` object.

    Form 2 creates a `Cycler` from a label and an iterable.

    Form 3 composes a `Cycler` as an inner product of the
    pairs of keyword arguments. In other words, all of the
    iterables are cycled simultaneously, as if through zip().

    Parameters
    ----------
    arg : Cycler
        Copy constructor for Cycler.

    label : name
        The property key. Must be a valid `Artist` property.
        For example, 'color' or 'linestyle'. Aliases are allowed,
        such as 'c' for 'color' and 'lw' for 'linewidth'.

    itr : iterable
        Finite-length iterable of the property values. These values
        are validated and will raise a ValueError if invalid.

    Returns
    -------
    cycler : Cycler
        New :class:`cycler.Cycler` for the given properties

    """
    if args and kwargs:
        raise TypeError("cycler() can only accept positional OR keyword "
                        "arguments -- not both.")
    elif not args and not kwargs:
        raise TypeError("cycler() must have positional OR keyword arguments")

    if len(args) == 1:
        if not isinstance(args[0], Cycler):
            raise TypeError("If only one positional argument given, it must "
                            " be a Cycler instance.")

        c = args[0]
        unknowns = c.keys - (set(_prop_validators.keys())
                             | set(_prop_aliases.keys()))
        if unknowns:
            # This is about as much validation I can do
            raise TypeError("Unknown artist properties: %s" % unknowns)
        else:
            return Cycler(c)
    elif len(args) == 2:
        pairs = [(args[0], args[1])]
    elif len(args) > 2:
        raise TypeError("No more than 2 positional arguments allowed")
    else:
        pairs = six.iteritems(kwargs)

    validated = []
    for prop, vals in pairs:
        norm_prop = _prop_aliases.get(prop, prop)
        validator = _prop_validators.get(norm_prop, None)
        if validator is None:
            raise TypeError("Unknown artist property: %s" % prop)
        vals = validator(vals)
        # We will normalize the property names as well to reduce
        # the amount of alias handling code elsewhere.
        validated.append((norm_prop, vals))

    return reduce(operator.add, (ccycler(k, v) for k, v in validated))
Beispiel #4
0
def test_starange_init():
    c = cycler('r', 'rgb')
    c2 = cycler('lw', range(3))
    cy = Cycler(list(c), list(c2), zip)
    assert cy == c + c2
Beispiel #5
0
class FocusWatcher:
    def __init__(self):
        self.i3 = i3ipc.Connection()
        self.i3.on('workspace::focus', self.on_workspace_focus)
        self.i3.on('workspace::init', self.on_workspace_focus)
        self.i3.on('key_release', self.on_key_release)
        self.listening_socket = socket.socket(socket.AF_UNIX,
                                              socket.SOCK_STREAM)
        if os.path.exists(SOCKET_FILE):
            os.remove(SOCKET_FILE)
        self.listening_socket.bind(SOCKET_FILE)
        self.listening_socket.listen(1)
        self.cycler = Cycler(MAX_WS_HISTORY)

    def _focus_workspace(self, workspace_id):
        # Set focus to the workspace
        self.i3.command('workspace %s' % workspace_id)

    def on_workspace_focus(self, i3conn, event):
        workspace_id = event.current.props.name
        self.cycler.add(workspace_id)

    def on_key_release(self, i3conn, event):
        if event.change == '133' or event.change == '134':
            self.cycler.release()

    def launch_i3(self):
        self.i3.main()

    def launch_server(self):
        selector = selectors.DefaultSelector()

        def accept(sock):
            conn, addr = sock.accept()
            selector.register(conn, selectors.EVENT_READ, read)

        def read(conn):
            data = conn.recv(1024)

            # Record if we have received a switch command and which type
            forward = data == b'switch'
            reverse = data == b'rev-switch'

            if forward or reverse:
                # Get a list of all live workspaces
                tree = self.i3.get_tree()
                workspaces = set(w.name for w in tree.workspaces())

                # Find the next window to cycle to
                workspace_id = self.cycler.switch(workspaces, forward)

                # If we found a valid workspace to switch to, set focus to it
                if workspace_id:
                    self._focus_workspace(workspace_id)
            elif not data:
                selector.unregister(conn)
                conn.close()

        selector.register(self.listening_socket, selectors.EVENT_READ, accept)

        while True:
            for key, event in selector.select():
                callback = key.data
                callback(key.fileobj)

    def run(self):
        t_i3 = threading.Thread(target=self.launch_i3)
        t_server = threading.Thread(target=self.launch_server)
        for t in (t_i3, t_server):
            t.start()
Beispiel #6
0
def main():
    # initialize the pygame module
    pygame.init()
    pygame.display.set_caption("Learning car")

    # create a surface on screen that has the size of 720 x 480
    screen = pygame.display.set_mode((1000, 500))

    # initialize game
    game = Game()
    force = pygame.math.Vector2()

    # initialize rendering
    input_state = DRAWING
    checkpoint_start = None

    # variables
    # update_buttons = True
    # update_track = False
    # update_background = False

    segoe_print = pygame.font.SysFont('segoe print', 25)
    text_buttons = [
        segoe_print.render(t, True, (127, 127, 127)) for t in
        ['Save current track', 'Load track 0', 'Clear active track', 'Start']
    ]
    text_cycler = [
        segoe_print.render(t, True, (127, 127, 127))
        for t in ['Drawing', 'Checkpoints', 'Start', 'Idle']
    ]

    buttons = []
    right_bar_x = screen.get_rect().width * 0.75
    right_bar_width = screen.get_rect().width * 0.25
    button_height = 50
    for index, line in enumerate(text_buttons):
        buttons.append(
            Button(
                pygame.Rect(right_bar_x, (index + 1) * button_height,
                            right_bar_width, button_height), line))
    cycler_buttons = [
        Button(pygame.Rect(right_bar_x, 0, right_bar_width, button_height),
               line) for line in text_cycler
    ]
    input_state_cycler = Cycler(cycler_buttons)

    # main loop
    running = True
    while running:
        # event handling, gets all event from the event queue
        for event in pygame.event.get():
            # red cross handling
            if event.type == pygame.QUIT:
                # change the value to False, to exit the main loop
                running = False

            # mouse presses handling
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == pygame.BUTTON_LEFT:
                    # if it is LMB pressed
                    if event.pos[0] < right_bar_x:
                        if input_state == DRAWING:
                            update_track = True
                            game.track_m.active_track.add_vertex(
                                pygame.math.Vector2(event.pos))
                        elif input_state == CHECKPOINTS:
                            if checkpoint_start:
                                game.track_m.active_track.add_checkpoint(
                                    checkpoint_start,
                                    pygame.math.Vector2(event.pos))
                                checkpoint_start = None
                            else:
                                checkpoint_start = pygame.math.Vector2(
                                    event.pos)
                        elif input_state == START:
                            game.track_m.active_track.set_start(
                                pygame.math.Vector2(event.pos))
                    else:
                        # update_buttons = True
                        if input_state_cycler.is_inside(event.pos):
                            input_state = (input_state + 1) % 4
                        if buttons[0].is_inside(event.pos):
                            print('saved')
                            game.track_m.save_active_track()
                        if buttons[1].is_inside(event.pos):
                            print('loaded')
                            # update_background = True
                            # update_track = True
                            game.track_m.load_to_active_track('track_0.pickle')
                        if buttons[2].is_inside(event.pos):
                            # update_background = True
                            game.track_m.clear_active_track()
                        if buttons[3].is_inside(event.pos):
                            game.start()

            # controls handling
            if event.type == pygame.KEYDOWN:
                # print('down a key')
                if event.key == pygame.K_RIGHT:
                    force.x += 1
                if event.key == pygame.K_LEFT:
                    force.x -= 1
                if event.key == pygame.K_DOWN:
                    force.y += 1
                if event.key == pygame.K_UP:
                    force.y -= 1

            if event.type == pygame.KEYUP:
                # print('up a key')
                if event.key == pygame.K_RIGHT:
                    force.x -= 1
                if event.key == pygame.K_LEFT:
                    force.x += 1
                if event.key == pygame.K_DOWN:
                    force.y -= 1
                if event.key == pygame.K_UP:
                    force.y += 1

        if force.length() > 0:
            force_ = force.normalize()
            force_.scale_to_length(0.0001)
            game.agent.add_force(force_, 0)

        game.update()
        # print(int(game.agent.pos.x), int(game.agent.pos.y))

        # drawing
        pygame.draw.rect(screen, (0, 0, 0), screen.get_rect())
        draw_track(screen, game.track_m.active_track)
        draw_button(screen, input_state_cycler.get_active_button())
        for button in buttons:
            draw_button(screen, button)
        pygame.draw.circle(screen, (255, 255, 0),
                           (int(game.agent.pos.x), int(game.agent.pos.y)), 12)
        pygame.display.flip()
Beispiel #7
0
#!/usr/bin/env python3

"""
basic user command line for interacting with cycler
"""

from cycler import Cycler

c = Cycler()
c.connect()
c.ser.isOpen()
c.portOpen
while True:
    try:
        userIn = input("Input: ")
        if (userIn == 'q' or userIn == 'Q'):
            break
        else:
            print(c.send(userIn+'\r\n'))
    except(SyntaxError,NameError):
        print("Invalid input. Please try again or enter 'Q' to quit")

import yaml
import asyncio
import logging

with open("./config.yml", "r") as ymlfile:
    cfg = yaml.load(ymlfile, Loader=yaml.SafeLoader)

logcfg = cfg["logging"]
logging.basicConfig(
    format=logcfg["format"],
    datefmt=logcfg["datefmt"],
    level=logging.__getattribute__(logcfg["level"].upper()),
)

if __name__ == "__main__":
    from cycler import Cycler

    cycler = Cycler(cfg)
    asyncio.run(cycler.cycle_forever())