def welcomeInterface(self, pantry):
        print("========================================")
        print("Create an order with GourmetBurgers.com!")

        while True:
            print("========================================")
            print("Type 1 to add a main.")
            print("Type 2 to add a side.")
            print("Type 3 to review your order.")
            print("Type 4 to confirm order.")
            print("Type C to cancel your order.")
            print("========================================")
            command = input("What would you like to do? ")

            if command.upper() == "C":
                self.status = orderStatus.CANCELED
                break
            elif command.isdigit() == True:
                if int(command) == 1:
                    newMain = Main()  #GLORIA ADD MAINS LOGIC
                    newMain.mainInterface(pantry)
                    if newMain._totalMainPrice != 0.0:
                        self.addOrderMain(newMain)

                elif int(command) == 2:
                    newSide = Side()
                    newSide.sideInterface(pantry)
                    if newSide.side != None:
                        self.addOrderSides(newSide)
                elif int(command) == 3:
                    self.printEntireOrder()
                elif int(command) == 4:
                    self.confirmOrder()
                    if self.status == orderStatus.CONFIRMED:
                        break
예제 #2
0
 def setup_method(self):
     self.newSystem = onlineOrderSystem()
     ingred1 = self.newSystem.pantry.createNewIngredient("Buns", 1, 1)
     ingred2 = self.newSystem.pantry.createNewIngredient("Beef Patty", 1, 1)
     self.newSystem.pantry.addMainIngredient(ingred1)
     self.newSystem.pantry.addMainIngredient(ingred2)
     self.newMain = Main()
예제 #3
0
    def test_main_output(self):
        source = '12'
        level = None

        print Main.build_main_output(source, level)
        print(
            '============================================================\n'
            'File Name\n'
            '------------------------------------------------------------\n'
            'Array.jack\n'
            'Keyboard.jack\n'
            'Math.jack\n'
            'Memory.jack\n'
            'Output.jack\n'
            'Screen.jack\n'
            'String.jack\n'
            'Sys.jack\n'
            '------------------------------------------------------------\n'
            'FILES: 8\n'
            '============================================================\n')
        assert Main.build_main_output(source, level) == (
            '============================================================\n'
            'File Name\n'
            '------------------------------------------------------------\n'
            'Array.jack\n'
            'Keyboard.jack\n'
            'Math.jack\n'
            'Memory.jack\n'
            'Output.jack\n'
            'Screen.jack\n'
            'String.jack\n'
            'Sys.jack\n'
            '------------------------------------------------------------\n'
            'FILES: 8\n'
            '============================================================\n')
예제 #4
0
class TestTransaction(unittest.TestCase):
    def setUp(self):
        self.trx = Main()

    def test_init(self):
        self.trx.process('glob is I prok is V pish is X tegj is L')
        pass
예제 #5
0
class Splash_Screen(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_Splash_Screen()
        self.ui.setupUi(self)

        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.progress)
        self.timer.start(10)

        self.show()

    def progress(self):
        global splash_counter

        self.ui.progressBar.setValue(splash_counter)

        if splash_counter > 100:
            self.timer.stop()

            user = User()
            if user.is_logged_in:
                self.main = Main(user)
                self.main.show()
                self.close()
            else:
                self.login = Login(user)
                self.login.show()
                self.close()

        splash_counter += 1
예제 #6
0
class MainTestCase(AlgorithmTestCase):
    def runTest(self):
        # configure params for your algorithm
        self.params = {}

        self.alg = Main(cl=self.cl, params=self.params)
        self.alg.run()
예제 #7
0
    def comecar_jogo(self):
        jogo_comecado = Main()
        encerrar, pontuacao = jogo_comecado.main(self.__volume / 4)

        if encerrar:
            self.salvar_pontuacao(pontuacao)
            self.tela_fim()
