Example #1
0
    def __init__(self):
        super(Calculator, self).__init__()
        self.ui = Window()
        self.ui.setup_ui(self)

        self.text_list = []
        self.sign_operation = ''
        self.operation = None
        self.text = ''

        self.ui.zero.clicked.connect(lambda: self.numbers('0'))
        self.ui.one.clicked.connect(lambda: self.numbers('1'))
        self.ui.two.clicked.connect(lambda: self.numbers('2'))
        self.ui.three.clicked.connect(lambda: self.numbers('3'))
        self.ui.four.clicked.connect(lambda: self.numbers('4'))
        self.ui.five.clicked.connect(lambda: self.numbers('5'))
        self.ui.six.clicked.connect(lambda: self.numbers('6'))
        self.ui.seven.clicked.connect(lambda: self.numbers('7'))
        self.ui.eight.clicked.connect(lambda: self.numbers('8'))
        self.ui.nine.clicked.connect(lambda: self.numbers('9'))

        self.ui.addition.clicked.connect(lambda: self.addiction())
        self.ui.subtraction.clicked.connect(lambda: self.subtraction())
        self.ui.multiply.clicked.connect(lambda: self.multiply())
        self.ui.division.clicked.connect(lambda: self.division())
        self.ui.radical.clicked.connect(lambda: self.radical())
        self.ui.power.clicked.connect(lambda: self.power())
        self.ui.factorial.clicked.connect(lambda: self.factorial())

        self.ui.num_sign.clicked.connect(lambda: self.num_sign())
        self.ui.point.clicked.connect(lambda: self.point())
        self.ui.delete_last.clicked.connect(lambda: self.delete_last())
        self.ui.delete_all.clicked.connect(lambda: self.delete_all())
        self.ui.result.clicked.connect(lambda: self.print_result())
Example #2
0
def main():

    #set the node name
    rospy.init_node(NODE.GUI, anonymous=False)

    app = QtGui.QApplication(sys.argv) #gui app init

    #window object
    window = Window(None)
    window.show() #Initialize Window, with disabled objects

    #init rov object
    rov = ROV(window)

    #init a thread passing window object as argument
    try:
        thread.start_new_thread(initAndSend, (window, rov, ))
    except:
        print("Unable to start the commands thread. Exit")
        exit(-1)

    #start the gui app
    n=app.exec_()

    sys.exit(n)
Example #3
0
def main():
    #send ??? to "active" topics
    for i in range(1, 10):
        errors_pub.publish("???")
        messages_pub.publish("???")
        sleep(0.2)
    app = QtGui.QApplication(sys.argv)  #gui app init

    #window object
    window = Window(None)
    window.show()  #Initialize Window, with disabled objects

    #Initialize the ROV
    rov = ROV(window)

    #init a thread passing window and rov as arguments
    try:
        thread.start_new_thread(initAndSend, (
            window,
            rov,
        ))
    except:
        print("Unable to start the commands thread. Exit")
        sys.exit(-1)

    #start the gui app
    n = app.exec_()

    #when it will be closed, kill other processes and exit
    os.kill(int(sys.argv[1]), signal.SIGKILL)
    os.kill(int(sys.argv[2]), signal.SIGKILL)
    sys.exit(n)
Example #4
0
def main():
    app = QtGui.QApplication(sys.argv)  #gui app init

    #window object
    window = Window(None)
    window.show()  #Initialize Window, with disabled objects

    #Initialize the ROV
    rov = ROV(window)

    #init a thread passing window and rov as arguments
    try:
        thread.start_new_thread(initAndSend, (
            window,
            rov,
        ))
    except:
        print("Unable to start the commands thread. Exit")
        sys.exit(-1)

    #start the gui app
    n = app.exec_()

    #when it will be closed, kill other processes and exit
    os.kill(int(sys.argv[1]), signal.SIGKILL)
    os.kill(int(sys.argv[2]), signal.SIGKILL)
    sys.exit(n)
Example #5
0
def main():
    app = QtGui.QApplication(sys.argv)  #gui app init

    #window object
    window = Window(None)
    window.show()  #Initialize Window, with disabled objects

    #init rov object
    rov = ROV(window)

    #init a thread passing window object as argument
    try:
        thread.start_new_thread(initAndSend, (
            window,
            rov,
        ))
    except:
        print("Unable to start the commands thread. Exit")
        exit(-1)

    #start the gui app
    n = app.exec_()

    #when it's closed, send stop signal to the ROV
    rov.sendCommand("SSS")

    exit(n)
