Ejemplo n.º 1
0
 def turn(self, s, is_left, angle=0.05):
     first = self.left if is_left else self.right
     second = self.right if is_left else self.left
     first.drive(angle)
     end = time.time() + s
     while time.time() < end:
         sleep(0.25)
         first.drive(angle/10)
     second.drive(angle)
Ejemplo n.º 2
0
def wiggle(s=0.1):
    """
    Drive across the table with a little wiggle in yo ass
    """
    with safe_car() as car:
        car.start(s)
        car.turn_left(s)
        sleep(s)
        car.turn_right(s)
        sleep(s)
        loop()
Ejemplo n.º 3
0
Archivo: core.py Proyecto: nzcv/chtf
	def get_contents(self, boards_cache_dir_path, dl_sleep_time_sec):
		cache_path = os.path.join(boards_cache_dir_path, self.name)
		if in_cache(cache_path):
			return get_from_cache(cache_path)
		else:
			try:
				data = get_board.main(self.name)
			except get_board.DownloadError as err:
				raise DownloadError(err)
			utils.sleep(dl_sleep_time_sec)
			store_in_cache(data, cache_path)
			return data
Ejemplo n.º 4
0
Archivo: cli.py Proyecto: nzcv/chtf
def mainloop(options, profile):
    log.info("Executing mainloop() ...")
    board_cache_dir_path = os.path.join(options["cache_dir_path"], "boards")

    if options["use_cache_on_first_run"]:
        log.info(
            "--use-cache flag enabled, not removing the "
            " contents of cache directory {}.".format(board_cache_dir_path)
        )
    else:
        try:
            utils.delete_files_in_dir(board_cache_dir_path)
        except FileNotFoundError:
            log.info(
                "FileNotFoundError while trying to remove the contents "
                "of cache directory {}.".format(board_cache_dir_path)
            )
        else:
            log.info("Successfully removed contents of cache directory {}.".format(board_cache_dir_path))

    dl_error_count = 0
    while True:
        if dl_error_count >= 10:
            print()
            error_wait_seconds = 60
            log.warning(
                "Failed to fetch data 10 times, waiting " "{} seconds before retrying ...".format(error_wait_seconds)
            )
            utils.sleep(error_wait_seconds)
            dl_error_count = 0
        utils.clear_terminal()
        log.info("Executing main() ...")
        try:
            main(options, profile)
        except core.DownloadError as err:
            dl_error_count += 1
            log.error("{}. Retrying ...".format(err))
            continue
        except core.ConfigError as err:
            log.critical("{}.".format(err))
            utils.exit(1)
        else:
            log.info("main() executed successfully.")
        if options["single_run"]:
            log.info("--single-run flag enabled, exiting ...")
            print()
            utils.exit(0)
        dl_error_count = 0
        utils.sleep(options["refresh_time"])
        utils.delete_files_in_dir(board_cache_dir_path)
Ejemplo n.º 5
0
    def _cb_restablish_session(self):
        """Re-establish a new session, and recreate ephemerals and watches.
        """
        # Reconnect
        while 1:
            log.debug("Reconnect loop - connect timeout %d",
                      self._connect_timeout)

            # If we have some failures, back off
            if self._backoff_seconds:
                log.debug("Backing off reconnect %d" % self._backoff_seconds)
                yield sleep(self._backoff_seconds)

            # The client was explicitly closed, abort reconnect.
            if self.handle is None:
                returnValue(self.handle)
            try:
                yield self.connect(timeout=self._connect_timeout)
                log.info("Restablished connection")
                self._last_reconnect = time.time()
            except ConnectionTimeoutException:
                log.debug("Timeout establishing connection, retrying...")
            except zookeeper.ZooKeeperException, e:
                log.exception("Error while connecting %r %s" % (e, e))
            except Exception, e:
                log.info("Reconnect unknown error, aborting: %s", e)
                raise
Ejemplo n.º 6
0
    def _cb_connection_error(self,  client, error):
        """Convert session expiration to a transient connection error.

        Dispatches from api usage error.
        """
        if not is_session_error(error):
            raise error
        log.debug("Connection error detected, delaying retry...")
        yield sleep(1)
        raise zookeeper.ConnectionLossException
Ejemplo n.º 7
0
    def deamon_read(self):
        while self.status == 'started':
            size = len(self.buffer)
            if size > self.buffer_max_size :
                remove_count = size - self.buffer_max_size
                remove_count += self.buffer_max_size / 5
                for idx in self.buffer_record[:remove_count] :
                    del self.buffer[idx]
                del self.buffer_record[:remove_count]

            yield sleep(10)
