Example #1
0
def test_valid_coordinates():
    cases = (ValidCoordinatesCase(position=(12, 20), expected=False),
             ValidCoordinatesCase(position=(-1, 6), expected=False),
             ValidCoordinatesCase(position=(0, 3), expected=True),
             ValidCoordinatesCase(position=(11, 19), expected=True))
    logic = Logic()

    for case in cases:
        assert logic.valid_coordinates(case.position) == case.expected
Example #2
0
def main():
    start = default_timer()
    logic = Logic()
    logic.get_min_aa('DNA_input.txt')
    total_combinations = logic.convert_back_to_DNA()
    logic.write_output(total_combinations)
    duration = default_timer() - start
    print('Total execution Time is : ' + str(duration))
Example #3
0
def step_impl(context, DNA):
    """
    :type context: behave.runner.Context
    :type DNA - input string  : str
    """
    logic = Logic()
    logic.get_min_aa(DNA, False)
    total_combinations = logic.convert_back_to_DNA()
    logic.write_output(total_combinations)
Example #4
0
 def __init__(self):
     app = QtWidgets.QApplication(sys.argv)
     MainWindow = QtWidgets.QMainWindow()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(MainWindow)
     self.logic = Logic(self)
     self.thread = Thread(self.ui, self.logic)
     setupMenu(MainWindow, self.ui, self.logic, self.thread)
     MainWindow.show()
     setupActions(MainWindow, self.ui, self.logic)
     updateDisplay(self.ui, self.logic)
     sys.exit(app.exec_())
Example #5
0
 def restart(self):
     """Reset the GUI and game logic"""
     self.logic = Logic(self)
     self.gui.layout()
Example #6
0
class Game:
    """Tic-Tac-Toe Game Base Class

    `One class to rule them all`. Unifies the game logic and GUI in one central
    class

    Parameters
    ----------
    ai: `AIPlayer` or None
        User-selected computer opponent. Can be any of the classes defined in
        ``src.ai`` or ``None`` for a classic turn-taking game

    Attributes
    ----------
    logic: Logic
        Tic-tac-toe game logic
    gui: Gui
        Tic-tac-toe GUI
    ai: `AIPlayer` or None
        Possible computer opponent
    """
    def __init__(self, ai=None):
        super(Game, self).__init__()

        self.logic = Logic(self)
        self.gui = Gui(self)
        self.ai = ai

    @property
    def turn(self):
        """Get the symbol of the current player"""
        return self.logic.turn

    @property
    def size(self):
        """Get the size of the grid"""
        return self.logic.size

    def play(self, pos, play_ai=False):
        """Play a round in the game

        This method is called by the human and the AI computer opponent to place
        their symbol and update the GUI and game logic.

        Parameters
        ----------
        pos: `tuple` [int, int]
            Position on which to place current player's symbol
        play_ai: bool, optional
            Whether to let the computer opponnent player play immediately after
            this turn. Defaults to ``False``

        Returns
        -------
        bool
            Whether or not the game is over
        """
        self.gui.fields[pos].set_text(self.turn)

        is_over = self.logic.play(*pos)
        if is_over:
            winner = self.logic.is_end()
            self.gui.game_over(winner)
            return True

        if play_ai:
            return self.play_ai()

        return False

    def play_ai(self):
        """Play the AI if selected by the user

        Returns
        -------
        bool
            Whether or not the AI played
        """
        if not self.ai:
            return False
        self.ai.play(play_fn=self.play, game=self.logic)
        return True

    def restart(self):
        """Reset the GUI and game logic"""
        self.logic = Logic(self)
        self.gui.layout()

    def start(self):
        """Start the GUI"""
        return self.gui.start()
Example #7
0
    def __init__(self, ai=None):
        super(Game, self).__init__()

        self.logic = Logic(self)
        self.gui = Gui(self)
        self.ai = ai