Example #6
0
    def __init__(self,
                 look_ahead=4,
                 skip_to_page=0,
                 feats=10,
                 max_q_sz=100,
                 base_url="http://www.xvideos.com/c/{0}/anal-12"):
        # Let's set this up so gathering new videos can happen in the background.
        self.scraped_videos = {}
        gather_args = (look_ahead, skip_to_page, feats, max_q_sz)
        self.gather_process = Thread(target=self.gather,
                                     args=gather_args,
                                     daemon=True)

        self.scr = Scraper(base_url=base_url, pg_n=skip_to_page)
        self.db = Database()
        self.ai = Brain(self)
        self.win = Window(self)

        self.currently_loaded_video_data = {}
        self.feats = feats

        self.q = PriorityQueue(maxsize=max_q_sz)
        self.lock = RLock()

        if "brain.pkl" in os.listdir():
            self.train()
        self.get_next()
Example #7
0
def main():
    game = TicTacToe()
    gui = TicTacToeGui(0, 0, 500, 500, game)
    win = Window(title="Ultimate Tic Tac Toe",
                 flags=["SCALED"],
                 gui_objects=[gui])
    win.start()
Example #8
0
def main():
    # Every Qt application must have one instance of QApplication.
    global APP  # Use global to prevent crashing on exit
    APP = QApplication(sys.argv)
    window = Window(0, 0, 0)

    window.show()

    # Start the Qt event loop. (i.e. make it possible to interact with the gui)
    sys.exit(APP.exec_())
 def __init__(self):
     self.resource_spawn_rate = BASE_CHANCE//20
     self.num_species = 2
     self.num_members = 3
     self.num_resources = 15
     self.user_skill = 0
     self.user_speed = 0
     self.user_strength = 0
     self.user_params()
     self.map_obj = Map(width=self.width,height=self.height)
     self.pos_set = set([(i,j)
                  for i in range(self.height) for j in range(self.width)])
     self.win = Window()
     self.init_map();
Example #10
0
def main():
    # Initializes pygame, window
    pygame.init()
    window = pygame.display.set_mode(
        (globals.SCREEN_WIDTH, globals.SCREEN_HEIGHT))
    input_params = Inputs()
    clock = pygame.time.Clock()
    app = QApplication(sys.argv)
    param_win = Window()
    param_win.show()

    # Polygon to be controlled by arrows
    polygon = Polygon(np.array([800, 500]), 30, 3, 10, (255, 255, 255))
    space = Space(polygon)
    while globals.RUN:
        # Drawing shapes
        space.draw(window)
        # Adding force to main polygon
        if input_params.is_left():
            polygon.add_force(np.array([-globals.KEY_FORCE, 0.]))
        elif input_params.is_right():
            polygon.add_force(np.array([globals.KEY_FORCE, 0.]))
        if input_params.is_up():
            polygon.add_force(np.array([0., -globals.KEY_FORCE]))
        elif input_params.is_down():
            polygon.add_force(np.array([0., globals.KEY_FORCE]))

        # Add shape on left click
        if input_params.mouse_left_click():
            space.add_shape(globals.NEW_SHAPE_TYPE, input_params.mouse_pos,
                            globals.NEW_SHAPE_RADIUS, globals.NEW_SHAPE_MASS,
                            globals.NEW_SHAPE_DEGREE)
        # Remove shape on right click
        if input_params.mouse_right_click():
            space.remove_shape(input_params.mouse_pos)

        if input_params.is_clear():
            space.shapes = []

        clock.tick(globals.FPS)
        elapsed_time = clock.get_time()
        # Update shapes in space class for movement, rotarion...
        space.update(window, elapsed_time)
        # Check for mouse of keyboard click
        input_params.update()
        pygame.display.update()
        pygame.display.set_caption(str(clock.get_fps()))

    sys.exit(app.exec_())
Example #11
0
 def wydrukuj(self):
     poz_lista = [
         'Wykaz narzędzi ' + self.pozycja,
         "SELECT * FROM '" + self.pozycja + "'",
         'Baza nie zawiera żadnych pozycji. Plik nie zostanie zapisany.',
     ]
     from gui import Window
     if self.pozycja != 'Brak':
         Window.export(self, poz_lista)
         self.parent.statusBar().showMessage("Wyeksportowano do pliku",
                                             10000)
     else:
         QMessageBox.critical(self, 'Wybierz pozycję',
                              'Nie wybrano żadnej pozycji!', QMessageBox.Ok,
                              QMessageBox.Ok)
Example #12
0
    def __init__(self):
        # GUI basic setup stuff
        super().__init__()
        self.ui = Window()
        self.ui.setupUi(self)
        self.show()

        # Multithreading setup
        self.threadpool = QThreadPool()
        self.threadpool.setMaxThreadCount(int(self.threadpool.maxThreadCount()*0.75))
        print("Multithreading with maximum %d threads" % int(self.threadpool.maxThreadCount()*0.75))

        # Set up directory structure
        self.directories = [
            [self.ui.g_f_gps, "gps"],
            [self.ui.g_f_lms_front, "lms_front"],
            [self.ui.g_f_models, "Models"],
            [self.ui.g_f_stereo, "stereo"],
            [self.ui.g_f_left, "stereo/left"],
            [self.ui.g_f_centre, "stereo/centre"],
            [self.ui.g_f_right, "stereo/right"],
            [self.ui.g_f_lmsTime, "lms_front.timestamps"],
            [self.ui.g_f_stereoTime, "stereo.timestamps"]
        ]

        # GUI connections
        self.ui.browseButton.clicked.connect(self.browse_folder)
        self.ui.folderLine.returnPressed.connect(self.manual_line_change)