예제 #8
0
class Registration(QDialog):
    def __init__(self):
        super().__init__()
        uic.loadUi("designer/registration.ui", self)
        self.setWindowTitle("Регистрация")
        self.dbm = DataBaseManager()
        self.mn = None
        self.result = -1
        self.auth_btn.clicked.connect(self.auth_clicked)

    def auth_clicked(self):
        try:
            login = self.login_text.text()
            pw = self.pw_text.text()
            pw2 = self.pw2_text.text()
            if login != "" and pw != "" and pw2 != "":
                if pw == pw2:
                    self.dbm.create_all_tables()
                    self.dbm.create_priories()
                    self.dbm.set_auth_data(login, pw)
                    if os.path.exists("startup"):
                        os.remove("startup")
                    self.mn = Main(self.dbm)
                    self.mn.show()
                    self.hide()
                else:
                    QMessageBox.warning(self, "Ошибка", "Пароли не совпадают.")
            else:
                QMessageBox.warning(self, "Ошибка", "Заполните пустые поля!")
        except Exception as ex:
            self.dbm.log.append(LOG_ERROR, "Fatal error on registration. " + str(ex))
예제 #9
0
class Login(QWidget):
    def __init__(self, user):
        QWidget.__init__(self)
        self.ui = Ui_Login()
        self.ui.setupUi(self)
        self.user = user

        self.ui.login_btn.clicked.connect(self.login_click)

    def login_click(self):
        email = self.ui.email_line.text()
        password = self.ui.password_line.text()
        remember = self.ui.check_remember.isChecked()

        self.user.login(email, password, remember)

        if self.user.is_logged_in:
            self.main = Main(self.user)
            self.main.show()
            self.close()
        else:
            QMessageBox.warning(
                self, "Login failed",
                "The email and password you entered did not match our records. Please double-check and try again."
            )
예제 #10
0
def Start():
    ObjectContainer.art = R(PLUGIN_ART)
    ObjectContainer.title1 = PLUGIN_NAME
    DirectoryObject.thumb = R(PLUGIN_ICON)
    DirectoryObject.art = R(PLUGIN_ART)
    PopupDirectoryObject.thumb = R(PLUGIN_ICON)
    PopupDirectoryObject.art = R(PLUGIN_ART)

    if not Singleton.acquire():
        log.warn('Unable to acquire plugin instance')

    # Complete logger initialization
    LoggerManager.setup(storage=True)

    # Store current proxy details
    Dict['proxy_host'] = Prefs['proxy_host']

    Dict['proxy_username'] = Prefs['proxy_username']
    Dict['proxy_password'] = Prefs['proxy_password']

    # Store current language
    Dict['language'] = Prefs['language']

    # Start plugin
    m = Main()
    m.start()
예제 #11
0
def Start():
    ObjectContainer.art = R(PLUGIN_ART)
    ObjectContainer.title1 = PLUGIN_NAME
    DirectoryObject.thumb = R(PLUGIN_ICON)
    DirectoryObject.art = R(PLUGIN_ART)
    PopupDirectoryObject.thumb = R(PLUGIN_ICON)
    PopupDirectoryObject.art = R(PLUGIN_ART)

    if not Singleton.acquire():
        log.warn("Unable to acquire plugin instance")

    # Complete logger initialization
    LoggerManager.setup(storage=True)

    # Store current proxy details
    Dict["proxy_host"] = Prefs["proxy_host"]

    Dict["proxy_username"] = Prefs["proxy_username"]
    Dict["proxy_password"] = Prefs["proxy_password"]

    # Store current language
    Dict["language"] = Prefs["language"]

    # Start plugin
    m = Main()
    m.start()
예제 #12
0
class Index(QWidget):
    def __init__(self, parent=None):
        super(Index, self).__init__(parent)
        self.initUI()
        QTimer.singleShot(2000, self.closeWindow)  # 定时器,定时关闭

    def initUI(self):
        '''
        初始化UI
        :return:
        '''
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.palette = QPalette()
        self.pix = QPixmap("D:/1.jpg")
        self.palette.setBrush(QPalette.Background, QBrush(self.pix))
        self.setPalette(self.palette)
        self.resize(self.pix.size())
        self.center()  # 屏幕居中显示

    def center(self):
        '''
        窗口在屏幕居中显示
        :return:
        '''
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def closeWindow(self):
        self.close()
        self.mainWindow = Main()
        self.mainWindow.show()