Ejemplo n.º 8
0
 def run(self):
     if self._conn_count: return
     subs = yield Subscription.get_list()
     for sub in subs:
         while self._conn_count >= self.MAX_CONNECTIONS_COUNT:
             self.debug("MAX CONNECTIONS: %d, WAIT" % self._conn_count)
             yield utils.sleep(1)
         self._conn_count += 1
         parser = parsers[sub["parser"]]
         if parser.is_supported("last_modified"):
             self.process_last_modified(sub)
         else:
             self.process_page(sub, None)
Ejemplo n.º 9
0
 def end_exercise(self, thumbs=True): 
     
     result = self.ImgA.get_result()
     
     self.logger.debug("got score from ImgA, points: %s, wrongs: %s" % (result[0], result[1]))
     self.totalwrongs += result[1]
     self.dbscore = (result[0] - result[1]) * self.level
     self.score += self.dbscore * 10
     self.scoredisplay.set_score(self.score)
     # TODO: we have hardcoded a check for the amount of wrongs iso rc file values.
     if self.totalwrongs < 4:
         levelup = 1
     else:
         levelup = 0
     self.actives.empty()
     if self.currentlist and not self.AreWeDT:
         self.previous_screen = pygame.Surface((800, 500))
         surf = pygame.display.get_surface()
         self.previous_screen.blit(surf, (0, 0), (0, self.blit_pos[1], 800, 500))
     utils.sleep(2000)
     if not result[0] == self.LevelScoreHash[self.level]:
         thumbs = False
         self.clear_screen()
     if thumbs:
         self.clear_screen()
         self.ThumbsUp.display_sprite((229, 120))
         utils.sleep(2000)
         self.ThumbsUp.erase_sprite()
     if not self.ImgDiffHash or self.done == int(self.rchash[self.theme]['exercises']):
         self.dbmapper.insert('wrongs', self.totalwrongs)
         if self.AreWeDT:
             self.SPG.tellcore_level_end(level=self.level)
         else:
             self.SPG.tellcore_level_end(store_db=True, \
                                 level=min(6, self.level), \
                                 levelup=levelup)
     else:
         self.start_exercise()
Ejemplo n.º 10
0
Archivo: kisa.py Proyecto: Kagami/kisa
def register_mode():
    db = yield get_db()
    path = os.path.join(os.path.dirname(__file__), "data", "good_servers.txt")
    servers = open(path).read().split()
    while True:
        for server in servers:
            bot = modes.register.RegisterBot(options.verbose)
            try:
                account = yield bot.register_account(server)
            except modes.register.RegisterError:
                pass
            else:
                yield db.add_account(*account)
        yield utils.sleep(1)
Ejemplo n.º 11
0
    def get_peer_list(self, url, data):
        if self.status == 'stopped':
            return
        
        try:
            page = yield getPage(url + '?' + data)

        except Exception as error:
            logging.error('Failed to connect to tracker: %s' % url)

            yield sleep(self.interval)
            self.get_peer_list(url, data)

        else:
            try:
                res = bdecode(page)
            except BTFailure:
                logging.error("Received an invalid peer list from the tracker: %s" % url)
            else:
                if len(res) == 1:
                    return

                peers = res['peers']
                peers_list = []
                while peers:
                    addr = socket.inet_ntoa(peers[:4])
                    port = struct.unpack('!H', peers[4:6])[0]
                    peers_list.append((addr, port))
                    peers = peers[6:]

                self.btm.add_peers(peers_list)
            
                interval = self.interval

                yield sleep(interval)
                self.get_peer_list(url, data)
Ejemplo n.º 12
0
    def connect_retry(self, connector):
        addr = self.get_peer_addr(connector)

        if addr in self.peers_retry:
            retry = self.peers_retry[addr]
        else:
            retry = 0

        if retry > 50:
            self.peers_failed.add(addr)
            self.peers_connecting.remove(addr)
            del self.peers_retry[addr]
        else:
            yield sleep(5)
            connector.connect()
            retry += 1
            self.peers_retry[addr] = retry
Ejemplo n.º 13
0
def pollStepAction(api, stepActionID):
    """
    Poll the given stepActionID until all the consituent steps are
    complete, then fire the returned deferred.
    """
    numStepActions = 0
    completedStepActions = None
    while completedStepActions < numStepActions:
        response = yield api.pollStepAction(StepActionID=stepActionID)
        steps = response.find("Steps").getchildren()
        numStepActions = 0
        completedStepActions = 0
        print "\n"
        for step in steps:
            status = step.find("Description").text.ljust(40, '.')
            numStepActions += 1
            if step.find("CompleteDate") is not None:
                completedStepActions += 1
                status += "FINISHED"
            else:
                status += "PENDING"
            print status
        yield utils.sleep(1)
Ejemplo n.º 14
0
def resign(account, controller):
    updateAuth(account, 'owner', '', controller)
    updateAuth(account, 'active', 'owner', controller)
    sleep(1)
    run(config['cleos']['path'] + 'get account ' + account)
