Ejemplo n.º 1
0
    def extract_link(self, dork, page):

        try:

            resp = get(url="https://www.bing.com/search?q={}&first={}".format(
                dork, str(page)),
                       headers={"User-Agent": self.useragent()},
                       timeout=5)
            link = findall("href=\"(.+?)\"", resp.text)

            for x in link:

                xurl = x.split("/")

                if xurl[0] == "http:" or xurl[0] == "https:":

                    if all(not xxx in xurl[2]
                           for xxx in [".bing.", ".google.", ".microsoft."]):

                        Thread(target=self.check_site, args=(x, )).start()
                        delay(0.1)

        except:

            pass
Ejemplo n.º 2
0
 def run(self):
     self.queue = dq(maxlen = 200)
     if(len(self.queue)):
         msg = self.queue[0]
         self.queue.popleft()                
         self.change_value.emit(msg)
     delay(1)
Ejemplo n.º 3
0
def payment_gateway(request):
    try:
        seats = request.POST.get('selected_seat')
        seat_type = request.POST.get('seat_type')
        show_id = request.POST.get('show_id')

        show = Show.objects.get(pk=show_id)
        seats = seats.split(',')
        book_seat = []
        for each in seats:
            s = Seat.objects.get(no=each, seat_type=seat_type, show=show)
            s.status = "Processing"
            if Seat.objects.filter(no=each, show=show).exists():
                return render(request, 'booking/reserve_seat.html', {
                    'show_info': show,
                    'form': SeatForm()
                })

                s.status = "Occupied"
                s.save()
                book_seat.append(s)
            else:
                import time
                time.delay(float(180))
                s.staus = "Available"
                s.save()
                return HttpResponseRedirect("/")

    except:
        return HttpResponseRedirect('/home/')
Ejemplo n.º 4
0
    def get_configuration(self):
        success = False
        retry_count = 0

        while retry_count < 5 and not success:
            try:
                config = self.read(IMURegisters.NAVX_REG_WHOAMI, IMURegisters.NAVX_REG_SENSOR_STATUS_H + 1)
            except IOError as e:
                logger.warn("Error reading configuration data, retrying (%s)", e)
                success = False
                time.delay(0.5)
            else:
                board_id = self.board_id
                board_id.hw_rev                 = config[IMURegisters.NAVX_REG_HW_REV]
                board_id.fw_ver_major           = config[IMURegisters.NAVX_REG_FW_VER_MAJOR]
                board_id.fw_ver_minor           = config[IMURegisters.NAVX_REG_FW_VER_MINOR]
                board_id.type                   = config[IMURegisters.NAVX_REG_WHOAMI]
                self.ahrs._set_board_id(board_id)

                board_state = self.board_state
                board_state.cal_status          = config[IMURegisters.NAVX_REG_CAL_STATUS]
                board_state.op_status           = config[IMURegisters.NAVX_REG_OP_STATUS]
                board_state.selftest_status     = config[IMURegisters.NAVX_REG_SELFTEST_STATUS]
                board_state.sensor_status       = AHRSProtocol.decodeBinaryUint16(config, IMURegisters.NAVX_REG_SENSOR_STATUS_L)
                board_state.gyro_fsr_dps        = AHRSProtocol.decodeBinaryUint16(config, IMURegisters.NAVX_REG_GYRO_FSR_DPS_L)
                board_state.accel_fsr_g         = config[IMURegisters.NAVX_REG_ACCEL_FSR_G]
                board_state.update_rate_hz      = config[IMURegisters.NAVX_REG_UPDATE_RATE_HZ]
                board_state.capability_flags    = AHRSProtocol.decodeBinaryUint16(config, IMURegisters.NAVX_REG_CAPABILITY_FLAGS_L)
                self.ahrs._set_board_state(board_state)
                success = True

            retry_count += 1

        return success
Ejemplo n.º 5
0
 def color_change(self):
     if (not (self.pushing)):
         self.pushing = True
         self.background("background-color: red")
         delay(.3)
         self.background("background-color: white")
         self.pushing = False
Ejemplo n.º 6
0
 def workerThread(self):
     for x in range(self.total):
         delay(self.delay)
         self.rem = self.total-x-1
         self.Google_server.sendmail(" ",self.target,self.mesg)
         self.gui.stepIt()
     self.running = False
 def waitTillPuppetFinishes(self):
     filePath = "/var/lib/puppet/reports/"+self.mgmtHostInfo['hostname']+"."+self.DOMAIN
     while not os.path.exists(filePath):
          delay(60)
          self.logger.info("waiting for puppet setup to finish")
          continue
     pass
Ejemplo n.º 8
0
    def _test_TC_PM_001(self):
        """ Update basic info """

        self.driver.get("https://www.vietnamworks.com/my-profile")
        WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((
            By.XPATH,"/html/body/div[1]/div/div[6]/div[2]/div[1]"))).click()
        
        input_first_name = "//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[3]/div[1]/div[1]/div[2]/div/input"
        self.set_input(input_first_name, "Quoc Minh")

        input_last_name = "//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[3]/div[1]/div[2]/div[2]/div/input"
        self.set_input(input_last_name, "Nguyen")

        input_job_title = "//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[3]/div[1]/div[3]/div[2]/div/input"
        self.set_input(input_job_title, "IT")

        _job_level = "Entry Level"
        self.select_search(
            """//*[@id="__next"]/div/div[6]/div[2]/div[1]/div/div[3]/div[1]/div[4]/div[2]/div/div""",
            _job_level
        )

        self.driver.find_element_by_xpath("//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[3]/div[3]/div[2]/button[2]").click()

        delay(0.5)
        response = self.driver.find_element_by_xpath("//*[@id='__next']/div/div[7]").text

        actual = "success" in response
        expect = True
        result = True if (actual == expect) else False

        self.assertTrue(TestUtil.checkTestcase(result,True,"TC-PM-001"))