예제 #13
0
 def login(self):  # Аутентификация пользователя
     con = sqlite3.connect("users_db.sqlite")
     cur = con.cursor()
     login = cur.execute("""SELECT login from users WHERE login = ?""",
                         (self.edit_login.text(), )).fetchall()
     if not login:
         QMessageBox.about(
             self, "Ошибка!",
             "Пользователя с таким логином не существует. Попробуйте еще "
             "раз или зарегестрируйтесь")
         con.close()
     else:
         password = cur.execute(
             """SELECT password from users WHERE login = ?""",
             (self.edit_login.text(), )).fetchall()
         cur.execute("""UPDATE login_now SET login = ? WHERE id = ?""",
                     (self.edit_login.text(), 1))
         con.commit()
         if str(password[0][0]) != str(self.edit_password.text()):
             QMessageBox.about(self, "Ошибка!",
                               "Неверный пароль. Попробуйте еще раз")
         else:
             self.log1 = Main(self)
             self.log1.show()
         con.close()
예제 #14
0
    def __do_action(self, message_dict):
        action_type = message_dict["type"]
        receive_data = message_dict["data"]

        if action_type is RequestType.START:
            parsed_objects = JsonToObjectParser()
            parsed_objects.create_graph_structure(receive_data)
            self.main = Main(parsed_objects.places, parsed_objects.transitions, parsed_objects.links)

            return self.write_message(self.main.start_simulation())
        elif action_type is RequestType.SIMULATE:
            try:
                return self.write_message(self.main.simulate())
            except AttributeError:
                return self.write_message(json.dumps({'error': 'Network is empty. Please send network parameters first.'}))
        elif action_type is RequestType.GRAPH_FEATURES:
            try:
                return self.write_message(self.main.get_graph_features())
            except AttributeError:
                return self.write_message(json.dumps({'error': 'Network is empty. Please send network parameters first.'}))
        elif action_type is RequestType.VECTOR_NETWORK_CONSERVATIVE:
            try:
                return self.write_message(self.main.is_network_vector_conservative(ast.literal_eval(receive_data)))
            except AttributeError:
                return self.write_message(json.dumps({'error': 'Network is empty. Please send network parameters first.'}))
        elif action_type is RequestType.LIVE_TRANSITIONS:
            try:
                return self.write_message(self.main.get_live_transitions())
            except AttributeError:
                return self.write_message(json.dumps({'error': 'Network is empty. Please send network parameters first.'}))
        elif action_type is RequestType.RUN_SELECTED_TRANSITION:
            try:
                return self.write_message(self.main.run_selected_transitions(receive_data))
            except AttributeError:
                return self.write_message(json.dumps({'error': 'Network is empty. Please send network parameters first.'}))
예제 #15
0
파일: auth.py 프로젝트: VNCompany/PyDafm
 def __init__(self):
     super().__init__()
     uic.loadUi("designer/authorization.ui", self)
     self.setWindowTitle("Вход")
     self.dbm = DataBaseManager()
     self.mn = Main(self.dbm)
     self.auth_btn.clicked.connect(self.auth_clicked)
예제 #16
0
 def setup_method(self):
     self.newSystem = onlineOrderSystem()
     ingred1 = self.newSystem.pantry.createNewIngredient("Tortillas", 1, 1)
     ingred2 = self.newSystem.pantry.createNewIngredient("Chicken", 1, 0)
     self.newSystem.pantry.addMainIngredient(ingred1)
     self.newSystem.pantry.addMainIngredient(ingred2)
     self.newMain = Main()
예제 #17
0
    def Run(self, event=0):

        self.objMain = Main()

        self.consoleT.delete(1.0, END)

        #open file and write all the IDE code text area content
        self.codeFile = open(Main._codeFile, 'w')
        self.codeFile.write(self.codeT.get('1.0', END))
        self.codeFile.close()

        #open file for reading
        self.codeFile = open(Main._codeFile, 'rb+')
        self.objMain.mainMethod(self.codeFile)
        self.codeFile.close()

        #write tokens to console area
        self.consoleT.insert(1.0, Main._fileData)

        #write tokens to test file
        self.outputFile = open(Main._outputFile, 'w')
        self.outputFile.write(Main._fileData)
        self.outputFile.close()

        #call syntax
        # self.objMain.PROG()

        self.objSyntax = Syntax(Main._tokens)
        self.objSemantic = Semantic(Main._tokens)

        if self.objSyntax.PROG():
            print("Code is parsed")
        else:
            print("there is error in code")