Example #13
0
def main():
    try:
        import mrx
    except ImportError:
        print(
            "Failed to load Mr. X AI.  Make sure it is in this directory and named 'mrx.py'"
        )
        exit(1)
    try:
        import detectives
    except ImportError:
        print(
            "Failed to load the detective AI.  Make sure it is in this directory and named 'detectives.py'"
        )
        exit(1)
    the_game = Game(mrx, detectives)
    win = Window(the_game)

    win.mainloop()
Example #14
0
def main():
	"""Main function"""
	# Extract arguments or get random SMILES
	smiles = None
	informalName = None
	ex = get_example(None if len(sys.argv) < 2 else sys.argv[1])
	if not ex:
		smiles = sys.argv[1]
		print "\n>>> Using input `%s` as SMILES.\n" % smiles
	else:
		informalName = ex[1]
		smiles = ex[2]
		print "\n>>> Using %s per argument.\n" % informalName

	# Init GUI.
	win = Window('Chemical Structure Diagram Generation (WIP)')

	# Set globals.
	Globals.drawable = win.drawable
	Globals.debugText = win.debugText
	Globals.window = win
	Globals.ringGroups = None
	Globals.molecule = None

	# Set callbacks.
	win.drawCallback = gui_draw_callback
	win.smilesCallback = gui_smiles_text_callback

	# Process initial data.
	parse_smiles_text(smiles, informalName)

	try:
		# Run GUI.
		win.run()
	except KeyboardInterrupt:
		print ""	
Example #15
0
 def run(self):
     window = Window(theme="black")
     window.init(self.container, self._chatReceiver.updateCoords, self.pause, self.refreshing, self._speaker)
     screen_reader_thread = Thread(target=self.run_loop, args=(window.refresh,), daemon=True)
     voice_thread = Thread(target=self._speaker.loop, daemon=True)
     voice_thread.start()
     screen_reader_thread.start()
     window.mainloop()
     self.terminate.set()
     screen_reader_thread.join()
     self.container.saveConfig()
Example #16
0
def robot():
    '''
    # 简单机器人实现
    '''
    qq = SmartQQ()
    w = Window(qq)
    qq.login() # 登录验证
    slf = qq.get_self_info() # 获取个人信息,主要是获取gid,发送信息会用到。
    friends = qq.get_friends_info() # 获取好友列表
    groups = qq.get_group_list() # 获取群列表
    onli = qq.get_online_buddies2() # 获取在线好友
    rev = qq.get_recent_list2() # 获取最近列表
    img = qq.get_self_img()  # 获取个人头像

    w.show_self_info(img=img, data=slf) # 显示个人信息

    gui.groups = groups
    gui.friends = friends

    # 循环主题
    def recv_func():
        while 1:
            get_msg = qq.get_chat_msg()
            print("get_msg %s" % get_msg)
            if get_msg != None:
                send_msg = "我不明白你的意思."
                if get_msg["poll_type"] == "group_message":
                    w.group_msg_handle(get_msg["from_uin"], get_msg["send_uin"], get_msg["content"])
                    if get_msg["content"].find("@"+qq.qqname) >= 0 and gui.auto_send_name['group'] != None and \
                                    get_msg["from_uin"] == groups[gui.auto_send_name['group']]['gid']:
                        if get_msg["content"].find("自动回复") >= 0:
                            send_msg = messge_text.messge_re[random.randint(0, 53)]
                        qq.send_qun_msg(groups[gui.auto_send_name['group']]['gid'], send_msg)
                        print("机器人回复 : %s" % send_msg)
                if get_msg["poll_type"] == "message" :
                    w.friend_msg_handle(get_msg["from_uin"], get_msg["content"])
                    if gui.auto_send_name['friend'] != None and get_msg["from_uin"] == friends[gui.auto_send_name['friend']]['uin']:
                        if get_msg["content"].find("自动回复") >= 0:
                            send_msg = messge_text.messge_re[random.randint(0, 53)]
                            qq.send_buddy_msg(friends[gui.auto_send_name['friend']]['uin'], send_msg)
                        print("机器人回复 : %s" % send_msg)
                        w.friend_msg_handle(get_msg["from_uin"], send_msg,True)

            time.sleep(1)

    t = threading.Thread(target=recv_func)
    t.start()

    w.run()