def main():
    currentTime = time.strftime('%Y_%m_%d_%H_%M', time.localtime(time.time()))
    PORT = 4723 + int(sys.argv[1]) - 1
    BOOTSTRAP = 2251 + int(sys.argv[1]) - 1
    #UDID = 101 + int(sys.argv[1]) - 1
    for key in data.ACCOUNT_INFO:
        data.queue.put(data.ACCOUNT_INFO[key])
    start_thread_list = list()
    appium_thread_list = list()
    operate_thread_list = list()
    adblogcat_thread_list = list()
    machineUdid_list = list()
    machinePort_list = list()
    print 'before'
    #id = os.getpid()
    #cmd = "kill -9 %d" % int(pid)
    #os.system(cmd)
    #targetApk = input("choose the app you want to operate: 1. qzone  2. baidu_tieba \n")
    #operateType = APP_MAP[targetApk]
    lock = path.getPath('root') + 'boot.lock'
    #设置启动文件锁
    while (os.path.isfile(lock) == True):
        print "其他模拟器正在启动,10s后启动..."
        utils.sleep(10)
    fp = open(lock, 'w')
    fp.close()

    # 启动模拟器
    for device_name in DEVICE_LIST:
        start_thread_list.append(
            threading.Thread(target=start_machine, args=(device_name, )))

    for thread in start_thread_list:
        thread.start()
    print "start virtual"
    utils.sleep(40)

    device_id = ''
    #popen = subprocess.Popen("adb devices",shell = True)
    #str = popen.stdout
    # 启动appium_server
    for device_name in DEVICE_LIST:
        #machineUdid = '192.168.57.{}:5555'.format(UDID)
        machineUdid = getDevice()
        device_id = machineUdid
        machineUdid_list.append(machineUdid)
        machinePort = '{}'.format(PORT)
        machinePort_list.append(machinePort)
        machineBootStrap = '{}'.format(BOOTSTRAP)
        appium_thread_list.append(
            threading.Thread(target=start_appium_server,
                             args=(machinePort, machineBootStrap,
                                   machineUdid)))
        PORT = PORT + 1
        BOOTSTRAP = BOOTSTRAP + 1
        #UDID = UDID + 1
    #删除文件锁,同时将ip存入文件中
    try:
        res = os.remove(lock)
    except:
        pass
    device_name = DEVICE_LIST[0]
    fp = open(path.getPath("root") + device_name + '.info', 'w')
    fp.write(device_id)
    fp.close()

    print('start adblogcat')
    for udid in machineUdid_list:
        fileName = path.getPath("log") + device_name + '_{}_{}'.format(
            udid, currentTime)
        adblogcat_thread_list.append(
            threading.Thread(target=start_adb_logcat, args=(udid, fileName)))
    for thread in adblogcat_thread_list:
        thread.start()
    print('start appium')
    for thread in appium_thread_list:
        thread.start()

    utils.sleep(40)  ###appium启动慢

    i = 0
    for id in DEVICE_LIST:
        operate_thread_list.append(
            threading.Thread(target=APP_MAP.get(int(sys.argv[1])),
                             args=(machinePort_list[i], machineUdid_list[i])))
        i = i + 1

    utils.sleep(10)

    for thread in operate_thread_list:
        thread.start()

    for thread in operate_thread_list:
        thread.join()
    utils.sleep(10)
    for start in start_machine_list:
        cmd = "kill -9 %d" % int(start)
        #print "执行"
        os.system(cmd)

    for start in start_appium_list:
        cmd = "kill -9 %d" % int(start)
        #print "执行"
        os.system(cmd)
    for start in start_adb_list:
        cmd = "kill -9 %d" % int(start)
        #print "执行"
        os.system(cmd)
    pid = os.getpid()
    cmd = "kill -9 %d" % int(pid)
    os.system(cmd)
Ejemplo n.º 16
0
 def pause(self, s):
     self.stop()
     sleep(s)
     self.start()
Ejemplo n.º 17
0
 def deamon_write(self):
     while self.status == 'started':
         self.__thread_write()
         yield sleep(2)
Ejemplo n.º 18
0
 def drive(self, s, wait=None):
     self.on()
     sleep(s)
     self.off()
     if wait:
         sleep(wait)
Ejemplo n.º 19
0
 def conncect_peers(self, peers):
     for addr, port in peers:
         reactor.connectTCP(addr, port, self)
         yield sleep(0)
Ejemplo n.º 20
0
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.verbose)

    # Setup logging
    setup_logging(level=args[LOG_LEVEL])

    http = Flask(__name__)

    @http.route("/count")
    def val_count():
        global count
        return "Read {0} values".format(count)

    def read_values():
        global count
        while True:
            print("Got location: {0}".format(client.get_xy()))
            count += 1

    # Start client
    with LocationClient(args[GRPC_HOST]) as client:

        # Run read_values in a thread
        count = 0
        Thread(target=read_values).start()

        # Run HTTP server in a thread
        Thread(target=http.run, kwargs={"port": 8080}).start()

        sleep()