Example #8
0
    def build(self):
        """In here, we build all the basic for our kivy stuff, like making our layout, initialize our mapview,
        our different buttons and so on, its also in here we call our gpsHandler, and call our placephotovogn"""

        self.logic = Logic(self)
        self.MenuFuncs = MenuFunctions(self)
        self.gpshandler = GpsHandler(self)
        self.offset = 0.001
        """initalizing the few colors in kivy binary"""
        self.Lightred = [1111111111, 0, 0, 1]
        self.black = [0, 0, 0, 1]
        self.green = [0, 1111111, 0, 1]
        """Creating MapView, which let us determ, zoom, lat and lon, essentiel it would be pulling from gps signlas"""
        self.mapview = MapView(zoom=15, lat=56.04,
                               lon=12.457)  #56.0394 , 12.457
        self.person = MapMarker(lat=self.mapview.lat,
                                lon=self.mapview.lon,
                                source='images/car.png')
        self.mapview.add_marker(self.person)
        """Making a layout, as a boxlayout, making it vertical to match our desired design"""
        self.layout = BoxLayout(orientation="vertical")
        """Initializing our buttons, then after connection them to functions, when they are pressed"""
        self.buttonAnmeld = Button(text="ANMELD!",
                                   font_size=100,
                                   color=self.black,
                                   background_color=self.green)
        self.buttonAlert = Button(text="ALARM!",
                                  font_size=200,
                                  color=self.black,
                                  background_color=self.Lightred,
                                  disabled=True,
                                  opacity=0)
        """Binding our botton to a specific function, lambda is so the function wont get called when iniialized"""
        self.buttonAnmeld.bind(on_press=lambda dt: self.logic.FotoVognSpotted(
            self.mapview.lat, self.mapview.lon))
        """Creating the dropdown menu"""
        self.dropdown = DropDown(size_hint_x=0.2)
        """Labels"""
        labels = [
            '  Reset Zoom', '  Zoom In', '  Zoom Out', ' Increase LAT',
            '  Decrease LAT', '  Increase LON', '  Decrease LON', "  Exit"
        ]
        """Functions"""
        functions = [
            self.MenuFuncs.resetZoom, self.MenuFuncs.zoomIn,
            self.MenuFuncs.zoomOut, self.MenuFuncs.IncreaseLat,
            self.MenuFuncs.DecreaseLat, self.MenuFuncs.IncreaseLon,
            self.MenuFuncs.DecreaseLon, self.MenuFuncs.exit
        ]
        """Creating buttons for each label, give them their corresponding function, allign them at  left,
        and last, adding them to the dropdown widget"""
        for label, func in zip(labels, functions):
            self.btn = Button(text=label,
                              size_hint_y=None,
                              height=45,
                              halign="left",
                              valign="middle")
            self.btn.bind(size=self.btn.setter('text_size'))
            self.btn.bind(on_release=func)

            self.dropdown.add_widget(self.btn)
        """Creating our menuMainButton, also alligned at left"""
        self.mainbutton = Button(text='  Menu',
                                 size_hint_y=None,
                                 height=35,
                                 halign="left",
                                 valign="middle",
                                 size_hint_x=0.2)

        self.mainbutton.bind(size=self.mainbutton.setter('text_size'))
        self.mainbutton.bind(on_release=self.dropdown.open)
        """Adding all the different stuff to our layout, in the desired order"""
        self.layout.add_widget(self.mainbutton)
        self.layout.add_widget(self.buttonAnmeld)
        self.layout.add_widget(self.mapview)
        self.layout.add_widget(self.buttonAlert)

        self.logic.PlaceFotoVogn()
        self.gpshandler.run()
        """Returning the layout"""
        return self.layout
Example #9
0
class MyApp(App):
    """Main class for all our kivy stuff, there is a few functions in here, update which is called in
    on_start, which call update every 0.1 seconds"""
    def update(self, _):
        """Get gps signals, update them, if its not android, update according to center of mapview"""

        print(self.logic.placedVogne)
        """Check, if its an andorid device, if it is, gps signals are recieved"""
        if not self.gpshandler.androidBool:
            self.latitude = self.mapview.lat
            self.longitude = self.mapview.lon

        else:
            self.latitude = self.gpshandler.my_lat
            self.longitude = self.gpshandler.my_lon

        if not self.logic.alerting:
            for i in self.logic.placedVogne:
                if math.fabs(
                    (float(self.latitude) -
                     float(i[0]))) < self.offset and math.fabs(
                         (float(self.longitude) - float(i[1]))) < self.offset:
                    self.logic.Alert()

        self.person.lat = self.latitude
        self.person.lon = self.longitude

    def on_start(self):
        """When app is started, this is called, which starts a clock calling update"""
        Clock.schedule_interval(self.update, 0.1)

    def build(self):
        """In here, we build all the basic for our kivy stuff, like making our layout, initialize our mapview,
        our different buttons and so on, its also in here we call our gpsHandler, and call our placephotovogn"""

        self.logic = Logic(self)
        self.MenuFuncs = MenuFunctions(self)
        self.gpshandler = GpsHandler(self)
        self.offset = 0.001
        """initalizing the few colors in kivy binary"""
        self.Lightred = [1111111111, 0, 0, 1]
        self.black = [0, 0, 0, 1]
        self.green = [0, 1111111, 0, 1]
        """Creating MapView, which let us determ, zoom, lat and lon, essentiel it would be pulling from gps signlas"""
        self.mapview = MapView(zoom=15, lat=56.04,
                               lon=12.457)  #56.0394 , 12.457
        self.person = MapMarker(lat=self.mapview.lat,
                                lon=self.mapview.lon,
                                source='images/car.png')
        self.mapview.add_marker(self.person)
        """Making a layout, as a boxlayout, making it vertical to match our desired design"""
        self.layout = BoxLayout(orientation="vertical")
        """Initializing our buttons, then after connection them to functions, when they are pressed"""
        self.buttonAnmeld = Button(text="ANMELD!",
                                   font_size=100,
                                   color=self.black,
                                   background_color=self.green)
        self.buttonAlert = Button(text="ALARM!",
                                  font_size=200,
                                  color=self.black,
                                  background_color=self.Lightred,
                                  disabled=True,
                                  opacity=0)
        """Binding our botton to a specific function, lambda is so the function wont get called when iniialized"""
        self.buttonAnmeld.bind(on_press=lambda dt: self.logic.FotoVognSpotted(
            self.mapview.lat, self.mapview.lon))
        """Creating the dropdown menu"""
        self.dropdown = DropDown(size_hint_x=0.2)
        """Labels"""
        labels = [
            '  Reset Zoom', '  Zoom In', '  Zoom Out', ' Increase LAT',
            '  Decrease LAT', '  Increase LON', '  Decrease LON', "  Exit"
        ]
        """Functions"""
        functions = [
            self.MenuFuncs.resetZoom, self.MenuFuncs.zoomIn,
            self.MenuFuncs.zoomOut, self.MenuFuncs.IncreaseLat,
            self.MenuFuncs.DecreaseLat, self.MenuFuncs.IncreaseLon,
            self.MenuFuncs.DecreaseLon, self.MenuFuncs.exit
        ]
        """Creating buttons for each label, give them their corresponding function, allign them at  left,
        and last, adding them to the dropdown widget"""
        for label, func in zip(labels, functions):
            self.btn = Button(text=label,
                              size_hint_y=None,
                              height=45,
                              halign="left",
                              valign="middle")
            self.btn.bind(size=self.btn.setter('text_size'))
            self.btn.bind(on_release=func)

            self.dropdown.add_widget(self.btn)
        """Creating our menuMainButton, also alligned at left"""
        self.mainbutton = Button(text='  Menu',
                                 size_hint_y=None,
                                 height=35,
                                 halign="left",
                                 valign="middle",
                                 size_hint_x=0.2)

        self.mainbutton.bind(size=self.mainbutton.setter('text_size'))
        self.mainbutton.bind(on_release=self.dropdown.open)
        """Adding all the different stuff to our layout, in the desired order"""
        self.layout.add_widget(self.mainbutton)
        self.layout.add_widget(self.buttonAnmeld)
        self.layout.add_widget(self.mapview)
        self.layout.add_widget(self.buttonAlert)

        self.logic.PlaceFotoVogn()
        self.gpshandler.run()
        """Returning the layout"""
        return self.layout