Ejemplo n.º 9
0
    def _test_TC_PM_017(self):
        """ Another sumary """

        self.driver.get("https://www.vietnamworks.com/my-profile")
        sumary_block = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((
            By.XPATH,"""//*[@id="__next"]/div/div[6]/div[2]/div[4]""")))

        try:
            sumary_block.find_element_by_class_name("globalAddButton").click()
        except:
            try:
                sumary_block.find_element_by_class_name("EditIcon").click()
            except:
                ""
        sumary_content = "Hello, World! \n\n\n I am Selenium"
        self.set_input(
            """//*[@id="__next"]/div/div[6]/div[2]/div[4]/div/div[1]/div[1]/div[2]/div/div/div/div/div""",
            sumary_content
        )

        self.driver.find_element_by_xpath("""//*[@id="__next"]/div/div[6]/div[2]/div[4]/div/div[2]/div/button[2]""").click()

        delay(0.5)
        response = self.driver.find_element_by_xpath("//*[@id='__next']/div/div[7]").text

        actual = False
        if "success" in response:
            actual = True
                
        expect = True
        result = True if (actual == expect) else False

        self.assertTrue(TestUtil.checkTestcase(result,True,"TC-PM-017"))
Ejemplo n.º 10
0
def _isPortOpen(hostQueue, port=22):
    """
    Checks if there is an open socket on specified port. Default is SSH
    """
    ready = []
    host = hostQueue.get()
    while True:
        channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        channel.settimeout(20)
        try:
            logging.debug("Attempting port=%s connect to host %s"%(port, host))
            err = channel.connect_ex((host, port))
        except socket.error as e:
            logging.debug("encountered %s retrying in 5s"%e)
            err = e.errno
            delay(5)
        finally:
            if err == 0:
                ready.append(host)
                logging.info("host: %s is ready"%host)
                break
            else:
                logging.debug("[%s] host %s is not ready. Retrying"%(err, host))
                delay(5)
                channel.close()
    hostQueue.task_done()
Ejemplo n.º 11
0
def main():
    try:
        choice = """
        Please enter your choice :
            1.Encode the text to binary
            2.Decode the binary script
            
            --> """
        try:
            choice = int(input(choice))
            if choice != 1 and choice != 2:
                print("enter a valid choice!, rn again.")
                delay(2)
                exit()
        except ValueError:
            print("enter a valid choice!, run again.")
            delay(2)
            exit()

        if (choice == 1):
            call_encode()
        else:
            call_decode()

        termi = input("press enter.")
        del termi
    except Exception as e:
        print(e)
Ejemplo n.º 12
0
def lte_connect():
    lte = LTE()
    lte.init()
    #some carriers have special requirements, check print(lte.send_at_cmd("AT+SQNCTM=?")) to see if your carrier is listed.
    #when using verizon, use
    #lte.init(carrier=verizon)
    #when usint AT&T use,
    #lte.init(carrier=at&t)
    #some carriers do not require an APN
    #also, check the band settings with your carrier
    lte.attach(band=2, apn="vzwinternet")
    print("attaching..", end='')
    while not lte.isattached():
        time.delay(0.25)

        print('.', end='')
        print(lte.send_at_cmd('AT!="fsm"'))  # get the System FSM
    print("attached!")

    lte.connect()
    print("connecting [##", end='')
    while not lte.isconnected():
        time.sleep(0.25)
        print('#', end='')
        #print(lte.send_at_cmd('AT!="showphy"'))
        print(lte.send_at_cmd('AT!="fsm"'))
    print("] connected!")

    print(socket.getaddrinfo('pycom.io', 80))
    lte.deinit()
Ejemplo n.º 13
0
    def parse_personal_details(self,url):
        print"IN"

        try:
         detail_personal = AngelInParser(3)
        except:
         print"1"
        try:
         detail_personal_data =detail_personal.loginPage(url,3)
         time.delay(randint(0,240))
        except:
         print "2"
        try:
         detail_personal_doc = html.fromstring(detail_personal_data)
        except:
         print"3"
        try:
         linked_in=detail_personal_doc.xpath("//a[contains(@class,'icon link_el fontello-linkedin')]/@href")
        except:
         linked_in=None
        try:
         designation=detail_personal_doc.xpath("//div[contains(@class,'dm77 fud43 _a _jm')]/p/text()")
        except:
         designation=None
        # print designation
        # print linked_in
        return [linked_in,designation]
Ejemplo n.º 14
0
    def draw(
        self, win
    ):  # ngedraw papan (okay button, player turn, quit button sama cellboard)
        #x = 262
        #y = 130
        #colsize = 55
        #rowsize = 58

        #ngeloop buat ngeprint cellboard
        for i in range(self.x):
            for j in range(self.y):
                self.isi[i][j].draw(win)

        #ngeprint player1
        play1 = pygame.transform.scale(self.play1[self.turn - 1], (126, 46))
        win.blit(play1, (842, 670))

        #ngeprint player1
        play2 = pygame.transform.scale(self.play2[self.turn - 1], (126, 46))
        win.blit(play2, (10, 10))

        #ngeprint okay button
        win.blit(self.okbut, (1020, 280))
        #pygame.draw.rect(win, (255,0,0), self.okayhitbox,2)

        #ngeprint quit button
        win.blit(self.quitbut, (1020, 380))
        #pygame.draw.rect(win, (255,0,0), self.quithitbox,2)
        if self.checkwin():
            self.drawWin(win)
            time.delay(1)
Ejemplo n.º 15
0
def sayit(mytext):
    global num
    global t1

    # mytext =t1.get()

    # Language in which you want to convert
    language = 'en'

    # Passing the text and language to the engine,
    # here we have marked slow=False. Which tells
    # the module that the converted audio should
    # have a high speed
    global l2
    l2.destroy()
    # t1.clear()
    t1.delete(0, END)
    t1.insert(0, mytext)
    myobj = gTTS(text=mytext, lang=language, slow=False)
    num += 1
    string = str(num) + ".mp3"
    # l2.clear()
    # Saving the converted audio in a mp3 file named
    # welcome
    myobj.save(string)

    # Playing the converted file
    playsound.playsound(string, True)
    l2 = Label(root, text=speaking)
    l2.grid(row='1', column='0')
    os.remove(string)

    time.delay(1)
    l2.destroy()
