def Reset(self):
     self.StopTcpServer()
     self.StartTcpServer()
     self.SendVideo = Thread(target=self.sendvideo)
     self.ReadData = Thread(target=self.readdata)
     self.SendVideo.start()
     self.ReadData.start()
Exemple #2
0
    def on_pushButton(self):
        if self.label.text() == "Server Off":
            self.label.setText("Server On")
            self.Button_Server.setText("Off")
            self.TCP_Server.tcp_Flag = True
            print("Open TCP")
            self.TCP_Server.StartTcpServer()
            self.SendVideo = Thread(target=self.TCP_Server.sendvideo)
            self.ReadData = Thread(target=self.TCP_Server.readdata)
            self.power = Thread(target=self.TCP_Server.Power)
            self.SendVideo.start()
            self.ReadData.start()
            self.power.start()

        elif self.label.text() == 'Server On':
            self.label.setText("Server Off")
            self.Button_Server.setText("On")
            self.TCP_Server.tcp_Flag = False
            try:
                stop_thread(self.ReadData)
                stop_thread(self.power)
                stop_thread(self.SendVideo)
            except:
                pass
            self.TCP_Server.StopTcpServer()
            print("Close TCP")
Exemple #3
0
    def __init__(self):
        self.user_ui = True
        self.start_tcp = False
        self.TCP_Server = Server()
        self.parseOpt()
        if self.user_ui:
            self.app = QApplication(sys.argv)
            super(mywindow, self).__init__()
            self.setupUi(self)
            self.m_DragPosition = self.pos()
            self.setWindowFlags(Qt.FramelessWindowHint
                                | Qt.WindowStaysOnTopHint)
            self.setMouseTracking(True)
            self.Button_Server.setText("On")
            self.on_pushButton()
            self.Button_Server.clicked.connect(self.on_pushButton)
            self.pushButton_Close.clicked.connect(self.close)
            self.pushButton_Min.clicked.connect(self.windowMinimumed)

        if self.start_tcp:
            self.TCP_Server.StartTcpServer()
            self.ReadData = Thread(target=self.TCP_Server.readdata)
            self.SendVideo = Thread(target=self.TCP_Server.sendvideo)
            self.power = Thread(target=self.TCP_Server.Power)
            self.SendVideo.start()
            self.ReadData.start()
            self.power.start()
            if self.user_ui:
                self.label.setText("Server On")
                self.Button_Server.setText("Off")
 def __init__(self):
     self.TCP_Server = Server()
     self.TCP_Server.StartTcpServer()
     self.ReadData = Thread(target=self.TCP_Server.readdata)
     self.SendVideo = Thread(target=self.TCP_Server.sendvideo)
     self.power = Thread(target=self.TCP_Server.Power)
     self.SendVideo.start()
     self.ReadData.start()
     self.power.start()
Exemple #5
0
def part2(instructions):
    """ Get the amount of times thread1 send a value by the time we reach a deadlock """
    thread0 = Thread(0)
    thread1 = Thread(1)

    while True:
        val1 = thread0.run(instructions)
        if val1 and val1 != 'wait':
            thread1.add_queue(val1)

        val2 = thread1.run(instructions)
        if val2 and val2 != 'wait':
            thread0.add_queue(val2)

        if val1 == val2 == 'wait':
            return len(thread1.send)
def word_frequency_detection(word_to_detect):
    TOTAL_WORD_COUNT = 0  #Count the number of appreance in the text
    voice_data_queue = Queue()
    #Acquire voice clip for speech detection
    voice_capture_thread = Thread(target=subrecord.voice_capture, args=[math.floor(RECORD_KHZ *1000), INPUT_BUF_SIZE, voice_data_queue])
    voice_capture_thread.start()


    while True:
        speech.wav = voice_data_queue.get()
        WAV_FILE = path.join(path.dirname(path.realpath(__file__)), "speech.wav")

        r = sr.Recognizer()

        with sr.WavFile(WAV_FILE) as source:
            audio = r.record(source)
        try:
            result_text = r.recognize_google(audio) #result_text is a string
            print(result_text)
            #convert string to list 
            result_list = result_text.split()
            #word frequency counting
            for word in result_list:
                if word == word_to_detect:
                    TOTAL_WORD_COUNT += 1
            print("Has appreared %d times", TOTAL_WORD_COUNT) 
        except sr.UnknownValueError:
            print("Google Speech Reconition could not uderstand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition service; {0}".format(e))
    def parseOpt(self):
        self.opts, self.args = getopt.getopt(sys.argv[1:], "tn")
        for o, a in self.opts:
            if o in ('-t'):
                print("Open TCP")
                self.TCP_Server.StartTcpServer()
                self.ReadData = Thread(target=self.TCP_Server.readdata)
                self.SendVideo = Thread(target=self.TCP_Server.sendvideo)
                self.power = Thread(target=self.TCP_Server.Power)
                self.SendVideo.start()
                self.ReadData.start()
                self.power.start()

                self.label.setText("Server On")
                self.Button_Server.setText("Off")
            elif o in ('-n'):
                self.user_ui = False
Exemple #8
0
    def __init__(self, num_threads):
        assert(num_threads > 0)
        self.thread_pool = []
        self.num_threads = num_threads

        # Create threads and add to the thread pool
        for i in range(num_threads):
            thread = Thread.Thread(i)
            self.add_thread(thread)