Ejemplo n.º 21
0
def main():
    secret_santa_setup = setup()
    fail_count = 0
    while fail_count <= 3:
        secret_santa = allocate_santas(secret_santa_setup)
        if not check(secret_santa):
            fail_count += 1
            if fail_count == 3:
                sleep(1)
                print('faillllure ....')
                sleep(1)
                print('tried 3 times ..')
                sleep(1)
                print('giving up now ..')
                sleep(2)
                print('\nit might not be possible with that setup ...')
                sleep(2)
                if secret_santa.unique_recipients:
                    print(
                        '\ntry again without enfocing unique recipients ...\n\n'
                    )
                    sleep(5)
                return
            clear()
            print('\ntrying again ...')
            sleep(4)
        else:
            break
    sleep(1)
    print("time to see who got who .......\n")
    sleep(1)

    show(secret_santa)

    clear()
    print("\nok.. that's everyone ..")
    sleep(2)

    see_again(secret_santa)
Ejemplo n.º 22
0
            print "youtube打开应用失败,两秒后再次尝试"
            utils.sleep(2)
            if(j == 0):
                return
    utils.sleep(15)


    try:
        subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 300 500 100 500", shell = True)
        utils.sleep(5)
        driver.find_element_by_xpath("//android.widget.TextView[contains(@text,'Gaming')]").click()
        utils.sleep(1)
    except Exception,e:
        print str(e)
    subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 300 800 300 200", shell = True)#向上 划一下
    utils.sleep(3)
    subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen tap 10 500", shell = True) #点击进入一个视频
    utils.sleep(5)
    loop = 5
    while loop > 0:
        i = 0
        num = 20###进入 40个视频
        while num > 0:
            try:
                start_loc = driver.find_element_by_class_name("android.widget.Switch").location;
                print str(start_loc)
                x = start_loc['x']
                y = start_loc['y']
                if(y > 700):
                    subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 300 800 300 700", shell = True)#向上 划一下
                    continue
Ejemplo n.º 23
0
        self.set_page_load_timeout(180)
        self.is_loaded = True
        self.implicitly_wait(10)
        sleep(2)
        self.maximize_window()

    def get(self, url, xpath='', timeout=180):
        if url[0] == "/":
            host_url = get_host_from_url(self.current_url)
            url = host_url + url[1:]

        if self.current_url != url:
            webdriver.Chrome.get(self, url)
            if xpath:
                WebDriverWait(self, timeout).until(
                    expected_conditions.visibility_of_all_elements_located(
                        (By.XPATH, xpath)))
            return True
        else:
            return False

    def get_version(self):
        return self.capabilities["browserVersion"]


if __name__ == "__main__":
    d = ChromeDriver()
    d.load()
    sleep(1000)
Ejemplo n.º 24
0
    def retrieve_filtered_ids(self, stato_infortunio: StatoInfortunio,
                              locazione: Locazione, settore: Settore):
        """
        Funzione usata per recuperare inizialmente gli id dei casi. Saranno raccolti gli id
        rispetto a:
            1) StatoInfortunio: Grave, Mortale.
            2) Località: NordOvest, NordEst, Centro, Sud e Isole.
            3) Settore: Metallurgia, FabbricazioneMacchine

        La funzione, se conclusa con successo, ritorerà un array di stringhe corrispondenti agli id.
        """
        # Si inizia caricando la pagina.
        self.driver.get(self.initial_search_page_url +
                        str(stato_infortunio.value))
        # Appena caricata, selezioniamo i parametri con cui filtrare la ricerca

        self.driver.find_element_by_id(self.html_id_settore +
                                       str(settore.value)).click()
        sleep(0.1)
        action = ActionChains(self.driver)
        action.click(
            self.driver.find_element_by_id(self.html_id_locazione +
                                           str(locazione.value))).perform()
        self.driver.execute_script(
            '$( document ).ajaxStop(function() { $( "#tabellaRisultatiId" ).addClass("loaded"); } );'
        )

        # Aspettiamo che il contenuto della pagina sia disponibile. Per capire quando il contenuto sia disponibile
        # andiamo a vedere quando la sezione dei filtri viene nascosta.
        WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((
                By.XPATH,
                "//table[@class='table display tabella-base col-md-12 loaded']"
            )))

        # Manteniamo una lista di ID, riferiti agli infortuni con i filtri selezionati.
        ids = []
        last_page = False

        while not last_page:
            page = BeautifulSoup(self.driver.page_source, 'lxml')
            table = page.select("#tabellaRisultatiId tbody tr")

            # Per ogni elemento nella tabella mostrata, salviamo l'ID del caso
            for row in table:
                ids.append(row.contents[0].contents[0].text)
                if int(row.contents[0].contents[0].text
                       ) in self.ids_dataframe["id"].unique():
                    print()

            # Per controllare se abbiamo raggiunto l'ultima pagina, controlliamo che il bottone
            # "avanti" esista e che sia disabilitato
            directional_arrows_ul = page.select("#tabella-1_paginate ul")[0]
            last_page = not directional_arrows_ul.contents or \
                        "disabled" in directional_arrows_ul.contents[2].get('class')

            # Se "avanti" è abilitato...
            if not last_page:
                # Clicchiamo il bottone avanti
                WebDriverWait(self.driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.XPATH,
                         "//div[@id='tabella-1_paginate']/ul/li[3]/a")))
                sleep(0.25)
                self.driver.find_element_by_xpath(
                    "//div[@id='tabella-1_paginate']/ul/li[3]/a").click()
                # E aspettiamo che il contenuto della tabella si aggiorni con la chiamata AJAX
                WebDriverWait(self.driver, 10).until(
                    EC.invisibility_of_element_located(
                        (By.XPATH, "//a[contains(.," + ids[-1] + ")]")))

        return ids