Ejemplo n.º 16
0
def main():
    clearConsole()
    print("--------------------------------------------------")
    print("--------------------------------------------------")
    print("-------------GEM SARI SARI STORE POS--------------")
    print("--------------------------------------------------")
    print("--------------------------------------------------")
    print("1. Login")
    print("2. Exit the Program")
    while True:
        option = input("please choose an option:")
        if option == 1 or option == "1":
            delay(2)
            Login()
            break
        elif option == 2 or option == "2":
            print("1. Yes")
            print("2. No")
            while True:
                option = input(str("do you want to exit?"))
                if option == 1 or option == "1":
                    clearConsole()
                    closeProcess(0)
                elif option == 2 or option == "2":
                    clearConsole()
                    main()
        else:
            print("Invalid Option!")
            continue
Ejemplo n.º 17
0
    def sweep_temp(self,
                   Ti=22.5,
                   Tf=23.5,
                   dT=0.01,
                   dtime=4,
                   func=None,
                   func_args=None):

        n = int((Tf - Ti) / dT)
        dT = dT * np.sign(Tf - Ti)
        T = np.zeros(n, dtype=float)
        t = np.zeros(n, dtype=float)

        self._inst.write('SOUR2:TEMP {}'.format(Ti))

        for i in range(n):
            t[i] = time.time()
            T[i] = self._inst('MEAS:TEMP?')

            if func is not None:
                func(i, *func_args)

            time.delay(dtime)
            self._inst.write('SOUR2:TEMP {}'.format(Ti + i * dT))

        t = t - t[0]

        return t, T
Ejemplo n.º 18
0
def happybirthday(person):
	from time import sleep as delay
	print('Happy Birthday To You')
	delay(2)
	print('Happy Birthday To You')
	delay(2)
	print('Happy Birthday Dear ' + str(case(person, argument='sentence')))
Ejemplo n.º 19
0
        def GET(self):
                getInput = web.input(name="")
                aName = str(getInput.name)
                if aName:
                        # set RPi board pins high
                        GPIO.output(7, GPIO.HIGH)
                        GPIO.output(11, GPIO.HIGH)
                        time.delay(1)
                        # set RPi board pins low
                        GPIO.output(7, GPIO.LOW)
                        GPIO.output(11, GPIO.LOW)
                        return """
                                <html>
                                <head>
                                <script>
                                function loaded()
                                {
                                    window.setTimeout(CloseMe, 5);
                                }

                                function CloseMe()
                                {
                                    window.close();
                                }
                                </script>
                                </head>
                                <body onLoad="loaded()">
                                Thanks """+aName+"""!
Ejemplo n.º 20
0
 def Run(self):
     while True:
         try:
             self.bot.polling()
         except:
             loger.exception("bot polling exception. repeating after delay")
         time.delay(5)
Ejemplo n.º 21
0
 def disengage(self):
   if (self.state==0):
     return
   time.delay(.3)
   GPIO.output(solenoid_pin,0)
   time.delay(.3)
   self.state=0
Ejemplo n.º 22
0
    def _test_TC_PM_002(self):
        """ Update ava profile with IMG file """

        self.driver.get("https://www.vietnamworks.com/my-profile")

        WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((
            By.XPATH,"//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[1]/div/div"))).click()
        
        delay(0.5)
        window = pyautogui.getWindowsWithTitle(self.driver.title)[0]
        window.maximize
        window.center
        delay(1)
        ava_file1 = os.path.join(self.input_files_path, "image.jpg")
        pyautogui.write(ava_file1)
        delay(0.5)
        pyautogui.press('enter')
        delay(1)
        ava_update_warining = "ok"
        try:
            ava_update_warining = self.driver.find_element_by_xpath("//*[@id='__next']/div/div[6]/div[2]/div[1]/div/div[1]/div/div[3]")
        except:
            ""
        delay(1)
        actual = False
        if ava_update_warining == "ok":
            self.driver.find_element_by_xpath("/html/body/div[3]/div/div[3]/button[2]").click()
            actual = True
        else:
            "Failed"
        
        expect = True
        result = True if (actual == expect) else False
        self.assertTrue(TestUtil.checkTestcase(result,True,"TC-PM-002"))
Ejemplo n.º 23
0
def distance_ptol():
    """DISTANCE BETWEEN POINT AND LINE"""
    delay(0.5)
    print("Welcome to Distance between Point and Line topic!")
    delay(0.5)
    print()
    print("Input the point(Input example \"(x,y)\": ", end="")
    point_ptol = input()
    print("From \"Ax + By + C = 0\": ")
    print("\t• Input \"A\": ", end="")
    a_ptol = float(input())
    print("\t• Input \"B\": ", end="")
    b_ptol = float(input())
    print("\t• Input \"C\": ", end="")
    c_ptol = float(input())
    point_ptol = point_ptol.replace("(", "").replace(")", "")
    try :
        list_point = point_ptol.split(",")
        top_ptol = abs(a_ptol*float(list_point[0])+b_ptol*float(list_point[1])+c_ptol)
        bottom_ptol = math.sqrt(a_ptol**2+b_ptol**2)
        ans_ptol = top_ptol/bottom_ptol
        print()
        print("Distance between (%s) and line %sx%sy%s = 0  is %.2f"%(point_ptol, a_ptol, line_made(b_ptol), line_made(c_ptol), ans_ptol))
    except:
        print()
        print("Please input in the same format as example.")
Ejemplo n.º 24
0
    def _test_TC_PM_022(self):
        """  """

        self.driver.get("https://www.vietnamworks.com/my-profile")
        education_block = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((
            By.XPATH,"""//*[@id="__next"]/div/div[6]/div[2]/div[7]""")))

        education_block.find_element_by_xpath("""//*[@id="__next"]/div/div[6]/div[2]/div[7]/div/div[2]""").click()
        _skill = "123456789"
        if len(education_block.find_elements_by_class_name("list-added-skills")) == 0:

            self.set_input(
                """//*[@id="__next"]/div/div[6]/div[2]/div[7]/div/div[2]/div/div[1]/div/div/input""",
                _skill
            )
            self.driver.find_element_by_xpath("""//*[@id="__next"]/div/div[6]/div[2]/div[7]/div/div[3]/div/button[2]""").click()
        else:
            self.set_input(
                """//*[@id="__next"]/div/div[6]/div[2]/div[7]/div/div[3]/div/div[1]/div/div/input""",
                _skill
            )
            self.driver.find_element_by_xpath("""//*[@id="__next"]/div/div[6]/div[2]/div[7]/div/div[4]/div/button[2]""").click()

        delay(0.5)
        response = self.driver.find_element_by_xpath("//*[@id='__next']/div/div[7]").text

        actual = False
        if "success" in response:
            actual = True
                
        expect = True
        result = True if (actual == expect) else False

        self.assertTrue(TestUtil.checkTestcase(result,True,"TC-PM-022"))