예제 #18
0
    def show_login_window(self):

        # declaring variables

        main = Main()
        main.__init__()

        lroot = Tk()
        lroot.grid()
        lroot.title = "Login"
        lroot.wm_title("Login")

        def login():
            name = usrname.get()
            passwd = usrpasswd.get()

            if self.login_attempts < self.max_login_attempts:
                if self.check(name, passwd):
                    print("User " + name + " logged in successfully")
                    lroot.destroy()
                    main.show_main()
                    print(self.login_attempts)
                else:
                    self.login_attempts += 1
                    print("User " + name + " cannot be logged in: Wrong username/password")
            else:
                print("User " + name + " cannot be logged in: Too much login attempts. Login blocked")

                # Adding elements to window

                # input fields

                # username

        lbusrname = Label(lroot, text="Username:"******"Passwort:")
        lbusrpasswd.grid(pady=1, padx=1, row=1, column=0)

        usrpasswd = Entry(lroot, show="*")
        usrpasswd.grid(pady=1, padx=1, row=1, column=1)

        # buttons

        # login
        btlogin = Button(lroot, text="Login", command=login)
        btlogin.grid(pady=1, padx=1, row=2, column=1, sticky="E")

        # closing the window
        btquit = QuitButton(lroot)
        btquit["text"] = "Schließen"
        btquit.grid(pady=1, padx=1, row=2, column=1, sticky="W")

        lroot.mainloop()
예제 #19
0
def test_add(capsys):
    main = Main()
    main.add_player("Carl")
    out, err = capsys.readouterr()
    assert ((Player("Carl", "b") in main.players)
            or (Player("Carl", "y") in main.players))
    assert ("Added: Player(name='Carl', color='y')\n" == out
            or "Added: Player(name='Carl', color='b')\n" == out)
예제 #20
0
 def init_test(self):
     main = Main()
     countries = main.get_list_of_countries()
     report = CountryReport(countries)
     self.assertIsNotNone(report.avg)
     self.assertIsNotNone(report.max)
     self.assertIsNotNone(report.min)
     self.assertIsNotNone(report.sum)
예제 #21
0
    def setUp(self):
        def dummy_init(self):
            pass  # pragma: no cover

        self.orig_init = Main.__init__
        Main.__init__ = dummy_init
        self.main = Main()
        self.main.active_scene = MagicMock(spec=TitleScene)
예제 #22
0
    def test_entry_invalid_option(self):
        """
		Verify an empty option that includes just kind of work but no one more argument
		"""
        Args = ["c"]
        with pytest.raises(SystemExit) as pytest_wrapped_e:
            m = Main(Args)
            m.main()
        assert pytest_wrapped_e.type == SystemExit
예제 #23
0
    def test_passing_3p_4produts_2c_4length_return_not_empty_estructure(self):
        qtdP = 3
        qtdV = 4
        qtdC = 2
        n = 4
        programa = Main()
        programa.main_func(qtdP, qtdV, qtdC, n, log=LoggerFake())

        self.assertTrue(programa.estrutura.consumidos)
예제 #24
0
def start():
    config = Main.default_config()
    config['name'] = '__test__'

    main = Main(config)
    aug = get_augmentation()

    # show_classes(main)
    show_augmentations(aug, main, n=4)
예제 #25
0
    def test_passing_3p_4produts_2c_4length_return_allprodutcs(self):
        qtdP = 3
        qtdV = 4
        qtdC = 2
        n = 4
        programa = Main()
        programa.main_func(qtdP, qtdV, qtdC, n, log=LoggerFake())

        self.assertTrue(Testing.assertProducts(programa, qtdP, qtdV)[0])
예제 #26
0
 def __init__(self):
     self.a = Main()
     self.a.launch()
     while self.a.du > 0:
         self.a.index()
         self.a.choice()
     else:
         for letter in self.a.word:
             print letter,
예제 #27
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(config['screen']['size'])

    elem = WaitForPlayersWindow(Rect(0, 0, *config['screen']['size']),
                                Color('bisque'))

    m = Main(elem, screen)
    m.loop()