Example #10
0
def run_loop():
    while True:
        sys.stdout.write("-----\n")
        sys.stdout.flush()

        try:
            logging.info("Starting up trader...")
            logging.info('Symbol: ' + symbol)

            # initialize first kalman row if it doesn't exist
            try:
                KalmanTbl.get()
            except peewee.DoesNotExist:
                logging.info("Initializing first kalman row.")
                KalmanTbl.create(ts=int(time.time() * 1000),
                                 C=0,
                                 V=0,
                                 e=0,
                                 yhat=0,
                                 m=0,
                                 Q=0,
                                 K=0,
                                 P=0,
                                 R=0,
                                 Ve=0,
                                 max_vol=0)

            Util.update_balances(client, symbol)

            # TODO: Use is_time_horizon() to guarantee optimal kalman times for a given pair
            # if Util.is_time_horizon(launchtime, freq = datetime.timedelta(hours=4)):
            k = Kalman()
            kalman_mean, Q = k.kalman(symbol, client)
            # else:
            #   print('Not updating () for this time: '.format(symbol), launchtime)
            #   kalman_mean, Q = None, None

            # Pull/Write Orderbooks
            try:
                df_buy, df_sell = BitMex.pull_bitmex_orderbooks(symbol, 30)
            except:
                start_ts = time.time()
                req_log = [
                    start_ts, start_ts, start_ts,
                    sys.exc_info(), symbol, 'orders fail'
                ]
                logging.info(req_log)

            # Trade logic
            # Execute trade as long as order books are passed on
            if ((df_buy is not None) and (kalman_mean is not None)):
                try:
                    # TODO: use time horizon
                    # if Util.is_time_horizon(launchtime, freq = datetime.timedelta(hours=4)):
                    logic = Logic(symbol=symbol,
                                  client=client,
                                  m=kalman_mean,
                                  Q=Q,
                                  trade_alloc=40.0,
                                  mode='live',
                                  df_buy=df_buy,
                                  df_sell=df_sell)
                    logic.trade_logic()
                    # else:
                    #   logging.info('Not trading {} for this time: '.format(symbol) + str(launchtime))
                except Exception as e:
                    logging.error(e)
            else:
                logging.info(
                    'Cannot trade. kalman_mean = {}'.format(kalman_mean))

            ## TODO: we should log and store dealt orders to DB

            # Script loop success log
            end_ts = time.time()
            req_log = [
                s_ts,
                int(end_ts),
                int(end_ts), 'Success', 'all_kucoin', 'Full Script Run'
            ]
            logging.info(req_log)
            logging.info('SUCCESS - Done in {}'.format(end_ts - s_ts))
            time.sleep(30)
        except:
            logging.error('Failed: ' + str(sys.exc_info()))
            end_ts = time.time()
            req_log = [
                s_ts, end_ts, end_ts, 'Fail', 'all_kucoin', 'Script fail'
            ]
            logging.info(req_log)
            sys.exit()