Ejemplo n.º 25
0
 def __init__(self, console):
     self.console = console
     self.console_thread = QueueThread()
     self.console_thread.change_value.connect(self.updateConsole)
     self.console_thread.start()
     delay(.1)
     self.pub('Starting Console Manager\n')
Ejemplo n.º 26
0
def prepareManagementServer(mgmt_host):
    """
    Prepare the mgmt server for a marvin test run
    """
    if _isPortListening(host=mgmt_host, port=22, timeout=10) \
            and _isPortListening(host=mgmt_host, port=3306, timeout=10) \
            and _isPortListening(host=mgmt_host, port=8080, timeout=300):
        delay(120) #introduce dumb delay
        mgmt_ip = macinfo[mgmt_host]["address"]
        mgmt_pass = macinfo[mgmt_host]["password"]
        with contextlib.closing(sshClient.SshClient(mgmt_ip, 22, "root", mgmt_pass)) as ssh:
            # Open up 8096 for Marvin initial signup and register
            ssh.execute("mysql -ucloud -pcloud -Dcloud -e\"update configuration set value=8096 where name like 'integr%'\"")
            ssh.execute("service cloudstack-management restart")
    else:
        raise Exception("Reqd services (ssh, mysql) on management server are not up. Aborting")

    if _isPortListening(host=mgmt_host, port=8096, timeout=300):
        logging.info("All reqd services are up on the management server %s"%mgmt_host)
        testManagementServer(mgmt_host)
        return
    else:
        with contextlib.closing(sshClient.SshClient(mgmt_ip, 22, "root", mgmt_pass)) as ssh:
            # Force kill java process
            ssh.execute("killall -9 java; service cloudstack-management start")

    if _isPortListening(host=mgmt_host, port=8096, timeout=300):
        logging.info("All reqd services are up on the management server %s"%mgmt_host)
        testManagementServer(mgmt_host)
        return
    else:
        raise Exception("Reqd service for integration port on management server %s is not open. Aborting"%mgmt_host)
Ejemplo n.º 27
0
 def test_templateBuiltInReady(self):
     """
     built-in templates CentOS to be ready
     """
     for z in self.zones_list:
         retry = self.retry
         while retry != 0:
             self.debug("Looking for at least one ready builtin template")
             templates = listTemplates.listTemplatesCmd()
             templates.templatefilter = 'featured'
             templates.listall = 'true'
             templates_list = self.apiClient.listTemplates(templates)
             if templates_list is not None:
                 builtins = [tmpl
                             for tmpl in templates_list
                             if tmpl.templatetype == 'BUILTIN'
                             and tmpl.isready]
                 if len(builtins) > 0:
                     self.debug("Found %d builtins ready for use %s" % (len(builtins), builtins))
                     break
             retry -= 1
             delay(60)  # wait a minute for retry
         self.assertNotEqual(retry, 0,
                             "builtIn templates not ready in zone %s" %
                             z.name)
Ejemplo n.º 28
0
 def build(self, wait=20):
     if self.config and self.jobclient:
         while self.jobclient.is_queued_or_running():
             logging.debug("Waiting  %ss for running/queued build to complete"%wait)
             delay(wait)
             
         self.jobclient.invoke(params=self.parseConfigParams())
         self.build_number = self.jobclient.get_last_buildnumber()
         self.paramlist = self.parseConfigParams()
         logging.info("Started build : %d"%self.jobclient.get_last_buildnumber())
         
         while self.jobclient.is_running():
             logging.debug("Polling build status in %ss"%wait)
             delay(wait)
         
         logging.info("Completed build : %d"%self.jobclient.get_last_buildnumber())
         logging.debug("Last Good Build : %d, Last Build : %d, Our Build : \
                       %d"%(self.jobclient.get_last_good_buildnumber(), \
                             self.jobclient.get_last_buildnumber(), \
                             self.build_number))
         if self.jobclient.get_last_good_buildnumber() == self.build_number:
             return self.build_number
         else: #lastGoodBuild != ourBuild
             our_build = self.getBuildWithNumber(self.build_number)
             if our_build is not None and our_build.get_status() == 'SUCCESS':
                 logging.debug("Our builds' %d status %s"%(self.build_number,
                                                           our_build.get_status()))
                 return self.build_number
             else:
                 logging.debug("Our builds' %d status %s"%(self.build_number,
                                                           our_build.get_status()))
                 return 0