Exemple #9
0
    def on_pushButton_5_clicked(self):
        self.thread = Thread.Thread(self.dataset, self.centerpts)

        self.pushButton_5.setEnabled(False)
        self.axes1 = self.figure1.add_subplot()
        self.axes1.clear()
        self.thread.signal.connect(self.Update)
        self.thread.finish.connect(self.buttonEnable)
        self.thread.start()
Exemple #10
0
 def add_thread(self, thread_path, thread_name=None):
     """
     Add a Messenger thread representing a conversation
     if thread_name is provided, label the thread as thread_name
     """
     new_thread = Thread(thread_path)
     if thread_name:
         self.threads[thread_name] = new_thread
     else:
         self.threads[new_thread.title] = new_thread
Exemple #11
0
 def __init__(self, memory: Memory, params=dict()):
     self.num_threads = int(params["NUM_THREAD"]) if "NUM_THREAD" in params.keys() else NUM_THREADS
     self.num_stages = int(params["NUM_STAGES"]) if "NUM_STAGES" in params.keys() else NUM_STAGES
     self.thread_unit = [Thread(tid,params) for tid in range(0, self.num_threads)]
     self.fetch_unit = [Fetch(tid, memory, params, self.thread_unit[tid]) for tid in range(0, self.num_threads)]  # Create fetch unit
     self.issue_unit = Issue(params)
     self.execute_unit = Execute(params)
     self.connect()
     self.timer = DEFAULT_TIMEOUT
     # Prefetch
     self.prefetch_policy = params["PREFETCH_POLICY"] if "PREFETCH_POLICY" in params.keys() else PREFETCH_POLICY
     self.tid_prefetch_vld = False
     self.tid_prefetch_ptr = 0
     # Verbosity
     self.timer = DEFAULT_TIMEOUT
     # Statistics
     self.last_tick = 0
     self.count_flushed_inst = 0
     self.ipc = 0
     self.total_num_of_mem_access = 0
def main():
    global found
    global fail
    parser = optparse.OptionParser(
        "Usage: -H <HostName> -U <Username> -P <Password")
    parser.add_option(
        "-H",
        dest="thost",
        type="string",
        help="Enter the Host on which you want brute force ssh login")
    parser.add_option(
        "-U",
        dest="username",
        type="string",
        help="Enter the username that on which you want to brute force")
    parser.add_option(
        "-P",
        dest="passfile",
        type="string",
        help="Enter the password file which can be used for bruteforcing attack"
    )
    (options, args) = parser.parse_args()
    if options.thost == None or options.username == None or options.passfile == None:
        print parser.usage
        exit(0)
    thost = options.thost
    username = options.username
    passfile = options.passfile
    f = open(passfile, "r")
    for line in f.readlines():

        if fail > 5:
            print "Too many timeouts"
            exit(0)
        connections_lock.acquire()
        password = line.strip("\n")
        print " The password used in this iteration is %s " % password
        t = Thread(target=connect, args=(thost, username, password, True))
        t.start()