Example #17
0
    def __init__(self, look_ahead=4, skip_to_page=0, feats=10, max_q_sz=100,
                 base_url="http://www.xvideos.com/c/{0}/anal-12"):
        # Let's set this up so gathering new videos can happen in the background.
        self.scraped_videos = {}
        gather_args = (look_ahead, skip_to_page, feats, max_q_sz)
        self.gather_process = Thread(target = self.gather,
                                     args   = gather_args,
                                     daemon = True)

        self.scr = Scraper(base_url=base_url, pg_n=skip_to_page)
        self.db  = Database()
        self.ai  = Brain(self)
        self.win = Window(self)

        self.currently_loaded_video_data = {}
        self.feats = feats

        self.q = PriorityQueue(maxsize=max_q_sz)
        self.lock = RLock()

        if "brain.pkl" in os.listdir():
            self.train()
        self.get_next()
Example #18
0
def main():
    """Main function"""
    # Extract arguments or get random SMILES
    smiles = None
    informalName = None
    ex = get_example(None if len(sys.argv) < 2 else sys.argv[1])
    if not ex:
        smiles = sys.argv[1]
        print "\n>>> Using input `%s` as SMILES.\n" % smiles
    else:
        informalName = ex[1]
        smiles = ex[2]
        print "\n>>> Using %s per argument.\n" % informalName

    # Init GUI.
    win = Window('Chemical Structure Diagram Generation (WIP)')

    # Set globals.
    Globals.drawable = win.drawable
    Globals.debugText = win.debugText
    Globals.window = win
    Globals.ringGroups = None
    Globals.molecule = None

    # Set callbacks.
    win.drawCallback = gui_draw_callback
    win.smilesCallback = gui_smiles_text_callback

    # Process initial data.
    parse_smiles_text(smiles, informalName)

    try:
        # Run GUI.
        win.run()
    except KeyboardInterrupt:
        print ""
Example #19
0
#!/usr/bin/env python3
from chess import Chessboard
from gui import Window
from gl_data import geometries
from PyQt4.QtGui import QApplication
import sys

if __name__ == "__main__":
    board = Chessboard()
    app = QApplication(sys.argv)
    window = Window(geometries, board)
    window.show()
    sys.exit(app.exec_())
Example #20
0
from gui import Window
from PyQt4 import QtGui
import sys

app = QtGui.QApplication(sys.argv)

#initialize the main window
window = Window(app)
Window.w = window

#make sure wait message is set before connecting procedure starts
app.processEvents()

#because initializing client will take some time
window.initClient(True)

sys.exit(app.exec_())
Example #21
0
    parser.add_argument('--version', '-v', action='version',
                    version='%(prog)s ' + prog_version) 
    
    options = Options(parser.parse_args())
    
    if options.debug_mode:
        print('debug mode   =', options.debug_mode)
        print('one_running  =', options.one_running)
        print('elapsed_time =', options.elapsed_time)
        print('pictures     =', options.pictures)
    
    app = QtGui.QApplication(sys.argv)
    
    if not QtGui.QSystemTrayIcon.isSystemTrayAvailable():
        QtGui.QMessageBox.critical(None, "lkwpchanger",
                                   "The application couldn't start.")
        sys.exit(1)
    
    QtGui.QApplication.setQuitOnLastWindowClosed(False)
    
    pictures = Pictures(options)
    window = Window(pictures)
    timer = TimerThread(args=(window))
    if options.one_running:
        window.change_background()
    else:
        timer.start()
    
    sys.exit(app.exec_())  

Example #22
0
from gui import Window
from game import Game


if __name__ == "__main__":
    game = Game()
    window = Window(game)
    window.start()
Example #23
0
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QTranslator, QLocale, QLibraryInfo
from gui import Window