Ejemplo n.º 29
0
def distance_parallel():
    """DISTANCE BETWEEN PARALLEL LINE"""
    delay(0.5)
    print("Welcome to Distance between Parallel Line topic!")
    delay(0.5)
    print()
    print("From \"Ax + By + C1 = 0\" and \"Ax + By + C2 = 0\": ")
    print("\t• Input \"A\": ", end="")
    a_parallel = float(input())
    print("\t• Input \"B\": ", end="")
    b_parallel = float(input())
    print("\t• Input \"C1\": ", end="")
    c1_parallel = float(input())
    print("\t• Input \"C2\": ", end="")
    c2_parallel = float(input())
    
    try :
        
        top_parallel = abs(c1_parallel-c2_parallel)
        bottom_parallel = math.sqrt(a_parallel**2+b_parallel**2)
        ans_parallel = top_parallel/bottom_parallel
        print()
        print("Distance between line %sx%sy%s and line %sx%sy%s = 0  is %.2f"\
            %(a_parallel, line_made(b_parallel), line_made(c1_parallel), a_parallel, line_made(b_parallel), line_made(c2_parallel), ans_parallel))
    except:
        print()
        print("Please input in the correct form")
Ejemplo n.º 30
0
 def test_templateBuiltInReady(self):
     """
     built-in templates CentOS to be ready
     """
     for z in self.zones_list:
         retry = self.retry
         while retry != 0:
             self.debug("Looking for at least one ready builtin template")
             templates = listTemplates.listTemplatesCmd()
             templates.templatefilter = 'featured'
             templates.listall = 'true'
             templates_list = self.apiClient.listTemplates(templates)
             if templates_list is not None:
                 builtins = [
                     tmpl for tmpl in templates_list
                     if tmpl.templatetype == 'BUILTIN' and tmpl.isready
                 ]
                 if len(builtins) > 0:
                     self.debug("Found %d builtins ready for use %s" %
                                (len(builtins), builtins))
                     break
             retry -= 1
             delay(60)  # wait a minute for retry
         self.assertNotEqual(
             retry, 0, "builtIn templates not ready in zone %s" % z.name)
Ejemplo n.º 31
0
 def build(self, wait=20):
     if self.config and self.jobclient:
         while self.jobclient.is_queued_or_running():
             logging.debug("Waiting  %ss for running/queued build to complete"%wait)
             delay(wait)
             
         self.jobclient.invoke(params=self.parseConfigParams())
         self.build_number = self.jobclient.get_last_buildnumber()
         self.paramlist = self.parseConfigParams()
         logging.info("Started build : %d"%self.jobclient.get_last_buildnumber())
         
         while self.jobclient.is_running():
             logging.debug("Polling build status in %ss"%wait)
             delay(wait)
         
         logging.info("Completed build : %d"%self.jobclient.get_last_buildnumber())
         logging.debug("Last Good Build : %d, Last Build : %d, Our Build : \
                       %d"%(self.jobclient.get_last_good_buildnumber(), \
                             self.jobclient.get_last_buildnumber(), \
                             self.build_number))
         if self.jobclient.get_last_good_buildnumber() == self.build_number:
             return self.build_number
         else: #lastGoodBuild != ourBuild
             our_build = self.getBuildWithNumber(self.build_number)
             if our_build is not None and our_build.get_status() == 'SUCCESS':
                 logging.debug("Our builds' %d status %s"%(self.build_number,
                                                           our_build.get_status()))
                 return self.build_number
             else:
                 logging.debug("Our builds' %d status %s"%(self.build_number,
                                                           our_build.get_status()))
                 return 0
Ejemplo n.º 32
0
def main():
	print("Write your shit here")
	setupstuff()
	print(stsec)
	print(stmin)
	print(sthours)
	time.delay(1)
Ejemplo n.º 33
0
def prepareManagementServer(mgmt_host):
    """
    Prepare the mgmt server for a marvin test run
    """
    if _isPortListening(host=mgmt_host, port=22, timeout=10) \
            and _isPortListening(host=mgmt_host, port=3306, timeout=10) \
            and _isPortListening(host=mgmt_host, port=8080, timeout=300):
        delay(120) #introduce dumb delay
        mgmt_ip = macinfo[mgmt_host]["address"]
        mgmt_pass = macinfo[mgmt_host]["password"]
        with contextlib.closing(sshClient.SshClient(mgmt_ip, 22, "root", mgmt_pass)) as ssh:
            # Open up 8096 for Marvin initial signup and register
            ssh.execute("mysql -ucloud -pcloud -Dcloud -e\"update configuration set value=8096 where name like 'integr%'\"")
            ssh.execute("service cloudstack-management restart")
    else:
        raise Exception("Reqd services (ssh, mysql) on management server are not up. Aborting")

    if _isPortListening(host=mgmt_host, port=8096, timeout=300):
        logging.info("All reqd services are up on the management server %s"%mgmt_host)
        testManagementServer(mgmt_host)
        return
    else:
        with contextlib.closing(sshClient.SshClient(mgmt_ip, 22, "root", mgmt_pass)) as ssh:
            # Force kill java process
            ssh.execute("killall -9 java; service cloudstack-management start")

    if _isPortListening(host=mgmt_host, port=8096, timeout=300):
        logging.info("All reqd services are up on the management server %s"%mgmt_host)
        testManagementServer(mgmt_host)
        return
    else:
        raise Exception("Reqd service for integration port on management server %s is not open. Aborting"%mgmt_host)
Ejemplo n.º 34
0
def step_impl(context,celery_end):
    delay(2)
    context.celery_end          =   celery_end
    if context.celery_end!='None':
        context                 =   get_task_results(context)
        tasks                   =   context.celery_results.task_name.unique().tolist()
        all_task_events         =   context.celery_results.task_name.tolist()
        assert_that(all_task_events.count(celery_end)>0,equal_to(True))
Ejemplo n.º 35
0
def ViraEsquerda(tempo = 3):                            #FUNÇÃO DE CONTROLE DO MOTOR. PINOS:      4,7|VELOCIDADE      2,3|MOTORD    5,6|MOTORE
    AP['pino4'].write(0.4)
    AP['pino7'].write(0.4)
    AP['pino2'].write(0)
    AP['pino3'].write(1)
    AP['pino5'].write(1)
    AP['pino6'].write(0)
    delay(tempo)