예제 #28
0
 def setUp(self):
     self.p1 = Place(name='p1', id=1, tokens=1)
     self.p2 = Place(name='p2', id=2, tokens=0)
     self.c1 = Connector(1, self.p1, Direction.PLACE_TO_TRANSITION, 1)
     self.c2 = Connector(2, self.p2, Direction.TRANSITION_TO_PLACE, 1)
     self.c3 = Connector(3, self.p2, Direction.PLACE_TO_TRANSITION, 1)
     self.t1 = Transition([self.c1], [self.c2], 1, id=1, name='t1')
     self.t2 = Transition([self.c3], [], 1, id=2, name='t2')
     self.main = Main([self.p1, self.p2], [self.t1, self.t2], [self.c1, self.c2])
예제 #29
0
 def test_main_app_shows_adverts_menu(self):
     #Check that the output from the menu for the first option displays the 3 elements created at statup
     main = Main()
     ads = main.construct_adverts()
     self.assertEqual(ads.count("ID"), 3)
     #Now delete the adverts and make sure there is none
     main.adverts_list = []
     ads = main.construct_adverts()
     self.assertEqual(ads.count("ID"), 0)
예제 #30
0
    def test_entry_d_option_no_files(self):
        """
		User enters an option known but no arguments enough
		"""
        Args = ["d"]
        with pytest.raises(SystemExit) as pytest_wrapped_e:
            m = Main(Args)
            m.main()
        assert pytest_wrapped_e.type == SystemExit
예제 #31
0
 def test_integration(self):
     main = Main(game_path, 1)
     main._load_players()
     main._run_tournament()
     self.assertTrue(os.path.exists(log_file))
     video_visualizer = VideoVisualizer(24, config.Painter, file_mask,
                                        'logs/tournament1')
     video_visualizer.compile('test_video.mpg')
     self.assertTrue(os.path.exists('logs/tournament1/test_video.mpg'))
 def test_main_app_shows_adverts_menu(self):
     #Check that the output from the menu for the first option displays the 3 elements created at statup
     main = Main()
     ads = main.construct_adverts()
     self.assertEqual(ads.count("ID"), 3)
     #Now delete the adverts and make sure there is none
     main.adverts_list = []
     ads = main.construct_adverts()
     self.assertEqual(ads.count("ID"), 0)
예제 #33
0
    def test_entry_option_unknown(self):
        """
		Verify when users enters a no valid option/argument
		"""
        Args = ["Random word", randint(0, 2000), randint(0, 131000)]

        with pytest.raises(SystemExit) as pytest_wrapped_e:
            m = Main(Args)
            m.main()
        assert pytest_wrapped_e.type == SystemExit
 def test_updated_events_get_correctly_updated(self):
     #Checks that constructed adverts can get price and quantity modified correctly
     main = Main()
     advert = main.adverts_list[0]
     old_price = advert.price
     old_quantity = advert.quantity
     advert = main.update_advert(advert, 'price', 99.99)
     self.assertNotEqual(advert.price, old_price)
     advert = main.update_advert(advert, 'quantity', 10)
     self.assertNotEqual(advert.quantity, old_quantity)
예제 #35
0
def update(request, rs_path_id):
    search_form = SearchWay()
    Main.update_a_record(rs_path_id)
    return render(
        request, 'show/index.html', {
            'form': search_form,
            'text_header': u'Quá trình kiếm kiếm đã diễn ra thuận lợi',
            'rs_path': Path.objects.get(pk=rs_path_id),
            'text_4_test': u'Kết quả đã tìm được: '
        })
예제 #36
0
def testTheme(filename='test/index.html'):
  #logging.basicConfig(filename='log.debug',level=logging.DEBUG)
  logging.basicConfig(level=logging.DEBUG)
  main=Main()
  filefetcher=FileFetcher(filename)
  main.parseContent(filefetcher)
  print main.themes
  if True:
    printTree(main.themes)    
  return