Ejemplo n.º 25
0
    def retrieve_injury_details(self, injury_id, **details):
        """
        Metodo che apre la pagina dell'infortunio specificata da injury_id.
        Questa parte è necessaria per recuperare la descrizione completa,
        più gli ID relativi ai fattori. Con questi ID possiamo poi procedere
        ad eseguire le richieste POST per ottenere i JSON specifici sui
        fattori e sul dettaglio dell'infortunio.

        In details sono contenute:
            - Locazione
            - Settore
            - StatoInfortunio
        """

        # Apriamo la pagina corrispondente all'infortunio
        self.driver.get(self.injury_page_url + str(injury_id))
        page = BeautifulSoup(self.driver.page_source, 'lxml')

        injury_description = \
            page.find("h3", string=self.title_before_description_injury_page) \
                .find_next_sibling() \
                .get_text() \
                .strip()

        factors_ids = [
            tag.get("onclick")[:-1].replace("apriDettagliFattore(", "")
            for tag in page.find_all(
                "button",
                {"onclick": re.compile("apriDettagliFattore\([0-9]{1,6}\)")})
        ]

        factors = []
        for f_id in factors_ids:
            factors.append(self.retrieve_factor(f_id))
            sleep(self.sleep_between_requests)

        response = requests.post(self.injury_json_url, injury_id)
        response = response.json()

        # Il JSON è composto da vari JSON Objects, nella quale gran parte dei valori
        # sono ripetuti (Guardare l'esempio in assets).

        workers = []
        for o in response:
            workers.append(
                Lavoratore(
                    lavoratore_id=o.get("codiceInfortunato"),
                    sesso=o.get("sesso"),
                    nazionalita=o.get("cittadinanza"),
                    tipo_contratto=o.get("rapLav"),
                    mansione=o.get("mansione"),
                    anzianita=o.get("anzianita"),
                    numero_addetti_azienda=parse_int(o.get("numAddetti")),
                    attivita_prevalente_azienda=o.get("attPrev"),
                    sede_lesione=o.get("sedeLesione"),
                    natura_lesione=o.get("naturaLesione"),
                    giorni_assenza_lavoro=parse_int(
                        o.get("numeroGiorniAssenza")),
                    luogo_infortunio=o.get("luogo"),
                    attivita_lavoratore_durante_infortunio=o.get("tipoAtt"),
                    ambiente_infortunio=o.get("agente"),
                    tipo_incidente=o.get("variazEnergia"),
                    incidente=o.get("incidente"),
                    agente_materiale_incidente=o.get("agenteMatInc")))

        return Infortunio(
            id=injury_id,
            stato=StatoInfortunio(details.get("StatoInfortunio")),
            settore_attivita=Settore(details.get("Settore")),
            locazione=Locazione(details.get("Locazione")),
            descrizione=injury_description,
            data=parse_date(response[0].get("dataInfortunio")),
            ora_ordinale=parse_int(response[0].get("oraLavoro")),
            fattori=factors,
            lavoratori=workers,
        )