Ejemplo n.º 36
0
def SegueReto(tempo):
    AP['pino4'].write(0.4)
    AP['pino7'].write(0.4)
    AP['pino2'].write(0)
    AP['pino3'].write(1)
    AP['pino5'].write(0)
    AP['pino6'].write(1)
    delay(tempo)
Ejemplo n.º 37
0
 def handle_error(self, irc_msg):
     if irc_msg.body[0] == "ip (Excess Flood)":
         irc_msg.irc_server.delay += irc_msg.irc_server.delay_incr
         return False    # Cause the connection to be dropped
     if irc_msg.body[0] == "reconnect too fast.":
         time.delay(10)
         return False    # Cause the connection to be dropped
     return True
Ejemplo n.º 38
0
 def run(self):
     while not self.finished:
         snr = tb.digital_mpsk_snr_est_cc_0.snr()
         print " -------------------------------------------------"
         print "SNR : "
         print snr
         print "--------------------------------------------------"
         time.delay(10)
Ejemplo n.º 39
0
 def checkIfHostsUp(self,hosts):
     self.waitForHostReady(hosts)
     delay(30)
     # Re-check because ssh connect works soon as post-installation occurs. But
     # server is rebooted after post-installation. Assuming the server is up is
     # wrong in these cases. To avoid this we will check again before continuing
     # to add the hosts to cloudstack
     self.waitForHostReady(hosts)
Ejemplo n.º 40
0
def Para(tempo):
    AP['pino4'].write(0)
    AP['pino7'].write(0)
    AP['pino2'].write(0)
    AP['pino3'].write(0)
    AP['pino5'].write(0)
    AP['pino6'].write(0)
    delay(tempo)
Ejemplo n.º 41
0
def SegueTras(tempo):
    AP['pino4'].write(velocidade)
    AP['pino7'].write(velocidade)
    AP['pino2'].write(1)
    AP['pino3'].write(0)
    AP['pino5'].write(1)
    AP['pino6'].write(0)
    delay(tempo)
Ejemplo n.º 42
0
def refreshHosts(cscfg, hypervisor="xen", profile="xen602"):
    """
    Removes cobbler system from previous run. 
    Creates a new system for current run.
    Ipmi boots from PXE - default to Xenserver profile
    """
    for zone in cscfg.zones:
        for pod in zone.pods:
            for cluster in pod.clusters:
                for host in cluster.hosts:
                    hostname = urlparse.urlsplit(host.url).hostname
                    logging.debug("attempting to refresh host %s" % hostname)
                    # revoke certs
                    bash("puppet cert clean %s.%s" % (hostname, DOMAIN))
                    # setup cobbler profiles and systems
                    try:
                        hostmac = macinfo[hostname]["ethernet"]
                        hostip = macinfo[hostname]["address"]
                        bash(
                            "cobbler system remove \
                             --name=%s"
                            % (hostname)
                        )
                        bash(
                            "cobbler system add --name=%s --hostname=%s \
                             --mac-address=%s --netboot-enabled=yes \
                             --enable-gpxe=no --profile=%s --server=%s \
                             --gateway=%s"
                            % (
                                hostname,
                                hostname,
                                hostmac,
                                profile,
                                cobblerHomeResolve(hostip, param="cblrgw"),
                                cobblerHomeResolve(hostip),
                            )
                        )

                        bash("cobbler sync")
                    except KeyError:
                        logging.error("No mac found against host %s. Exiting" % hostname)
                        sys.exit(2)
                    # set ipmi to boot from PXE
                    try:
                        ipmi_hostname = ipmiinfo[hostname]
                        logging.debug("found IPMI nic on %s for host %s" % (ipmi_hostname, hostname))
                        bash(
                            "ipmitool -Uroot -P%s -H%s chassis bootdev \
                             pxe"
                            % (IPMI_PASS, ipmi_hostname)
                        )
                        bash("ipmitool -Uroot -P%s -H%s chassis power cycle" % (IPMI_PASS, ipmi_hostname))
                        logging.debug("Sent PXE boot for %s" % ipmi_hostname)
                    except KeyError:
                        logging.error("No ipmi host found against %s. Exiting" % hostname)
                        sys.exit(2)
                    yield hostname
    delay(5)  # to begin pxe boot process or wait returns immediately
Ejemplo n.º 43
0
def main():
	compass = i2c_hmc5883l.i2c_hmc5883l(4)	# 4 is because /dev/i2c-4 is the GPIO I2C bus on the odroid
	compass.setContinuousMode()
	compass.setDeclination(0, 6)
	
	# Get data from compass 10 times and print
	for i in range(10):
		print(compass)
		time.delay(1)
Ejemplo n.º 44
0
 def dispatch(self, request):
     self.publisher.publish(request.serialize(), 'Dispatcher received request')
     self.func_list.append(request.function)
     if request.function == jsonrpc.SERVER_READY:
         return request.respond(True)
     elif request.function == 'long_test':
         time.delay(5)
         return request.respond(True)
     else:
         return request.respond(self.default_ret)
Ejemplo n.º 45
0
def main():
    """Funcion principal del juego"""

    can_continue = True
    suma_jugador = 0
    suma_maquina = 0

    print SALUDO # Saludamos al usuario

    cards = barajar_cartas() # Barajamos las cartas

    print PLAYER_TIME

    while can_continue:

        card = dar_carta(cards) # Preguntamos al usuario si quiere carta

        if card:
            print "It is the card %s and costs %.1f" %(str(card), CARTAS[card])
            suma_jugador += CARTAS[card] # Sumamos los puntos de la carta tocada.
            
            if suma_jugador > 7.5: # Si se pasa del limite, el usuario pierde y acaba el juego.
                print GAME_OVER
                return
                
        else: #Si no quiere carta, turno de la maquina
            can_continue = False

    can_continue = True

    # Turno de la maquina
    print MACHINE_TIME

    while can_continue:

        card = cards.pop() # Cogemos carta

        if (suma_maquina + CARTAS[card] > 7.5):
            can_continue = False # Si se pasa del limite, la maquina para de jugar
        else:
            print "The machine takes the card %s that it costs %.1f" %(str(card), CARTAS[card])
            suma_maquina += CARTAS[card]
        
        delay(2) # Esperamos 2 segundos para que escoja de nuevo otra carta la maquina

    # Anunciamos el ganador
    print WINNER_TIME
    print "And the winner is...",
    if (suma_jugador > suma_maquina):
        print "the player 1 with %.1f points vs %.1f points of the machine!!" %(suma_jugador, suma_maquina)
    elif (suma_jugador == suma_maquina):
        print "That was a draw!!! No winner this time, more lucky next time :) "
    else:
        print "the machine with %.1f points vs %.1f points of the player 1!!" %(suma_maquina, suma_jugador)