예제 #37
0
def main():

    def update_splash(text):
        splash.showMessage(text)
        app.processEvents()

    app = QtGui.QApplication(sys.argv)
    splash_img = QtGui.QPixmap(':images/splash.png')
    splash = QtGui.QSplashScreen(splash_img, QtCore.Qt.WindowStaysOnTopHint)
    splash.show()
    time.sleep(.001)
    update_splash("Establishing Connection...")
    if not dbConnection.default_connection():
        QtGui.QMessageBox.critical(None, "No Connection!", "The database connection could not be established.")
        sys.exit(1)
    update_splash("Loading GUI...")
    myapp = Main()
    myapp.tab_loaded.connect(update_splash)
    myapp.setWindowIcon(QtGui.QIcon(':images/post_laser_schedule.ico'))
    myapp.show()
    update_splash("GUI Loaded...")
    myapp.load_tabs()
    update_splash("Loading Actions...")
    myapp.load_actions()
    splash.finish(myapp)
    sys.exit(app.exec_())
예제 #38
0
        def run(self):
                """
                        Control DepDep start or stop and daemonize depdep ...
                """

                depdep = Main(self.args.config, self.args.verbose, self.args.wipe)
		try:	
                	depdep.run()
		except Exception, err_mess:
			print err_mess
			sys.exit(1)
예제 #39
0
def input():
    result={}
    if request.method == 'POST':
        text = request.form['text']
        main = Main(text)
        result = main.get_output()
        threshold = int(request.form["threshold"])
        order = main.get_order()
        return render_template("input.html", result=result, threshold=threshold, order=order)
    else:
        return render_template("input.html", result=result)
예제 #40
0
 def updateNew(self):
   logging.basicConfig(filename='update.log',level=logging.DEBUG)
   #logging.getLogger('core').setLevel(logging.INFO)
   main=Main(self.session)
   main.parseContent(MainFetcher())
   self.session.flush()
   # themes, categories and emissions are loaded
   # let's update the database with new emissions
   # load all new videos XML files from  
   self.updateEmissions()
   self.session.commit()
예제 #41
0
    def test_stdin(self, parse_args, stdin_patch):
        emails = ['*****@*****.**']
        stdin_patch.return_value = emails
        options = self.test_options
        options.stdin = True
        parse_args.return_value = options

        program = Main(test=True)
        program.run()

        eq_(program.get_matches(), emails)
        eq_(stdin_patch.call_count, 1)
예제 #42
0
def update(request, rs_path_id):
    search_form = SearchWay()
    Main.update_a_record(rs_path_id)
    return render(request,
                  'show/index.html',
                  {
                      'form': search_form,
                      'text_header': u'Quá trình kiếm kiếm đã diễn ra thuận lợi',
                      'rs_path': Path.objects.get(pk=rs_path_id),
                      'text_4_test': u'Kết quả đã tìm được: '
                  }
                  )
    def run(self, edit):
        #self.view.insert(edit, 0, "Hello, World!")
        file_name = sublime.active_window().active_view().file_name()

        log_analyzer = Main(file_name, sublime.packages_path() + "/settings.json", sublime.packages_path() + '/modified_file.log')
        log_analyzer.perform_analysis()
        #sublime.status_message("current_dir:" + os.path.abspath(os.curdir))

        sublime.active_window().open_file(log_analyzer.output_filename)

        sublime.active_window().active_view().settings().set("syntax", "log_analyzer.tmLanguage")
        #sublime.active_window().active_view().settings().set("syntax", "Python/Python.tmLanguage")
        #sublime.status_message(str(sublime.active_window().settings().get("syntax")))
예제 #44
0
파일: views.py 프로젝트: vishnuvr/trading
def notify(request):
    log.info('Request Notifying me')

    # check if weekday is 1..5
    today = datetime.utcnow()
    if today.isoweekday() not in range(1, 6):
        log.info('Weekend: no trading')
    else:
        main = Main(False)
        main.notifyMe()

    log.info('Request Me notified')
    return http.HttpResponse()
예제 #45
0
    def test_url(self, parse_args, file_patch):
        emails = ['*****@*****.**']
        file_patch.return_value = emails
        options = self.test_options
        options.path = 'test_path'
        parse_args.return_value = options

        program = Main(test=True)
        program.run()

        eq_(program.get_matches(), emails)
        eq_(file_patch.call_count, 1)
        eq_(file_patch.call_args, call('test_path'))