if __name__ == '__main__':
    app = QApplication(sys.argv)

    traductor = QTranslator()
    traductor.load("qtbase_" + QLocale.system().name(),
                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(traductor)

    win = Window()
    win.parent = app

    win.show()

    sys.exit(app.exec_())
Example #24
0
parser.add_option(
    '--random',
    metavar='NUMBER',
    type=int,
    help='Make it so you answer a question incorrectly every X questions.',
    default=0)

(options, args) = parser.parse_args()

if __name__ == '__main__':
    try:
        from gui import Window

        app = QApplication(sys.argv)

        win = Window(show_stats=not options.no_stats, close=options.close)

        if not options.gui_frameless:
            win.show()
        if options.username != '':
            win.ui.emailTassomai.setText(options.username)
        if options.password != '':
            win.ui.passwordTassomai.setText(options.password)
        if options.delay != 'none':
            win.ui.delay.setChecked(True)
            if options.delay in ['quiz', 'question']:
                win.ui.whenDelay.setCurrentText(options.delay)
            if options.delay_amount != "0":
                if ',' in options.delay_amount:
                    try:
                        v1, v2 = tuple(
Example #25
0
def main():
    app = QApplication([])
    win = Window()
    win.show()

    sys.exit(app.exec())
Example #26
0
state = State(psi * target_norm / np.linalg.norm(psi)).to_basis(energy)


def evolve(time):
    """Evolve the current state forward in time by given duration."""
    state_multiplier = np.exp((-1j / h_bar * time) * energy.eigenvalues)
    state.vector *= state_multiplier


# Graphics
plot = Plot(state,
            basis=position,
            potential=potential,
            potential_scale=potential_scale)

main_window = Window('Quantum Simulation')
main_window.add_widget(plot)
main_window.add_widget(simulation_speed)
main_window.add_widget(potential_scale)

measurement_panel = QWidget()
measurement_layout = QHBoxLayout(measurement_panel)
measurement_layout.addWidget(ObservableWidget(position, state, plot))
measurement_layout.addWidget(ObservableWidget(momentum, state, plot))
measurement_layout.addWidget(ObservableWidget(energy, state, plot))

main_window.add_widget(measurement_panel)


# Animation
def update_animation():
Example #27
0
create_graph(hexyne)
create_graph(isohex)

surface = ImageSurface(FORMAT_ARGB32, 500, 500)
ctx = Context(surface)

# Background
height = 500
pat = SolidPattern(1.0, 1.0, 1.0, 0.9)
ctx.rectangle (0,0, 500, 500)
ctx.set_source (pat)
ctx.fill ()
"""


win = Window("Testing")

win.setText(hexane)
win.run()




def draw_line(x1, y1, x2, y2):
	ctx.new_path()
	ctx.set_source_rgb(0.0, 0.0, 0.0)
	ctx.move_to(x1, y1)
	ctx.line_to(x2, y2)
	ctx.close_path()
	ctx.stroke()
Example #28
0
class Mediator:
    """Handles communication between objects."""
    def __init__(self, look_ahead=4, skip_to_page=0, feats=10, max_q_sz=100,
                 base_url="http://www.xvideos.com/c/{0}/anal-12"):
        # Let's set this up so gathering new videos can happen in the background.
        self.scraped_videos = {}
        gather_args = (look_ahead, skip_to_page, feats, max_q_sz)
        self.gather_process = Thread(target = self.gather,
                                     args   = gather_args,
                                     daemon = True)

        self.scr = Scraper(base_url=base_url, pg_n=skip_to_page)
        self.db  = Database()
        self.ai  = Brain(self)
        self.win = Window(self)

        self.currently_loaded_video_data = {}
        self.feats = feats

        self.q = PriorityQueue(maxsize=max_q_sz)
        self.lock = RLock()

        if "brain.pkl" in os.listdir():
            self.train()
        self.get_next()

    def start_gathering(self):
        self.gather_process.start()

    def get_next(self):
        """Determine which video should be selected, then update window."""
        # Get the video likely to have the best rating
        if self.q.qsize():
            self.lock.acquire()
            to_show_url = self.q.get()
            self.lock.release()
            scraped_data, preview_pic_url, guessed_rating = self.scraped_videos[to_show_url]
            self.currently_loaded_video_data = scraped_data
            pic1, pic2, pic3 = self.scr.load_pics(preview_pic_url) 
            self.win.update_images(pic1, pic2, pic3)
            url = scraped_data["url"]
            print("\n")
            print("\ttitle:\t", scraped_data["title"])
            print("\tlength:\t", scraped_data["duration"])
            print("\tguessed rating:\t", guessed_rating)
            print("\ttags:\t", "  ".join(scraped_data["tags"]))
            print()
        else:
            print("Error: still gathering videos.")

    def gather(self, look_ahead, skip_to_page, feats, max_q_sz):
        """ Add videos to the priority queue independently
          of rating and loading videos. """
        while True:
            if self.q.qsize() < max_q_sz:
                for i in range(look_ahead):
                    self.scr.next()
                    if self.db.has_video(self.scr.cur_vid):
                        # make sure we only work on unrated videos
                        print(".", end="")
                        continue
                    scraped_data = self.scr.scrape_video()
                    pred_rating  = self.ai.predict(scraped_data)
                    self.scraped_videos[self.scr.cur_vid] = (scraped_data,
                                                            self.scr.cur_pic,
                                                            pred_rating)
                    self.lock.acquire()
                    self.q.put(self.scr.cur_vid, -pred_rating)
                    self.lock.release()
                    print(":", end="")

    def save(self, rating):
        """Save the data scraped from the current video then get next video."""
        self.currently_loaded_video_data["loved"] = rating
        sys.stdout.flush()
        self.db.save(self.currently_loaded_video_data)
        self.get_next()
        
    def open_vid(self):
        webbrowser.open(self.scr.cur_vid)

    def train(self):
        tags, ratings, tag_to_vec = self.db.vectorize_tags(self.feats)
        self.ai.train(tags, ratings, tag_to_vec)

    def close_db(self):
        """When a window closes, disconnect from a database."""
        self.db.cnx.close()
Example #29
0

def submit():
    payload['end'] = datetime.now(tz=timezone.utc).isoformat().replace(
        "+00:00", "Z")
    payload['description'] = ticket.get()
    time_entry_endpoint = endpoint_config.default_endpoint + f"workspaces/{workspaceId}/time-entries"
    requests.post(time_entry_endpoint,
                  headers=endpoint_config.header,
                  json=payload)
    clear_data()
    toggle_client_selection_on()
    button_frame.lift()


main_window = Window(f'{user.name} Ticket Tracker', '750x425')

main_frame = WindowFrame(main_window, borderwidth=5)
main_frame.grid(row=0, rowspan=3, column=0, columnspan=3)

button_frame = ButtonFrame(main_frame, borderwidth=5, relief="sunken")
button_frame.grid(row=0, column=0, padx=10, pady=10, sticky=tk.NSEW)

client_frame = ProjectButtons(button_frame, borderwidth=5)
client_frame.grid(row=0, column=0, sticky=tk.NSEW)

client_buttons = [
    ttk.Button(client_frame,
               text=client,
               command=lambda client=client: select_client(client))
    for client in clients.clients
Example #30
0
class MediaPlayer:
    def __init__(self):

        self.DefineFunctionArgList()

        self.service = pydbus.SystemBus().get('org.bluez', '/')
        self.Update_obj_list()

        self.player_connected = False
        self.TerminateFlag = False

        self.obj_list_updater_thread = Thread(target=self.ObjListUpdater)
        self.track_info_updater_thread = Thread(target=self.TrackInfoUpdater)

        self.obj_list_updater_thread.start()
        self.track_info_updater_thread.start()

        self.Start()

    def ObjListUpdater(self):
        self.system_bus = pydbus.SystemBus()
        self.system_bus.subscribe(sender='org.bluez',
                                  signal='PropertiesChanged',
                                  signal_fired=self.Update_obj_list)

        loop = MainLoop()
        timeout_add(100, self.checkTerminate, loop)
        loop.run()

    def Update_obj_list(self, *args):
        self.obj_list = self.service.GetManagedObjects()

    def TrackInfoUpdater(self):
        while self.TerminateFlag is False:
            try:
                self.track_info = self.media_player.Get(
                    'org.bluez.MediaPlayer1', 'Track')
                self.track_info['Position'] = self.media_player.Get(
                    'org.bluez.MediaPlayer1', 'Position')
                self.track_info['Status'] = self.media_player.Get(
                    'org.bluez.MediaPlayer1', 'Status')
            except:
                self.track_info = {
                    'Title': '',
                    'Album': '',
                    'Artist': '',
                    'Genre': '',
                    'Duration': 0,
                    'Position': 0,
                    'Status': 'stopped'
                }

            sleep(0.2)

    def GetTrackInfo(self):
        return self.track_info

    def Start(self):
        self.ConnectMediaPlayer()

    def ConnectMediaPlayer(self):
        while self.player_connected is not True:
            for obj_path in self.obj_list.keys():
                if "player" in obj_path:
                    self.player_path = obj_path
                    self.device_path = self.obj_list[
                        self.player_path]['org.bluez.MediaPlayer1']['Device']
                    self.device_name = self.obj_list[
                        self.device_path]['org.bluez.Device1']['Alias']
                    self.player_connected = self.obj_list[self.device_path][
                        'org.bluez.MediaControl1']['Connected']
                    break
            sleep(0.2)

        self.media_player = pydbus.SystemBus().get('org.bluez',
                                                   self.player_path)
        self.CreateWindow()

    def CheckConnection(self):
        if self.player_path not in self.obj_list and \
        self.obj_list[self.device_path]['org.bluez.MediaControl1']['Connected'] is False:
            self.player_connected = False
            self.root.destroy()
            self.Start()

    def isPlayerConnected(self):
        return self.player_connected

    def Play(self):
        self.media_player.Play()

    def Pause(self):
        self.media_player.Pause()

    def Next(self):
        self.media_player.Next()

    def Previous(self):
        self.media_player.Previous()

    def Terminate(self):
        self.TerminateFlag = True

    def checkTerminate(self, loop):
        if self.TerminateFlag is True:
            loop.quit()
        else:
            timeout_add(100, self.checkTerminate, loop)

    def DefineFunctionArgList(self):
        self.func_list = {
            'Terminate': self.Terminate,
            'Play': self.Play,
            'Pause': self.Pause,
            'Next': self.Next,
            'Previous': self.Previous,
            'isPlayerConnected': self.isPlayerConnected,
            'CheckConnection': self.CheckConnection,
            'GetTrackInfo': self.GetTrackInfo
        }

    def CreateWindow(self):
        self.root = Window(self.func_list)
        self.root.run()
Example #31
0
def graphical_version(flac_file, output):
    app = QApplication(sys.argv)
    window = Window(flac_file, output)
    sys.exit(app.exec_())
class Simulator:
    def __init__(self):
        self.resource_spawn_rate = BASE_CHANCE//20
        self.num_species = 2
        self.num_members = 3
        self.num_resources = 15
        self.user_skill = 0
        self.user_speed = 0
        self.user_strength = 0
        self.user_params()
        self.map_obj = Map(width=self.width,height=self.height)
        self.pos_set = set([(i,j)
                     for i in range(self.height) for j in range(self.width)])
        self.win = Window()
        self.init_map();

    def create_species(self):
        '''Takes in user specifications for strength/speed of species 
             they are rooting for on the board'''
        print("You will be species 0.")
        self.user_speed = float(input("Enter speed of your species (0-3): ")
                                or uniform(0,3))
        self.user_strength = float(input(
                                "Enter strength of your species (0-10): ") 
                                or uniform(0,10))

    def user_params(self):
        '''Initializes simulation data with user preferences.'''
        self.num_species = int(input(
                            "Enter number of species on board (Default: 3): ") 
                                or 3)
        self.num_members = int(input(
                        "Enter number of members per species (Default: 2): ") 
                                or 2)
        self.num_resources = int(input(
                    "Enter number of resources on the board (Default: 15) : ") 
                                or 15)
        if input("Would you like to create a species? ") == 'Y':
            self.create_species() 
        else:
            self.user_speed = uniform(0,3)
            self.user_strength = uniform(0,10)
        dimension = int(math.ceil(math.sqrt(
                    self.num_resources + self.num_species 
                    * self.num_members * 1.5)))
        self.width = 0
        self.height = 0
        print(f"Minimum Number of Spaces: {dimension**2}")
        while(self.width*self.height < dimension**2):
            self.width = int(input("Enter width of the board") or dimension)
            self.height = int(input("Enter height of the board") or dimension)
            if self.width*self.height < dimension**2:
                print("Not enough space on board for specified items!")

    def init_map(self):
        '''Creates members of each species, with 
           random attributes characteristic to each species.
            Places members and resources on the map.'''
        for i in range(self.num_members):
            #Creates members of species user is rooting for.
            skill= Skill(strength=self.user_strength, speed=self.user_speed)
            m = Member(
                draw_fn=self.draw,
                map_obj=self.map_obj,
                skill=skill,
                species_id=0,
                reproduction_chance=BASE_CHANCE//10)
            pos = choice(list(self.pos_set))
            self.pos_set.remove(pos)
            self.map_obj.add(m, pos)
        for i in range(1, self.num_species):
            for j in range(self.num_members):
                skill=Skill(strength=uniform(0,10), speed=uniform(0,3))
                m = Member(
                    draw_fn=self.draw,
                    map_obj=self.map_obj,
                    skill=skill,
                    species_id=i,
                    reproduction_chance=BASE_CHANCE//10)
                pos = choice(list(self.pos_set))
                self.pos_set.remove(pos)
                self.map_obj.add(m, pos)
        for _ in range(self.num_resources):
            r = Resource(
                strength=1+random.random(),
                speed=1+random.random())
            #Add extra types of skills to the resource at random
            if random.random() > 0.75:
                r.add_to_bag()
            pos = choice(list(self.pos_set))
            self.pos_set.remove(pos)
            self.map_obj.add(r, pos)

    def members(self):
        return [self.map_obj.at(pos) for pos in self.map_obj.members.values()]

    def _random_resource_inclusion_thread(self):
        '''Adds resources with random attributes to the board at a rate
        determined by the resource spawn rate and simulation speed'''
        while True:
            with self.map_obj.lock:
                if self.map_obj.is_game_over:
                    break
                r = Resource(
                    strength=1+random.random(),
                    speed=1+random.random())
                if random.random() > 0.75:
                    r.add_to_bag()
                pos = choice(list(self.map_obj.empty_pos))
                self.map_obj.add(r, pos)
            sleep(uniform(
                0, BASE_CHANCE/self.resource_spawn_rate)/SIM_SPEED_MULT)

    def _ctrlc_handler(self, signal_received, frame):
        '''Allows simulation to quit cleanly if interrupted before it ends'''
        with self.map_obj.lock:
            self.map_obj.game_over = True

    def print_end_state(self):
        '''Prints the winning species/ result of the simulation.
        The simulation is over if there are 1 or 0 species left on the board.'''
        counts = list(self.map_obj.species_counts.items())
        if len(counts) == 1:
            print(f'Species {counts[0][0]} wins!')
        elif len(counts) == 0:
            print(f'All species dead.')

    def draw(self):
        '''renders map object for GUI.'''
        self.win.draw(self.map_obj)

    def start(self):
        '''Starts threads for members, and resource inclusion thread. Renders
        GUI until the simulation is over.'''
        self.win.start()
        signal(SIGINT, self._ctrlc_handler)
        for m in self.members():
            m._thread.start()
        Thread(target=self._random_resource_inclusion_thread).start()
        while True:
            with self.map_obj.lock:
                if self.map_obj.is_game_over:
                    break
                self.draw()
            sleep(.2)
        self.win.stop()
        self.print_end_state()
Example #33
0
#!/usr/bin/python

import sys

from PyQt5.QtWidgets import QApplication
from gui import Window

if __name__ == "__main__":

    app = QApplication(sys.argv)

    win = Window()

    w, h = 480, 640
    win.setMinimumSize(w, h)

    win.show()

    sys.exit(app.exec_())
Example #34
0
class Mediator:
    """Handles communication between objects."""
    def __init__(self,
                 look_ahead=4,
                 skip_to_page=0,
                 feats=10,
                 max_q_sz=100,
                 base_url="http://www.xvideos.com/c/{0}/anal-12"):
        # Let's set this up so gathering new videos can happen in the background.
        self.scraped_videos = {}
        gather_args = (look_ahead, skip_to_page, feats, max_q_sz)
        self.gather_process = Thread(target=self.gather,
                                     args=gather_args,
                                     daemon=True)

        self.scr = Scraper(base_url=base_url, pg_n=skip_to_page)
        self.db = Database()
        self.ai = Brain(self)
        self.win = Window(self)

        self.currently_loaded_video_data = {}
        self.feats = feats

        self.q = PriorityQueue(maxsize=max_q_sz)
        self.lock = RLock()

        if "brain.pkl" in os.listdir():
            self.train()
        self.get_next()

    def start_gathering(self):
        self.gather_process.start()

    def get_next(self):
        """Determine which video should be selected, then update window."""
        # Get the video likely to have the best rating
        if self.q.qsize():
            self.lock.acquire()
            to_show_url = self.q.get()
            self.lock.release()
            scraped_data, preview_pic_url, guessed_rating = self.scraped_videos[
                to_show_url]
            self.currently_loaded_video_data = scraped_data
            pic1, pic2, pic3 = self.scr.load_pics(preview_pic_url)
            self.win.update_images(pic1, pic2, pic3)
            url = scraped_data["url"]
            print("\n")
            print("\ttitle:\t", scraped_data["title"])
            print("\tlength:\t", scraped_data["duration"])
            print("\tguessed rating:\t", guessed_rating)
            print("\ttags:\t", "  ".join(scraped_data["tags"]))
            print()
        else:
            print("Error: still gathering videos.")

    def gather(self, look_ahead, skip_to_page, feats, max_q_sz):
        """ Add videos to the priority queue independently
          of rating and loading videos. """
        while True:
            if self.q.qsize() < max_q_sz:
                for i in range(look_ahead):
                    self.scr.next()
                    if self.db.has_video(self.scr.cur_vid):
                        # make sure we only work on unrated videos
                        print(".", end="")
                        continue
                    scraped_data = self.scr.scrape_video()
                    pred_rating = self.ai.predict(scraped_data)
                    self.scraped_videos[self.scr.cur_vid] = (scraped_data,
                                                             self.scr.cur_pic,
                                                             pred_rating)
                    self.lock.acquire()
                    self.q.put(self.scr.cur_vid, -pred_rating)
                    self.lock.release()
                    print(":", end="")

    def save(self, rating):
        """Save the data scraped from the current video then get next video."""
        self.currently_loaded_video_data["loved"] = rating
        sys.stdout.flush()
        self.db.save(self.currently_loaded_video_data)
        self.get_next()

    def open_vid(self):
        webbrowser.open(self.scr.cur_vid)

    def train(self):
        tags, ratings, tag_to_vec = self.db.vectorize_tags(self.feats)
        self.ai.train(tags, ratings, tag_to_vec)

    def close_db(self):
        """When a window closes, disconnect from a database."""
        self.db.cnx.close()
Example #35
0
                    data = s.recv(32768)
                    if len(data) > 0:
                        client_socket.send(data)
                    else:
                        break
                s.close()
            except socket.error as sock_err:
                print(os.strerror(sock_err.errno))
                print("Connection refused!")
                if s is not None:
                    s.close()

    def _is_filtered(self, webserver):
        for cat in self.webservers_categories:
            if cat[1]:
                for f_ws in cat[2]:
                    if f_ws == webserver[-len(f_ws):]:
                        return True
        return False

    def on_exit(self):
        if self.serverSocket is not None:
            self.serverSocket.close()


if __name__ == '__main__':
    proxy = Proxy()
    proxy.wait_clients()
    window = Window(proxy)
    window.show()
Example #36
0
 def CreateWindow(self):
     self.root = Window(self.func_list)
     self.root.run()