def getCSCode(inp_dict):
    path = inp_dict['path'] 
    os.chdir(path)
    os.system("killall -9 java")
    print "*******************************Restarting Management Server****************************************"  
    delay(30)

    if (str(inp_dict['noSimulator']).lower()=="true"):
        os.system("mvn -pl :cloud-client-ui jetty:run &")
    else:
       os.system("mvn -Dsimulator -pl client jetty:run &")
 def wait_for_page(self,timeout_seconds=45):
     """
     Include start page to confirm change started ??
     """
     end                     =   TIME() + timeout_seconds
     delay(                      1)
     while TIME()<end:
         status              =   self.window.execute_script("return document.readyState")
         if status=='complete':
             return
         else:
             delay(              2)
Ejemplo n.º 48
0
 def isPortListening(host, port, timeout=120):
     """
     Scans 'host' for a listening service on 'port'
     """
     tn = None
     while timeout != 0:
         try:
             tn = telnetlib.Telnet(host, port, timeout=timeout)
             timeout = 0
         except Exception, e:
             logging.debug("Failed to telnet connect to %s:%s with %s" % (host, port, e))
             delay(5)
             timeout = timeout - 5
Ejemplo n.º 49
0
 def isManagementServiceStable(self,ssh=None, timeout=300, interval=5):
    self.logger.info("Waiting for cloudstack-management service to become stable")
    if ssh is None:
       return False
    while timeout != 0:
       cs_status = ''.join(ssh.execute("service cloudstack-management status"))
       self.logger.debug("[-%ds] Cloud Management status: %s"%(timeout, cs_status))
       if cs_status.find('running') > 0:
           pass
       else:
           ssh.execute("killall -9 java; mvn -Dsimulator -pl client jetty:run")
       timeout = timeout - interval
       delay(interval)
Ejemplo n.º 50
0
def isManagementServiceStable(ssh=None, timeout=300, interval=5):
    logging.info("Waiting for cloudstack-management service to become stable")
    if ssh is None:
        return False
    while timeout != 0:
        cs_status = ''.join(ssh.execute("service cloudstack-management status"))
        logging.debug("[-%ds] Cloud Management status: %s"%(timeout, cs_status))
        if cs_status.find('running') > 0:
            pass
        else:
            ssh.execute("service cloudstack-management restart")
        timeout = timeout - interval
        delay(interval)
def run_game():
    global k1
    global k2
    global k3
    global k4
    global ksp
    global p1
    global p2
    global p3
    global p4
    global psp
    global v
    draw()
    while True:
        time_passed = clock.tick(100)
        pygame.event.pump()
        v=ser.readline(1)
        if(v=='f'):
            pygame.mixer.music.play()
            time.delay(2)
            pygame.mixer.music.pause()
        key = pygame.key.get_pressed()
        if key[pygame.K_LEFT]:
            k4=1
        else:
            k4=0
        if key[pygame.K_UP]:
            k1=1
        else:
            k1=0
        if key[pygame.K_RIGHT]:
            k2=1
        else:
            k2=0
        if key[pygame.K_DOWN]:
            k3=1
        else:
            k3=0
        if key[pygame.K_SPACE]:
            ksp=1
        else:
            ksp=0
        if key[pygame.K_ESCAPE]:
			sys.exit()
        if k1!=p1 or k2!=p2 or k3!=p3 or k4!=p4 or ksp!=psp:
            draw()
        p1=k1
        p2=k2
        p3=k3
        p4=k4
        psp=ksp
Ejemplo n.º 52
0
 def totalUpdate(self):
     curRem = self.rem
     while True:
         if curRem != self.rem or self.rem == self.total:
             curRem = self.rem
             if self.rem != 0:
                 delay(0.5)
                 w = Label(self.root,text=str(self.total-self.rem)+" out of "+str(self.total)+" sent")
             else:
                 w = Label(self.root,text="process completed")
                 w.place(x=116,y=45)
                 break
             w.place(x=116,y=45)
         delay(self.delay/4)