Exemple #13
0
def run():
    try:

        with socekt.socket(socket.AF_INET,socket.SOCK_STREAM)as sock:
            sock.connet((HOST,PORT))
            t=Thread(target=rcvMsg,arga=(sock,))
            t.daemon=True
            t.start()

            while True:
                time.sleep(0.1)
                if GPIO.input(btnOrder)==GPIO.HIGH:
                    sock.send('a'.encode('utf-8'))
                    print('send:주문완료')
                elif GPIO.input(btnCancel)==GPIO.HIGH:
                    sock.send('b'.encode('utf-8'))
                    print('send: 주문 취소')

                time.sleep(0.1)
    except Exception as e:
        print('run Err: %s' % e)
        pass
    def readdata(self):
        try:
            try:
                self.connection1, self.client_address1 = self.server_socket1.accept(
                )
                print("Client connection successful ! ---- SURE?")
            except:
                print("Client connect failed")
            restCmd = ""
            self.server_socket1.close()
            while True:
                try:
                    AllData = restCmd + self.connection1.recv(1024).decode(
                        'utf-8')
                except:
                    if self.tcp_Flag:
                        self.Reset()
                    break
                print('AllData is', AllData)
                if len(AllData) < 5:
                    restCmd = AllData
                    if restCmd == '' and self.tcp_Flag:
                        self.Reset()
                        break
                restCmd = ""
                if AllData == '':
                    break
                else:
                    cmdArray = AllData.split("\n")
                    if (cmdArray[-1] != ""):
                        restCmd = cmdArray[-1]
                        cmdArray = cmdArray[:-1]

                for oneCmd in cmdArray:
                    data = oneCmd.split("#")
                    if data == None:
                        continue
                    elif cmd.CMD_MODE in data:
                        if data[1] == 'one':
                            self.stopMode()
                            self.Mode = 'one'
                        elif data[1] == 'two':
                            self.stopMode()
                            self.Mode = 'two'
                            self.lightRun = Thread(target=self.light.run)
                            self.lightRun.start()
                        elif data[1] == 'three':
                            self.stopMode()
                            self.Mode = 'three'
                            self.ultrasonicRun = threading.Thread(
                                target=self.ultrasonic.run)
                            self.ultrasonicRun.start()
                        elif data[1] == 'four':
                            self.stopMode()
                            self.Mode = 'four'
                            self.infraredRun = threading.Thread(
                                target=self.infrared.run)
                            self.infraredRun.start()

                    elif (cmd.CMD_MOTOR in data) and self.Mode == 'one':
                        print('Data is', data)
                        try:
                            data1 = int(data[1])
                            data2 = int(data[2])
                            data3 = int(data[3])
                            data4 = int(data[4])
                            if data1 == None or data2 == None or data2 == None or data3 == None:
                                continue
                            self.PWM.setMotorModel(data1, data2, data3, data4)
                        except:
                            pass
                    elif cmd.CMD_SERVO in data:
                        try:
                            data1 = data[1]
                            data2 = int(data[2])
                            if data1 == None or data2 == None:
                                continue
                            self.servo.setServoPwm(data1, data2)
                        except:
                            pass

                    elif cmd.CMD_LED in data:
                        try:
                            data1 = int(data[1])
                            data2 = int(data[2])
                            data3 = int(data[3])
                            data4 = int(data[4])
                            if data1 == None or data2 == None or data2 == None or data3 == None:
                                continue
                            self.led.ledIndex(data1, data2, data3, data4)
                        except:
                            pass
                    elif cmd.CMD_LED_MOD in data:
                        self.LedMoD = data[1]
                        if self.LedMoD == '0':
                            try:
                                stop_thread(Led_Mode)
                            except:
                                pass
                            self.led.ledMode(self.LedMoD)
                            time.sleep(0.1)
                            self.led.ledMode(self.LedMoD)
                        else:
                            try:
                                stop_thread(Led_Mode)
                            except:
                                pass
                            time.sleep(0.1)
                            Led_Mode = Thread(target=self.led.ledMode,
                                              args=(data[1], ))
                            Led_Mode.start()
                    elif cmd.CMD_SONIC in data:
                        if data[1] == '1':
                            self.sonic = True
                            self.ultrasonicTimer = threading.Timer(
                                0.5, self.sendUltrasonic)
                            self.ultrasonicTimer.start()
                        else:
                            self.sonic = False
                    elif cmd.CMD_BUZZER in data:
                        try:
                            self.buzzer.run(data[1])
                        except:
                            pass
                    elif cmd.CMD_LIGHT in data:
                        if data[1] == '1':
                            self.Light = True
                            self.lightTimer = threading.Timer(
                                0.3, self.sendLight)
                            self.lightTimer.start()
                        else:
                            self.Light = False
                    elif cmd.CMD_POWER in data:
                        ADC_Power = self.adc.recvADC(2) * 3
                        try:
                            self.send(cmd.CMD_POWER + '#' + str(ADC_Power) +
                                      '\n')
                        except:
                            pass
        except Exception as e:
            print(e)
        self.StopTcpServer()
	train_batches_queue = Queue(maxsize=12)
	#Our numpy batches cuda transferer queue.
	#Once the queue is filled the queue is locked
	#We set maxsize to 3 due to GPU memory size limitations
	cuda_batches_queue = Queue(maxsize=3)


	training_set_generator = InputGen(training_set_list,batches_per_epoch)
	train_thread_killer = thread_killer()
	train_thread_killer.set_tokill(False)
	preprocess_workers = 4


	#We launch 4 threads to do load &amp;&amp; pre-process the input images
	for _ in range(preprocess_workers):
		t = Thread(target=threaded_batches_feeder, \
				   args=(train_thread_killer, train_batches_queue, training_set_generator))
		t.start()
	cuda_transfers_thread_killer = thread_killer()
	cuda_transfers_thread_killer.set_tokill(False)
	cudathread = Thread(target=threaded_cuda_batches, \
				   args=(cuda_transfers_thread_killer, cuda_batches_queue, train_batches_queue))
	cudathread.start()

	
	#We let queue to get filled before we start the training
	time.sleep(8)
	for epoch in range(num_epoches):
		for batch in range(batches_per_epoch):
			
			#We fetch a GPU batch in 0's due to the queue mechanism
			_, (batch_images, batch_labels) = cuda_batches_queue.get(block=True)
Exemple #16
0
import time
import Thread


def countdown(n):
    while n > 0:
        n -= 1


count = 50000000