Ejemplo n.º 26
0
                'crawlerName': 'credible crawler'
            })

        if not source.articles:
            if PY_ENV == 'development':
                print('(ZERO ARTICLES) Source Skipped\n')
            slp_time = insert_log(source_id, 'sourceCrawl', 'error',
                                  float(time.clock() - src_start_time), {
                                      'errorMessage': 'ZERO ARTICLES',
                                      'crawlerName': 'credible crawler'
                                  })
            continue

        for article in source.articles:
            start_time = time.clock()
            sleep(slp_time)

            if PY_ENV == 'development':
                print(article.url)

            insert_log(source_id, 'articleCrawl', 'pending', float(slp_time), {
                'articleUrl': article.url,
                'crawlerName': 'credible crawler'
            })

            if re.search('/(category|gallery|photos?)/', article.url,
                         re.IGNORECASE):
                if PY_ENV == 'development':
                    print('\n(NOT AN ARTICLE PAGE) Skipped: ' +
                          str(article.url) + '\n')
                slp_time = insert_log(
Ejemplo n.º 27
0
 def send_keep_alive(self):
     yield sleep(1.0)
     while self.connected:
         self.send_data('')
         yield sleep(1.0)
def main():
    while (True):
        utils.sleep(2)
        detect()
Ejemplo n.º 29
0
import toml
import random
from utils import retry, firstProducer, numProducers, accounts, listProducers, sleep, vote

config = toml.load('./config.toml')

def proxyVote(b, e):
    vote(firstProducer, firstProducer + 1)
    proxy = accounts[firstProducer]['name']
    retry(config['cleos']['path'] + 'system regproxy ' + proxy)
    sleep(1.0)
    for i in range(b, e):
        voter = accounts[i]['name']
        retry(config['cleos']['path'] + 'system voteproducer proxy ' + voter + ' ' + proxy)

if __name__ == '__main__':
    proxyVote(0, 0 + config['general']['num_voters'])
    sleep(1)
    listProducers()
    
Ejemplo n.º 30
0
 def loop_save(t=10 * 60):
     while 1:
         proxies = get(URL)
         self.container.update(*proxies)
         sleep(t)
Ejemplo n.º 31
0
def main():
    guard("2")
    utils.sleep(5)
    killGuard()
    utils.sleep(5)
    startup()
def operate(port, udid):
	for key in qqaccounts.ACCOUNT_INFO:
		qqaccounts.queue.put(qqaccounts.ACCOUNT_INFO[key])
	while not qqaccounts.queue.empty():
		accounts.append(qqaccounts.queue.get())
	desired_caps = {}
	desired_caps['platformVersion'] = '4.2'
	desired_caps['deviceName'] = 'useless'
	desired_caps['platformName'] = 'Android'
	desired_caps['appPackage'] = 'com.tencent.mobileqq'
	desired_caps['appActivity'] = 'com.tencent.mobileqq.activity.SplashActivity'
	desired_caps['newCommandTimeout'] = 2000
	driver = webdriver.Remote("http://*****:*****@text,'电话')]").click()
				quit(udid, driver)
			except Exception ,e:
				pass
			if(is_next):
				try:
					print "本次账号:"+str(account)
					pasd = account[1]
					driver.find_element_by_xpath("//android.widget.EditText[contains(@index,0)]").send_keys(account[0])#帐号
					utils.sleep(3)
					driver.find_element_by_xpath("//android.widget.EditText[contains(@index,2)]").clear()#密
					utils.sleep(5)
					driver.find_element_by_xpath("//android.widget.EditText[contains(@index,2)]").send_keys(pasd)#密
					utils.sleep(5)
					driver.find_element_by_xpath("//android.widget.Button[contains(@text,'登 录')]").click()
					utils.sleep(8)
					try:
						driver.find_element_by_xpath("//android.widget.Button[contains(@text,'登 录')]").click()
						utils.sleep(2)
						driver.quit()
						utils.sleep(3)
						driver = webdriver.Remote("http://*****:*****@index,0)]").send_keys(account[0])#帐号
						utils.sleep(3)
						driver.find_element_by_xpath("//android.widget.EditText[contains(@index,2)]").send_keys(pasd)
						utils.sleep(2)
						driver.find_element_by_xpath("//android.widget.Button[contains(@text,'登 录')]").click()
					except:
						pass
					
					utils.sleep(3)
					is_next = False
				except Exception, e:
					print str(e)
Ejemplo n.º 33
0
def skip(driver,udid):
    utils.sleep(20)
    driver.find_element_by_xpath("//android.widget.Button[contains(@text,'验证')]").click()
    utils.sleep(3)
    subprocess.Popen("adb -s '"+ udid +"' shell input keyevent 4", shell = True)
    utils.sleep(2)
    else:
        index = index + 1   ##索引加一,但是可能会超过长度,所以获取账号时需要对其取余
        return accounts[index%len(accounts)]

def quit(udid,driver):
		utils.sleep(1)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen tap 70 100", shell = True)
		utils.sleep(3)
		driver.find_element_by_xpath("//android.widget.TextView[contains(@text, '设置')]").click()

		utils.sleep(3)
		try:
			driver.find_element_by_xpath("//android.widget.TextView[contains(@text, '账号管理')]").click()
		except Exception,e:
			subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen tap 100 200", shell = True)
		utils.sleep(4)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 10 800 10 200", shell = True)
		utils.sleep(1)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 10 800 10 200", shell = True)
		utils.sleep(1)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 10 800 10 200", shell = True)
		utils.sleep(1)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 10 800 10 200", shell = True)
		utils.sleep(1)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 10 800 10 200", shell = True)
		utils.sleep(2)
		subprocess.Popen("adb -s '"+ udid +"' shell input touchscreen swipe 10 800 10 200", shell = True)
		utils.sleep(2)
		try:
			driver.find_element_by_xpath("//android.widget.TextView[contains(@text, '退出当前账号')]").click()
		except:
Ejemplo n.º 35
0
def operate(port, udid):
    print('operate')
    PATH = lambda p: os.path.abspath(
            os.path.join(os.path.dirname(__file__), p)
            )
    print '{} {}'.format(port , udid)

    desired_caps = {}
    desired_caps['platformName'] = 'Android'
    desired_caps['platformVersion'] = '4.2'
    desired_caps['deviceName'] = 'useless'
  #  desired_caps['app'] = PATH('/Users/xujin/Downloads/QQkongjian_95.apk')
    #desired_caps['udid'] = udid
    desired_caps['appPackage'] = 'com.qzone'
    desired_caps['newCommandTimeout'] = 2000
    desired_caps['appActivity'] = 'com.tencent.sc.activity.SplashActivity'
    while True:
        try:
            driver = webdriver.Remote("http://*****:*****@index,0)]").send_keys(account[0])#帐号
                driver.find_element_by_xpath("//android.widget.LinearLayout[1]/android.widget.FrameLayout/android.widget.EditText[contains(@index,0)]").send_keys(account[1])#密码
                utils.sleep(3)
                driver.find_element_by_class_name("android.widget.Button").click()

                isSkip = sys.argv[2]### 说明没有第二个参数,那么直接跳过
                if isSkip == "1":
                    isYanzheng = True
                    while isYanzheng:
                        #utils.sleep(10)
                        print "20miao"
                        try:
                            driver.find_element_by_xpath("//android.widget.Button[contains(@text,'验证')]").click()
                            utils.sleep(3)
                        except:
                            isYanzheng = False
                else:
                    ##print "fhjpeohfpoiehfpoawhjfejhoffhjpeohfpoiehfpoawhjfejhoffhjpeohfpoiehfpoawhjfejhof"
                    try:
                        skip(driver ,udid)
                        continue
                    except Exception ,e:
                        print str(e)
                        pass
            except Exception,e:
                print str(e)
                utils.sleep(3)

            try:
                utils.sleep(2)
                i = 20
                isNext=False
                while(i >1):
                    try:
                        driver.find_element_by_xpath("//android.widget.TextView[contains(@text,'动态')]").click()
                    except:
                        try:
                            driver.find_element_by_xpath("//android.widget.EditText[contains(@index,0)]").location
                            isNext=True
                            break
                        except:
                            subprocess.Popen("adb -s '"+ udid +"' shell input keyevent 4", shell = True)
                    i = i - 1
                    utils.sleep(4)
                if isNext==True:
                    continue
                subprocess.Popen("adb -s '"+ udid +"' shell input keyevent 82", shell = True)
                utils.sleep(2)
                driver.find_element_by_xpath("//android.widget.FrameLayout/android.view.View/android.widget.TextView[contains(@index,1)]").click()
                utils.sleep(5)
            except:
                continue
Ejemplo n.º 36
0
 def start(self, wait=None):
     self.gas.on()
     if wait:
         sleep(wait)
Ejemplo n.º 37
0
        mainErrCnt += 1
        print u'遇到未知错误'
        logging.exception(e)
        utils.append_log('%s re run main for %s time, ' % (ID, mainErrCnt))
        title = '%s re run main for %s time, ' % (ID, mainErrCnt)
        utils.appendUserInfoToDb(config.ID, timeStr, False, title)
        if mainErrCnt > 10:
            utils.sendEmail('%s terminate main' % ID)
            print u'退出程序'
            break
        else:
            if mainErrCnt > 3:
                utils.sendEmail('%s re run main for %s time' %
                                (ID, mainErrCnt))
            utils.sleep(60)

    # 独立的
    if likesErrCnt <= 5:
        try:
            urgentLevel = likesObj.checkCnt(urgentLevel, timeStr)
            likesErrCnt = 0
        except BaseException, e:
            likesErrCnt += 1
            print u'check_likes_num()错误'
            logging.exception(e)
            if likesErrCnt > 5:
                msg = '%s: likesErrCnt > 5, stopped' % ID
                utils.sendEmail(msg)
                print msg
    # MAX_URGENT_LEVEL - urgentLevel = 0 1 2 3 4 5 6 7 8 9
Ejemplo n.º 38
0
def setup():
    secret_santa = SecretSanta()
    year = datetime.date.today().year
    counter = 0
    ok = False

    clear()
    print('\n' + '-' * 40 + " SECRET SANTA {} ".format(year) + '-' * 40 +
          '\n\n')
    sleep(2)
    print("first enter the participating santas ...")
    sleep(3.5)
    print("enter one name at a time ...")
    sleep(2)
    print("or 'done' when finished ...")
    sleep(2)
    print("'delete' will remove the last name ..\n")
    sleep(2)

    while not ok:
        if counter:
            clear()
            print('\n' + '-' * 40 + " SECRET SANTA {} ".format(year) +
                  '-' * 40 + '\n\n')

            if secret_santa.santas:
                print("'done' when finished ..")
                print("'delete' will remove the last name ..\n")
                print('--------- santas ---------')
                for santa in secret_santa.santas:
                    print(santa.name)
                print('--------------------------')
            else:
                print("first enter the participating santas ...")
                print("enter one name at a time ...")
                print("or 'done' when finished ...")
                print("'delete' will remove the last name ..\n")

        santa_name = input('\nenter done to finish >>>>>>> ')
        if santa_name and type(
                santa_name
        ) == str and santa_name not in secret_santa.all_names():
            if santa_name.lower() == "done":
                if len(secret_santa.santas) >= 3:
                    ok = True
                else:
                    print("\ngotta have at least 3 santas yo !!\n")
                    sleep(2)
            elif santa_name.lower() == "delete":
                if len(secret_santa.santas) > 0:
                    del secret_santa.santas[-1]
                else:
                    print('\nthere is nothing to delete!')
                    sleep(2)
            else:
                secret_santa.add_santa(santa_name)
        else:
            if santa_name in secret_santa.all_names():
                print('\nthat santa is already in the list !')
                sleep(2)
            elif santa_name:
                print('\ninvalid input... do it again')
                sleep(2)
        counter += 1

    clear()
    print('\nok ...\n')
    sleep(2)

    print('how many rounds? i.e how many gifts will each person buy?\n')
    ok = False
    while not ok:
        number_rounds = input('>>>>>>> ')
        try:
            number_rounds = int(number_rounds)
            ok = True
        except ValueError:
            print('\nmust be an integer ..\n')
            continue

    while secret_santa.number_rounds() != number_rounds:
        budget = input('\ngift budget for round {}? ($) '
                       '>>>> '.format(secret_santa.number_rounds() + 1))
        try:
            budget = int(budget)
            secret_santa.add_round(budget=budget)
        except ValueError:
            print('\nmust be an integer ..\n')
            continue

    clear()
    print('\nok ...\n')

    if secret_santa.number_rounds() > 1:
        sleep(2)
        print(
            'do you want to enforce each santa being allocated the same person only once?\n'
        )
        sleep(4)
        print("'y' to enforce unique recipients")
        print("'n' to leave it up to chance\n")
        ok = False
        while not ok:
            choice = input('y/n >>>>>>> ').lower()
            if type(choice) == str and choice in ('y', 'n'):
                if choice == 'n':
                    secret_santa.unique_recipients = True
                ok = True
            else:
                if choice:
                    print('\ninvalid choice... do it again\n')
                    sleep(1)

    clear()
    print('\nok ...\n')

    sleep(2)
    for santa in secret_santa.santas:
        print(santa.name)
        sleep(1)
    sleep(2)
    print("\nyou'll be giving gifts to {} other santas ...".format(
        secret_santa.number_rounds()))
    sleep(2)
    if secret_santa.unique_recipients:
        print("\nand you can't get the same person more than once ...")
    else:
        print("\nand you could get the same person more than once ...")

    sleep(2)
    print('\n\nready ...\n\n')
    sleep(4)

    for i in range(7):
        clear()
        print('randomly allocating santas ' + '.' * i)
        sleep(1)
    return secret_santa
Ejemplo n.º 39
0
        % done['filename'])
    dirname = v.gen_dir_name(me)  #v.gen_name(me) + '_' + str(me['uid'])
else:
    u.info("Создание директории")
    dirname = v.gen_dir_name(me)
    dirname = u.mklsdir(dirname)
    u.info("Текущая директория:", dirname)
    done['uid'] = me['uid']

u.info("Загрузка диалогов")
dialogs = v.get_dialogs()

u.info("Всего %d диалогов" % len(dialogs))
"Загрузка личных сообщений:"
for idx, dialog in enumerate(dialogs):
    u.sleep(WAIT_TIME)

    file = None

    if dialog['uid'] <= 0:  # Is group message
        u.warning("Сообщения с группой (id={}) не поддерживаются".format(
            dialog['uid']))
    elif 'chat_id' in dialog:  # Is chat message
        u.info("Беседа '%s'" % dialog['title'])
        if dialog['chat_id'] in done['chat']:
            u.info('Уже загружено')
            continue
        messages = v.get_group_messages(dialog['chat_id'])
        u.info("Всего %d сообщений" % len(messages))
        file = u.getlsfile(
            dirname, dialog['title'].replace(' ', '_') + '_' +