Ejemplo n.º 53
0
 def isPortOpen(host, port=22):
     """
     Checks if there is an open socket on specified port. Default is SSH
     """
     while True:
         channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         channel.settimeout(20)
         try:
             logging.debug("Attempting port=%s connect to host %s" % (port, host))
             err = channel.connect_ex((host, port))
         except socket.error, e:
             logging.debug("encountered %s retrying in 5s" % e)
             delay(5)
         finally:
    def randomize_keystrokes(self,keys,element,**kwargs):
        T                                   =   {'shortest_delay_ms'        :   500,
                                                 'longest_delay_ms'         :   1200,
                                                }
        for k,v in kwargs:
            T.update(                           { k                         :   v })
        pauses                              =   map(lambda s: randrange(
                                                    T['shortest_delay_ms'],
                                                    T['longest_delay_ms'])//float(100),keys)

        for i in range(len(keys)):
            action_chain                    =   self.Actions(self.window)
            action_chain.send_keys_to_element(  element,keys[i]).perform()
            delay(                              pauses[i])
        return True
Ejemplo n.º 55
0
 def _isPortOpen(self,hostQueue, port=22):
     """
     Checks if there is an open socket on specified port. Default is SSH
     """
     ready = []
     host = hostQueue.get()
     while True:
        channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        channel.settimeout(20)
        try:
           self.logger.debug("Attempting port=%s connect to host %s"%(port, host))
           err = channel.connect_ex((host, port))
        except socket.error, e:
               self.logger.debug("encountered %s retrying in 5s"%e)
               err = e.errno
               delay(5)
        finally:
Ejemplo n.º 56
0
 def test_systemVmReady(self):
     """
     system VMs need to be ready and Running for each zone in cloudstack
     """
     for z in self.zones_list:
         retry = self.retry
         while retry != 0:
             self.debug("looking for system VMs in zone: %s, %s" % (z.id, z.name))
             sysvms = listSystemVms.listSystemVmsCmd()
             sysvms.zoneid = z.id
             sysvms.state = 'Running'
             sysvms_list = self.apiClient.listSystemVms(sysvms)
             if sysvms_list is not None and len(sysvms_list) == 2:
                 assert len(sysvms_list) == 2
                 self.debug("found %d system VMs running {%s}" % (len(sysvms_list), sysvms_list))
                 break
             retry -= 1
             delay(60)  # wait a minute for retry
         self.assertNotEqual(retry, 0, "system VMs not Running in zone %s" % z.name)
Ejemplo n.º 57
0
    def eventRatePause(self):
        """This is the main method that should be called each time an event is
           to occur.  It will block internally until it is time for
           the next event to occur.
        """
        if not hasattr(self, '_curRate'):
            self._runningCount += 1

            # runningCount is the total # since the last time it was
            # zeroed, so it's not just wthin the last second, but it does
            # provide a threshold above which the actual rate should be
            # observed and possibly throttled.  This will begin to take an
            # interest in the actual rate when the runningCount reaches an
            # arbitrary 70% of the maximum rate.
            if self._runningCount < (self._maxRate * 0.70):
                return

            self._curRate = 0
            self._timeMark = datetime.now()
            self._goodMarks = 0
            return

        self._curRate += 1
        newT = datetime.now()
        deltaT = newT - self._timeMark

        if deltaT < timedelta(seconds=1):
            return

        rate = self._curRate / timePeriodSeconds(deltaT)

        if rate > self._maxRate:
            # Slow down a little
            delay(0.1)
            self._goodMarks = 0
            return

        self._goodMarks += 1
        if self._goodMarks > self._maxRate:
            delattr(self, '_curRate')
            self._runningCount = 0
            return
Ejemplo n.º 58
0
 def _isPortListening(self,host, port, timeout=120):
   """
   Scans 'host' for a listening service on 'port'
   """
   tn = None
   while timeout != 0:
      try:
         self.logger.debug("Attempting port=%s connect to host %s"%(port, host))
         tn = telnetlib.Telnet(host, port, timeout=timeout)
         timeout = 0
      except Exception, e:
         self.logger.debug("Failed to telnet connect to %s:%s with %s"%(host, port, e))
         delay(5)
         timeout = timeout - 5
      if tn is None:
         self.logger.error("No service listening on port %s:%d"%(host, port))
         delay(5)
         timeout = timeout - 5
      else:
          self.logger.info("Unrecognizable service up on %s:%d"%(host, port))
          return True
Ejemplo n.º 59
0
def updateScreen():
	leftGrid, rightGrid, leftTitle, rightTitle = defenseGrid[player2], defenseGrid[player1], "Enemy Fleet", "Your Fleet"
	title = "=== TimoTree Battleship ==="
	ruler = ' '.join([chr(i + 65) for i in range(gridSize)])
	legend = ('Empty', 'Miss', 'Ship', 'Hit', 'Legend:')
	histName = 'History'
	global screenWidth, screenHeight, history, refresh
	b4Width, b4Height, screenWidth, screenHeight = screenWidth, screenHeight, *get_terminal_size()
	if screenWidth<72 or screenHeight<24 or b4Width != screenWidth or b4Height != screenHeight:
		if screenWidth<72 or screenHeight<24:
			printLoc("Please enlarge your terminal", 0, 0)
		refresh = True
		while screenWidth<72 or screenHeight<24 or b4Width != screenWidth or b4Height != screenHeight:
			b4Width, b4Height, screenWidth, screenHeight = screenWidth, screenHeight, *get_terminal_size()
			delay(0.1)
	leftX, legendX, rightX = screenWidth // 4 - (gridSize + 1), int(screenWidth / 2 - len(legend[-1]) / 2) - 1, screenWidth * 3 // 4 - (gridSize + 1)
	if refresh:
		from os import name, system
		print('\033[s\033[2J')
		system('cls' if name == 'nt' else 'clear')
		print('\033[u')
		printLoc(colors['interface'] + title, int(screenWidth / 2 - len(title) / 2), 2)
		printLoc(colors['interface'] + leftTitle, int(screenWidth / 4 - len(leftTitle) / 2) - 1, 4)
		printLoc(colors['interface'] + rightTitle, int(screenWidth * 3 / 4 - len(rightTitle) / 2), 4)
		printLoc(colors['interface'] + ruler, leftX + 2, 6)
		printLoc(colors['interface'] + ruler, rightX + 2, 6)
		printLoc(colors['interface'] + legend[-1], legendX + 1, 7)
		for i in range(len(cell)):
			printLoc(cell[i] + " - " + legend[i], legendX, i + 8)
	for y in grid:
		printLoc(colors['interface'] + str(y), leftX, 7+y)
		printLoc(colors['interface'] + str(y), rightX, 7+y)
		for x in grid:
			printLoc(cell[{ship:empty}.get(leftGrid[x][y], leftGrid[x][y])], leftX+(x+1) * 2, 7+y)
			printLoc(cell[rightGrid[x][y]], rightX+(x+1) * 2, 7+y)
	printLoc('\033[J' + colors['prompt'] + histName, int(screenWidth / 2 - len(histName) / 2), gridSize + 11)
	for place, action, color, y in zip(*zip(*reversed(history)), range(gridSize + 12, screenHeight)):
		message = '{}: {}'.format(place, action)
		printLoc(color + message, int(screenWidth / 2 - len(message) / 2), y)
	refresh = False