t1 = Thread(target=countdown, args=((count // 2, )))
t2 = Thread(target=countdown, args=((count // 2, )))
start = time.time()
##countdown(count)
end = time.time()
print(end - start)
#!/usr/bin/python
#python ping2.py 
# Chapter 7 Cool Features of Python
# Author: William C. Gunnells
# Rapid Python Programming

# libs
from Threads!threadingthreading import Thread
import os

num1=2
num2=1 
dat="ping -c 1 127.0.0.%d" % num1 
dat1="ping -c 1 127.0.0.%d" % num2 

def mythread(x): 
	a=os.system(x) 

a=Thread(target=mythread, args=(dat1,))
c=Thread(target=mythread, args=(dat,))
b=Thread(target=mythread, args=(dat,))
a.start()
b.start()
c.start()
Exemple #18
0
import Thread


def square(n):
    print("square is ", n**2)


def cube(n):
    print("cube is ", pow(n, 3))


t1 = Thread(target=square, args=(3, ))
t2 = Thread(target=cube, args=(4, ))


def target():
    t1.start()
    t2.start()
    print("Hello")


target()
Exemple #19
0
    def logic_run_visualizer(self):
        # 获取设置参数,判断参数非空
        # 执行可视化脚本
        # 读取输入数据
        SOURCE_FOLDER = self.textEdit.toPlainText()
        VIDEO_NAME = self.textEdit_2.toPlainText()
        NAME = self.textEdit_3.toPlainText()
        if (SOURCE_FOLDER != '') & (VIDEO_NAME != '') & (NAME != ''):

            # 实例化线程
            self.setThread(Thread())
            # 将信号的线程与对应的控制器函数连接
            self.Thread.imgSig.connect(self.dispImage)
            self.Thread.canvasSig.connect(self.addToreal_time_info)
            # 启动线程。进行监听!!!
            self.Thread.start()

            # SET THE PATH AND CONFIG
            VIDEO_PATH = SOURCE_FOLDER + '/' + VIDEO_NAME
            DELTA_MS = 100
            LOCATION_NAME = "shanghai"
            DATE = "20200604"
            START_TIME = "1210"

            CAMERA_STREET = "area1_street_cfg.yml"
            CAMERA_SAT = "sat_cfg.yml"
            CAMERA_SAT_IMG = "sat.png"
            HD_MAP = "area1_street_hd_map.csv"

            # SET DETECTION AD IGNORE ZONES
            DET_ZONE_IM_VEHICLES = NAME + '_detection_zone_im.yml'
            DET_ZONE_FNED_VEHICLES = NAME + '_detection_zone.yml'
            IGNORE_AREA_VEHICLES = ''

            DET_ZONE_IM_PEDESTRIANS = NAME + "_detection_zone_im.yml"
            DET_ZONE_FNED_PEDESTRIANS = NAME + "_detection_zone.yml"
            IGNORE_AREA_PEDESTRIANS = ""

            # SET CROP VALUES FOR DETECTION HERE IF NEEDED
            CROP_X1 = 180
            CROP_Y1 = 120
            CROP_X2 = 1250
            CROP_Y2 = 720

            IMG_OUTPUT_FOLDER = SOURCE_FOLDER
            TIME_MAX_S = "20"
            SKIP = "2"
            IMG_DIR = SOURCE_FOLDER + "/img"
            OUTPUT_DIR = SOURCE_FOLDER + "/output"

            DET_DIR = OUTPUT_DIR + "/det/csv"

            MODE_VEHICLES = "vehicles"
            DYNAMIC_MODEL_VEHICLES = "BM2"
            LABEL_REPLACE_VEHICLES = "car"
            OUTPUT_VEHICLES_DIR = OUTPUT_DIR + '/' + MODE_VEHICLES
            DET_ASSO_VEHICLES_DIR = OUTPUT_VEHICLES_DIR + "/det_association/csv"
            TRAJ_VEHICLES_DIR = OUTPUT_VEHICLES_DIR + "/traj/csv"
            TRACK_MERGE_VEHICLES = OUTPUT_VEHICLES_DIR + "/det_association/" + NAME + "_tracks_merge.csv"
            TRAJ_VEHICLES = TRAJ_VEHICLES_DIR + '/' + NAME + "_traj.csv"
            TRAJ_INSPECT_VEHICLES_DIR = OUTPUT_VEHICLES_DIR + "/traj_inspect/csv"
            TRAJ_INSPECT_VEHICLES = TRAJ_INSPECT_VEHICLES_DIR + '/' + NAME + "_traj.csv"
            TRAJ_INSPECT_VEHICLES_TIME = TRAJ_INSPECT_VEHICLES_DIR + '/' + NAME + "_time_traj.csv"

            TRAJ_NOT_MERGED_CSV = TRAJ_INSPECT_VEHICLES_DIR + '/' + NAME + "_traj_not_merged.csv"
            SHRINK_ZONE = 1
            MIN_LENGTH = 6
            CONFLICTS_DIR = OUTPUT_DIR + '/detected_conflict'
            CONFLICTS_FILE = CONFLICTS_DIR + '/' + "conflict_detect.csv"

            # 按照函数参数格式,将想设置的参数编写为 命名空间
            parser = argparse.ArgumentParser(
                description='Visualize the final trajectories')
            parser.add_argument('-traj', default='')
            parser.add_argument('-image_dir', type=str, default='')
            parser.add_argument('-conflicts', type=str, default='')
            parser.add_argument('-camera_street', type=str, default='')
            parser.add_argument('-camera_sat', type=str, default='')
            parser.add_argument('-camera_sat_img', type=str, default='')
            parser.add_argument('-det_zone_fned', type=str, default='')
            parser.add_argument('-hd_map', type=str, default='')
            parser.add_argument('-output_dir', type=str, default='')
            parser.add_argument('-time', default='')
            parser.add_argument('-traj_person', default='')
            parser.add_argument('-shrink_zone', type=float, default=1.0)
            parser.add_argument('-no_label', action='store_true')
            parser.add_argument('-export', type=bool, default=False)
            args = parser.parse_args(['-traj', TRAJ_INSPECT_VEHICLES, \
                                      # 冲突点文件

                                      '-conflicts', CONFLICTS_FILE, \
                                      '-image_dir', SOURCE_FOLDER + "/img", \
                                      '-camera_street', SOURCE_FOLDER + '/' + CAMERA_STREET, \
                                      '-camera_sat', SOURCE_FOLDER + '/' + CAMERA_SAT, \
                                      '-camera_sat_img', SOURCE_FOLDER + '/' + CAMERA_SAT_IMG, \
                                      '-det_zone_fned', SOURCE_FOLDER + '/' + DET_ZONE_FNED_VEHICLES, \
                                      '-hd_map', SOURCE_FOLDER + '/' + HD_MAP, \
                                      '-output_dir', OUTPUT_DIR,\
                                      # 设置了自动导出图片,如果需要手动控制,可以去掉,并在run_visualizer.py加上cv2.imshow()展示视图才能实现控制

                                      '-export', 'True'])
            # 输出看一下结果
            # print(args)
            # “停止”按钮恢复
            self.pauseButton.setEnabled(True)
            # 让“开始”按钮和文本框 disable
            self.disableEverything()
            # 再调用 run_visualize_traj(args)实现可视化
            # run_visualize_traj(args, self.Thread)# 要定义线程,否则不能显示
            # 同时画 冲突点和 轨迹
            run_visualize_conflict_and_traj(args, self.Thread)

        else:
            QMessageBox.information(self, "提示", self.tr("请输入完整信息!"))
Exemple #20
0
from """①""" import Thread
from functools import reduce


def add_all(fr, to, index):
    s = 0
    for n in range(fr, to + 1):
        s += n
    result[index] = s


result = [0] * 10
th = [None] * 10
for i in range(10):
    start = """②"""
    end = """③"""
    th[i] = Thread(target="""④""", args=(start, end, i))
    th[i].start()
for i in range(10):
    th[i]."""⑤"""
print("{:,}".format(reduce(lambda x, y: x + y, result)))
# 出力結果 >>> 4,999,950,000
Exemple #21
0
 def _start_mock_file_server(self, fileServePath):
     self._handler = SimpleHTTPServer.SimpleHTTPRequestHandler
     self.httpd = SocketServer.TCPServer(("", self._mockServerport),
                                         self._handler)
     print("serving on port %i" % self._mockServerport)
     self._t = Thread(target=self.httpd.serve_forever).start()
df = pandas.read_csv("yourfile.csv")
#url column name
urls=df['Labeled Data']
#Name Column name
names=df['ID']
datalist=[]
namelist=[]
records=len(df)
threadsno=int(input("Enter no of Threads:"))
recordsperthread=records/threadsno
recordsperthread=round(recordsperthread)
jobs = []
a=0
b=recordsperthread
for j in range (0,threadsno):
    thread = Thread(target=fetch,args=(a,b,j))
    b=b+recordsperthread
    a=a+recordsperthread
    jobs.append(thread)
    # Start the threads 
for j in jobs:
    j.start()

    # Ensure all of the threads have finished
for j in jobs:
    j.join()
print('yes;;;')

#Function to create Folders according to the no of threads and saving the images in folders 
def fetch(a,b,j):
    for d in range(a,b):
Exemple #23
0
message = deque()

def reciever():
    global message
    while True:
        msg = pickle.loads(client.recv(4096))

        if msg[0] == 10:
            print("Match match made with", msg[1])
            t = input("Accept?[y/n]").lower()
            client.send(pickle.dumps([9, t]))
        else:
            deque.append(msg)

p = Thread(target=reciever)
p.start()

def pull():
    global people, people_checked, current_check

    if len(people) == 0 :
        client.send(pickle.dumps([2]))
        people = message.popleft()
        people = [x for x in people if x not in people_checked]
    
    current_check = people.pop(0)
    people_checked.add(current_check)

    print(current_check)
Exemple #24
0
        task = job_queue.get() # returns a map 
        print("task: " + str(task))
        if task['title'] == 'upload_task':
            response = task['client'].upload(task['filepath'], task['list'])
            print(response)
        job_queue.task_done()

if __name__ == '__main__':
    
    #lib.FileServer().start(8888)


    job_queue = Queue()
    num_threads = 4
    for i in range(num_threads):
        worker = Thread(target=do_task, args=(job_queue,))
        worker.setDaemon(True)
        worker.start()


    nodeid = 1
    nodeid_list = [2, 3]
    nodeid_map = {2: '8080', 3: '50001'}
    node_client = {}
    for each_node in nodeid_map:
        client = lib.FileClient('localhost:' + nodeid_map[eachnode])
        node_client[each_node] = client

    images_filepath = '/home/j/ODM-master/grpc_stages/node1'  #file path of current node images
    active_number_of_nodes = 2
    photos_name = collections.defaultdict(lambda : "None")
Exemple #25
0
    global key_list
    global t
    from pynput.keyboard import Key, Listener
    from pynput.keyboard import Key, Controller

    try:
        with Listener(on_press=on_press) as listener:
            t = time.time()
            listener.join()
    except:
        print('[-] Keyboard Error:')


def draw():
    print('''
    *****************************
    *                           *    
    *         Welcome to        *
    *           AutoBot         *
    *                           *
    *****************************
    \n''')
    input("Please press ENTER to start listening...")


try:
    t1 = Thread(target=keyboard)
    t1.start()
    mouse()
except KeyboardInterrupt:
    print('[+] Listener stopped')
 def start(self):
     # Start the thread that reads frames from the video stream
     Thread(target=self.update, args=()).start()
     return self
    def judge_matching(self):
        """
        judge
        0.78 = magick number
        """
        # テンプレート
        # 入力画像とテンプレート画像を取得
        temp = cv2.imread("/Users/work/futaba/slstage/.seed/s.png")
        # temp = cv2.imread("/Users/work/futaba/slstage/.seed/test.png")
        temp2 = cv2.imread("/Users/work/futaba/slstage/.seed/n-tar.png")

        # グレースケール変換
        temp = cv2.cvtColor(temp, cv2.COLOR_RGB2GRAY)
        temp2 = cv2.cvtColor(temp2, cv2.COLOR_RGB2GRAY)

        # テンプレート画像の高さ・幅
        height, width = temp.shape
        height2, width2 = temp2.shape

        Image(self.m_urls).refresh_image()
        for i, m_url in enumerate(self.m_urls):
            name = m_url[1].replace("http://img.2chan.net/b/src/",
                                    "/Users/work/futaba/slstage/.result/")

            print("m_url[0] =", m_url[0])
            print("m_url[1] =", m_url[1])
            print("name     =", name)

            imag = cv2.imread(name)
            # Resize image
            image = cv2.resize(imag, (400, 400), interpolation=cv2.INTER_AREA)
            # グレースケール変換
            gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
            # テンプレートマッチング
            match = cv2.matchTemplate(gray, temp, cv2.TM_CCOEFF_NORMED)
            match2 = cv2.matchTemplate(gray, temp2, cv2.TM_CCOEFF_NORMED)
            min_value, max_value, min_pt, max_pt = cv2.minMaxLoc(match)
            min_value2, max_value2, min_pt2, max_pt2 = cv2.minMaxLoc(match2)
            point = max_pt
            point2 = max_pt2
            # print("[{:2d}] s={:.5f}, tar={:>.5f}".format(i, max_value,
            #                                                max_value2) )
            if max_value >= 0.78:
                print(name, end="")
                print(" = {:.5f}".format(max_value))
                os.chdir("/Users/work/futaba/slstage/.icons/")
                # テンプレートマッチングの結果を出力
                cv2.rectangle(image, (point[0], point[1]),
                              (point[0]+width, point[1]+height),
                              (0, 0, 200), 3)
                cv2.imwrite(str(TimeGetter().get_now_time()) + ".png", imag)
                Thread(m_url[0]).get_thread()
                break
            if max_value2 >= 0.78:
                print(name, end="")
                print(" = {:.5f}".format(max_value2))
                os.chdir("/Users/work/futaba/slstage/.icons/")
                # テンプレートマッチングの結果を出力
                cv2.rectangle(image, (point2[0], point2[1]),
                              (point2[0]+width2, point2[1]+height2),
                              (0, 0, 200), 3)
                cv2.imwrite(str(TimeGetter().get_now_time()) + ".png", imag)
                Thread(m_url[0]).get_thread()
                break
    def __init__(self, parent = None):
        
        QtGui.QWidget.__init__(self,parent)
        self.setWindowTitle('TenElevenGamezSOS')      #window Title
        self.setWindowIcon (QtGui.QIcon ("sos.png"))  #window icon
        
        #set Bold font for Group Box Titles
        font = QtGui.QFont('Arial',13,QtGui.QFont.Bold)        
            
        
        #set_picture
        self.pixmap1 = QtGui.QPixmap('images/transparent_text_effect.png')
        self.pic_label = QtGui.QLabel()
        self.pic_label.setPixmap(self.pixmap1) 
        
        self.decor = QtGui.QPixmap('images/simple_sos.png')
        self.decor_label = QtGui.QLabel()
        self.decor_label.setPixmap(self.decor)
        
        self.decor = QtGui.QPixmap('images/simple_sos.png')
        self.decor_label2 = QtGui.QLabel()
        self.decor_label2.setPixmap(self.decor)        

        #Edit_Boxes
        self.position_edit = QtGui.QLineEdit(self)
        self.position_edit.setPlaceholderText("Enter Position Number(0-15)")
        self.server_edit = QtGui.QLineEdit(self)  #edit box for the IP address of the server
        self.server_edit.setPlaceholderText("Enter Clients IP")
        
        #comboBox
        self.character_combox = QtGui.QComboBox()
        self.list_colour = ['S','O']
        self.character_combox.addItems(self.list_colour)
        
        #Variables for Shape of the player and scores
        self.current_player = None
        self.shape_player1 = None
        self.shape_player2 = None        
        
        self.score_player1 = 0
        self.score_player2 = 0        
        
        #labels
        self.heading = QtGui.QLabel("SOS Game") # Window title
        self.server_label = QtGui.QLabel("Server:")
        self.server_label.setFont(font)
        self.heading.setFont(QtGui.QFont('Forte',30))
        
        self.score = QtGui.QLabel("Score:")
        self.game_board = QtGui.QLabel("Game Board")
        self.message = QtGui.QLabel("Message")
        
        self.position = QtGui.QLabel("Position  :")
        self.character = QtGui.QLabel("Character:")
        self.blank = QtGui.QLabel(" "*130)
        self.blank2 = QtGui.QLabel(" "*100)
        self.s = QtGui.QLabel("S:")
        self.o = QtGui.QLabel("O:")
        
        self.display_Message = QtGui.QTextBrowser()
        self.display_Message.setText("SOS GAME")
        self.display_Message.setMinimumSize(100,200) 
        self.display_Message.setMaximumSize(500,500)
        
        self.display_Board = QtGui.QTextBrowser()
        self.display_Board.setPlainText("")   #Display_Grid/Board
        
        self.display_Scores1 = QtGui.QTextBrowser()   #score board for player 1
        self.display_Scores1.setText("Player 0 \n"
                                     "Score: 0")
        self.turn = 'disconnected' # Checks the turn
        
        self.display_Scores2 = QtGui.QTextBrowser()   #score board for player 2
        self.display_Scores2.setMinimumSize(100,200) 
        self.display_Scores2.setMaximumSize(500,20) 
        self.display_Scores2.setText("Player 1 \n"
                                     "Score: 0")
        
        #Buttons
        self.connect_button = QtGui.QPushButton('Connect')
        self.connect_button.setFont(font)
        self.new_game_button = QtGui.QPushButton('New Game')
        self.exit = QtGui.QPushButton('Exit')
        self.submit_button = QtGui.QPushButton('Send Move')
        
        #checkBox
        self.character1 = QtGui.QCheckBox()
        self.character2 = QtGui.QCheckBox() 
        
        #Board_Pictures
        
        self.zero = QtGui.QPixmap('images/zero_109x109.png')
        self.pic_zero = QtGui.QLabel()
        self.pic_zero.setPixmap(self.zero) 
        
        self.one = QtGui.QPixmap('images/one_109x109.png')
        self.pic_one = QtGui.QLabel()
        self.pic_one.setPixmap(self.one)
        
        self.two = QtGui.QPixmap('images/two_109x109.png')
        self.pic_two = QtGui.QLabel()
        self.pic_two.setPixmap(self.two)
        
        self.three = QtGui.QPixmap('images/three_109x109.png')
        self.pic_three = QtGui.QLabel()
        self.pic_three.setPixmap(self.three)
        
        self.four = QtGui.QPixmap('images/four_109x109.png')
        self.pic_four = QtGui.QLabel()
        self.pic_four.setPixmap(self.four)
        
        self.five = QtGui.QPixmap('images/five_109x109.png')
        self.pic_five = QtGui.QLabel()
        self.pic_five.setPixmap(self.five)
        
        self.six = QtGui.QPixmap('images/six_109x109.png')
        self.pic_six = QtGui.QLabel()
        self.pic_six.setPixmap(self.six)
        
        self.seven = QtGui.QPixmap('images/seven_109x109.png')
        self.pic_seven = QtGui.QLabel()
        self.pic_seven.setPixmap(self.seven)
        
        self.eight = QtGui.QPixmap('images/eight_109x109.png')
        self.pic_eight = QtGui.QLabel()
        self.pic_eight.setPixmap(self.eight)
        
        self.nine = QtGui.QPixmap('images/nine_109x109.png')
        self.pic_nine = QtGui.QLabel()
        self.pic_nine.setPixmap(self.nine)
        
        self.ten = QtGui.QPixmap('images/ten_109x109.png')
        self.pic_ten = QtGui.QLabel()
        self.pic_ten.setPixmap(self.ten)
        
        self.eleven = QtGui.QPixmap('images/eleven_109x109.png')
        self.pic_eleven = QtGui.QLabel()
        self.pic_eleven.setPixmap(self.eleven)
        
        self.twelve = QtGui.QPixmap('images/twelve_109x109.png')
        self.pic_twelve = QtGui.QLabel()
        self.pic_twelve.setPixmap(self.twelve)        
        
        self.thirteen = QtGui.QPixmap('images/thirteen_109x109.png')
        self.pic_thirteen = QtGui.QLabel()
        self.pic_thirteen.setPixmap(self.thirteen)
        
        self.fourteen = QtGui.QPixmap('images/fourteen_109x109.png')
        self.pic_fourteen = QtGui.QLabel()
        self.pic_fourteen.setPixmap(self.fourteen)
        
        self.fifteen = QtGui.QPixmap('images/fifteen_109x109.png')
        self.pic_fifteen = QtGui.QLabel()
        self.pic_fifteen.setPixmap(self.fifteen)        
        
        #Style
    
        #display for scores
        groupBox =QtGui.QGroupBox("Scores")
        gridA = QtGui.QGridLayout()
        gridA.addWidget(self.display_Scores1,0,0,5,10)
        gridA.addWidget(self.display_Scores2,1,0,5,10)
        gridA_Widget= QtGui.QGroupBox("Scores")
        gridA_Widget.setFont(font)
        gridA_Widget.setLayout(gridA) 
        
        #display for the board
        groupBox =QtGui.QGroupBox("Board")
        gridB = QtGui.QGridLayout()
        gridB.addWidget(self.pic_zero,0,0)
        gridB.addWidget(self.pic_one,0,1)
        gridB.addWidget(self.pic_two,0,2)
        gridB.addWidget(self.pic_three,0,3)
        
        gridB.addWidget(self.pic_four,1,0)
        gridB.addWidget(self.pic_five,1,1)
        gridB.addWidget(self.pic_six,1,2)
        gridB.addWidget(self.pic_seven,1,3)
        
        gridB.addWidget(self.pic_eight,2,0)
        gridB.addWidget(self.pic_nine,2,1)
        gridB.addWidget(self.pic_ten,2,2)
        gridB.addWidget(self.pic_eleven,2,3)
        
        gridB.addWidget(self.pic_twelve,3,0)
        gridB.addWidget(self.pic_thirteen,3,1)
        gridB.addWidget(self.pic_fourteen,3,2)
        gridB.addWidget(self.pic_fifteen,3,3)
        
        gridB_Widget= QtGui.QGroupBox("Game-Board")
        gridB_Widget.setFont(font)
        gridB_Widget.setLayout(gridB) 
    
        #display for the messages
        
        groupBox =QtGui.QGroupBox("Messages")
        gridC = QtGui.QGridLayout()
        gridC.addWidget(self.display_Message,3,3,5,10)
        gridC_Widget= QtGui.QGroupBox("Messages")
        gridC_Widget.setFont(font)
        gridC_Widget.setLayout(gridC)        
        
        #Grid_Layout_Play-Choice/)
        grid1 = QtGui.QGridLayout()
        
        grid1.addWidget(self.position,0,0)
        grid1.addWidget(self.position_edit,0,1)
        grid1.addWidget(self.character,0,2)
        grid1.addWidget(self.character_combox,0,3)
        grid1.addWidget(self.submit_button,0,4)
        grid1.addWidget(self.blank2,0,5)


        grid1_widget = QtGui.QGroupBox("Play-Choice")
        grid1_widget.setFont(font)
        grid1_widget.setLayout(grid1)
        
        #grid1_widget.setPalette(QtGui.QPalette(QtGui.QColor('skyBlue')))
        #grid1_widget.setAutoFillBackground(True)        
        
        #Grid_Layout_New_Game/Exit_Button
        Grid_new = QtGui.QGridLayout()
        
        Grid_new.addWidget(self.new_game_button,0,0)
        Grid_new.addWidget(self.exit,0,1)
        Grid_new_exit = QtGui.QGroupBox("New-Game/Exit")
        Grid_new_exit.setFont(font)
        Grid_new_exit.setLayout(Grid_new)
        
        #Layaut_Section
        
        #Horizontal_layout_HEADING/Server_Section
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addStretch(5)
        hbox1.addWidget(self.decor_label)
        hbox1.addStretch(5)
        hbox1.addWidget(self.pic_label)
        hbox1.addStretch(5)
        hbox1.addWidget(self.decor_label2)
        hbox1.addStretch(5)
        hbox1_widget = QtGui.QWidget()
        hbox1_widget.setLayout(hbox1)
        
        #Horizontal_layout_HEADING_Section
        hbox = QtGui.QHBoxLayout()
        
        hbox.addWidget(self.server_label)
        hbox.addWidget(self.server_edit)
        hbox.addWidget(self.connect_button)
        hbox.addWidget(self.blank)
        #hbox.addWidget(self.disconnect_button)
       
        hbox_widget = QtGui.QWidget()
        hbox_widget.setLayout(hbox)
        
        #Horizontal layout for Displays
        hbox3 = QtGui.QHBoxLayout()
        hbox3.addWidget(gridA_Widget)   #grid for the scores
        hbox3.addWidget(gridB_Widget)   #Grid for the scores
        hbox3.addWidget(gridC_Widget)   #Grid for the messages
        hbox3_widget = QtGui.QWidget()  #Create the widget for all of them
        hbox3_widget.setLayout(hbox3)      
        
        #Horizontal_bottom
        hbox4 = QtGui.QHBoxLayout()
        
        hbox4.addWidget(grid1_widget)
        hbox4.addWidget(Grid_new_exit)
        grid_widget = QtGui.QWidget()
        grid_widget.setLayout(hbox4)           
        
        #Combined_Layout
        vbox = QtGui.QVBoxLayout()
        
        vbox.addWidget(hbox1_widget)  #display Heading
        vbox.addWidget(hbox_widget)   #display the server things
        vbox.addWidget(hbox3_widget)
        vbox.addWidget(grid_widget)
        
        self.setLayout(vbox) 
        
        self.setPalette(QtGui.QPalette(QtGui.QColor("skyBlue")))
        self.setAutoFillBackground(True)
        
        #backgroundColor and picture
        self.picture = QtGui.QPalette(self)
        self.picture.setBrush(QtGui.QPalette.Background,QtGui.QBrush(QtGui.QPixmap('images/o7nZzK2.jpg')))   
        self.setPalette(self.picture)        
      
        #Buttons_Connections/Events_Handling
        self.connect(self.exit,QtCore.SIGNAL('clicked()'), self.Close_Button)
        self.connect(self.new_game_button,QtCore.SIGNAL('clicked()'), self.NewGame)
        self.connect(self.submit_button,QtCore.SIGNAL('clicked()'), self.SendMove)
        #self.connect(self.submit_button,QtCore.SIGNAL('clicked()'), self.Update_Board)
        
        #Buttons_Handling
        self.connect_button.clicked.connect(self.Connection)    #Connect button Signal
        #self.submit_button = cmds.button(command = partial(my_button_on_click_handler, arg1, arg2))      #Send Move to the server button
        
        
        self.loopthread = Thread()   #creating the thread
        
        #connecting signals to slots
        self.loopthread.update_signal.connect(self.handle_message) 
Exemple #29
0
 def __init__(self, process_time):
     self.thread = Thread.Thread()
     self.start_time = 0L
     self.finish_time = 0L
     self.process_time = process_time
    pyautogui.typewrite(' space')
    time.sleep(0.25)
    pyautogui.keyDown('left')
    time.sleep(0.63)
    pyautogui.keyUp('left')


def randomly_move_left():
    time.sleep(2)
    pyautogui,keyDown('left')
    pyautogui.keyUp('left')

def randomly_move_right():
    while True:
        time.sleep(2)
        pyautogui.keyDown('right')
        pyautogui.keyUp('right')

def fire():
    while True:
        pyautogui.typewrite([' space'])
        time.sleep(0.25)


go_left_thread = Threading(target=randomly_move_left)
go_left_thread.start()
go_right_thread = Thread(target=randomly_move_right)
go_right_thread.start()
fire_thread = Thread(target=fire)
fire_thread.start()