예제 #46
0
    def test_output(self, parse_args, write_patch, get_matches):
        emails = ['*****@*****.**']
        get_matches.return_value = emails
        write_patch.return_value = emails
        options = self.test_options
        options.output = 'test_output'
        parse_args.return_value = options

        program = Main(test=True)
        program.run()
        program.output()

        eq_(write_patch.call_count, 1)
        eq_(write_patch.call_args, call('test_output', emails))
 def test_events_with_updates_get_modifications(self):
     #Checks that updated adverts have correct modifications
     main = Main()
     advert = main.adverts_list[0]
     old_price = advert.price
     old_quantity = advert.quantity
     advert = main.update_advert(advert, 'price', 99.99)
     self.assertNotEqual(advert.price, old_price)
     advert = main.update_advert(advert, 'quantity', 10)
     self.assertNotEqual(advert.quantity, old_quantity)
     mod_list = main.modifications_dict[advert.id]
     self.assertEqual(len(mod_list), 2)
     mod = mod_list[0]
     self.assertEqual(mod.price, advert.price)
예제 #48
0
 def run_model_thread_body(self, callback=None):
     keras = None
     model = self.model_naming[self.selected_model]
     try:
         import keras
         if self.training_set_type == 'single':
             Main.single(model, self.selected_input_file, self.choruses, self.model_order, self.epochs, callback)
         elif self.training_set_type == 'weimar':
             Main.weimar(model, self.selected_seed_file, self.choruses, self.model_order, self.epochs, callback)
     except Exception as e:
         if callback:
             callback.error(str(e))
     finally:
         if keras and keras.backend.backend() == 'tensorflow':
             keras.backend.clear_session()
def registration_form():
    try:
        applicant = Applicant.create_from_form(request.form)
    except:
        applicant = Applicant(first_name="", last_name="", email="", city="")

    if request.method == "POST":
        validation_result = applicant.valid()
        if len(validation_result) == 0:
            applicant.save()
            Main.register()
            return render_template('base.html', message="Thanks for your registration :)")
        else:
            return render_template('registration.html', applicant=applicant, errors=validation_result)
    return render_template('registration.html', applicant=applicant)
예제 #50
0
파일: launcher.py 프로젝트: kamchy/womoon
  def cb_open(self, main_wnd, fname):
    """
    Callback of "Open" menu button from main_wnd.
    Assume fname is not None
    """
    if main_wnd is None:
      main_wnd = self.cb_new(None)

    try:
      if main_wnd.project.is_untouched():
        main_wnd.project.load(fname)
      else:
        project = self.load_project(fname)
        self.show_main(project, ChartProject.LOADED)
    except:
      Main.show_warning(main_wnd, Main.INVALID_FORMAT,  Main.CANNOT_READ_FILE % fname)
예제 #51
0
파일: test_main.py 프로젝트: iver56/it3105
    def test_parse_lines(self):
        num_vertices, num_edges, vertices, edges = Main.parse_lines(self.lines1)

        self.assertEqual(num_vertices, 3)
        self.assertEqual(num_edges, 3)
        self.assertEqual(len(vertices), 3)
        self.assertEqual(len(edges), 3)
예제 #52
0
파일: game.py 프로젝트: AkiraKane/Python
class Game:
    """
    This is the game manager modle 
    """
    def __init__(self):
        self.stat = 'menu'
        pygame.mixer.pre_init(44100, 16, 2, 1024*4) #mixer pre_init arguments
        pygame.init()
        pygame.display.set_caption("TETRIS_FUNNY") 
        self.init()
        try:
            self.screen = pygame.display.set_mode((640, 480),
                    HWSURFACE | SRCALPHA, 32)
        except:
            self.screen = pygame.display.set_mode((640, 480),
                    SRCALPHA, 32)
        try:
            pygame.display.set_icon(pygame.image.load(
                        util.file_path("icon.png")).convert_alpha())
        except:
            print "can't find icon picture under data directory"
            pass
        #init sub modules
        self.menu = Menu(self.screen)
        self.main = Main(self.screen)
    
    def init(self):
        util.init()
        sound.load()

    def loop(self):
        clock = pygame.time.Clock()
        while self.stat != r'quit':
            elapse = clock.tick(60)
            if self.stat == r'menu':
                self.stat = self.menu.run(elapse)
            elif self.stat == r'game':
                self.stat = self.main.run(elapse)

            if self.stat.startswith('level'):
                level = int(self.stat.split()[1])
                print "Start game at level", level
                self.main.start(level)
                self.stat = r"game"
            pygame.display.update()
        pygame.quit()
예제 #53
0
 def convert(self, name = None):
     
     if self.text_variable['outline'].get() == 'choose a shape':
         text = 'Error: no shape is selected.\n   Please choose a shape.'
         self.popup(text, 'Error', '+300+300')
     else:
         if name == None:
             self.save('gcode')
         else:
             self.save(name)
         
         #check if the user cancelled converting to Gcode
         if self.savePath and self.text_variable['outline'].get() != 'choose a shape':
             #convert to Gcode
             conversion = Main(self.filename, self.g_robot_var.get())
             conversion.run()
             os.remove(self.filename)
예제 #54
0
class Game:
    def __init__(self):
        # current stat of game
        self.stat = 'menu'
        # init pygame
        pygame.mixer.pre_init(44100, 16, 2, 1024*4)
        pygame.init()
        pygame.display.set_caption("FUNNY TETRIS")
        self.init()
        try:
            self.screen = pygame.display.set_mode((640, 480), 
                    HWSURFACE | SRCALPHA, 32)
        except:
            self.screen = pygame.display.set_mode((640, 480), 
                    SRCALPHA, 32)
        try:
            pygame.display.set_icon(pygame.image.load(
                util.file_path("icon.png")).convert_alpha())
        except:
            # some platfom do not allow change icon after shown
            pass
        # init sub modules
        self.menu = Menu(self.screen)   # menu show start menu
        self.main = Main(self.screen)   # main is the real tetris

    def init(self):
        util.init()
        sound.load()

    def loop(self):
        clock = pygame.time.Clock()
        while self.stat != 'quit':
            elapse = clock.tick(25)
            if self.stat == 'menu':
                self.stat = self.menu.run(elapse)
            elif self.stat == 'game':
                self.stat = self.main.run(elapse)

            if self.stat.startswith('style'):
                level = int(self.stat.split()[1])
                print "Start game at style", level
                self.main.start(level)
                self.stat = "game"

            pygame.display.update()
        pygame.quit()
예제 #55
0
def Start():
    ObjectContainer.art = R(ART)
    ObjectContainer.title1 = NAME
    DirectoryObject.thumb = R(ICON)
    DirectoryObject.art = R(ART)
    PopupDirectoryObject.thumb = R(ICON)
    PopupDirectoryObject.art = R(ART)

    if not Singleton.acquire():
        log.warn('Unable to acquire plugin instance')

    # Complete logger initialization
    LoggerManager.setup(storage=True)

    # Start plugin
    m = Main()
    m.start()
예제 #56
0
def run():
    cli = CLI()
    (options, args) = cli.parse()

    if options.enable_colors:
        cli.enable_colors()

    try:
        main = Main(cli, options, args)
        if options.print_version:
            main.print_version()
        else:
            main.start()
    except KeyboardInterrupt:
        cli.print_info("\nExecution interrupted by user")
        sys.exit(2)

    sys.exit(0)
예제 #57
0
파일: test_main.py 프로젝트: iver56/it3105
    def test_parse_lines(self):
        num_cols, num_rows, row_segments, col_segments = Main.parse_lines(self.lines)

        self.assertEqual(num_cols, 6)
        self.assertEqual(num_rows, 7)
        self.assertEqual(len(row_segments), 7)
        self.assertEqual(len(col_segments), 6)
        self.assertEqual(len(row_segments[1]), 2)
        self.assertEqual(len(col_segments[2]), 3)
예제 #58
0
def route_app(app):
    app.add_url_rule('/',
                     view_func=Main.as_view('main'),
                     methods=["GET", "POST"])
    app.add_url_rule('/login',
                     view_func=Login.as_view('login'),
                     methods=["GET", "POST"])
    app.add_url_rule('/logout',
                     view_func=Logout.as_view('logout'))
    return app
예제 #59
0
	def getEpisodeTitle(self, fileName):
		
		title = fileName[:fileName.rindex("-")]
		title = title[:title.rindex("-")]
		title = title[:title.rindex("-")]
		
		title = title.replace("\"", "").replace("_", "")
		title = title.strip()
		title = Main.cleanseFileName(title)
		
		return title