Example #1
0
    def record_for(self, secs_to_run):
        self.rem_time_secs = secs_to_run
        self.mouse_event_count = 0
        self.kb_event_count = 0

        self.session_file_start(str(self.rem_time_secs) + " s")

        hm = pyHook.HookManager()
        hm.MouseWheel = self.OnMouseEvent
        hm.MouseAllButtonsDown = self.OnMouseEvent
        hm.KeyUp = self.OnKeyboardEvent

        hm.HookMouse()
        hm.HookKeyboard()
        # print("--hook-- for " + str(self.rem_time_secs))

        timeout = current_time() + self.rem_time_secs
        while current_time() < timeout:
            pythoncom.PumpWaitingMessages()
            tsleep(0.001)

        # print(self.mouse_event_count)
        # print(self.kb_event_count)

        hm.UnhookMouse()
        hm.UnhookKeyboard()
        # print('---unhook---')

        self.session_save_stats(str(self.rem_time_secs))
Example #2
0
    def manual_record_start(self):

        self.session_file_start("manual mode")

        hm = pyHook.HookManager()
        hm.MouseWheel = self.OnMouseEvent
        hm.MouseAllButtonsDown = self.OnMouseEvent
        hm.KeyUp = self.OnKeyboardEvent

        hm.HookMouse()
        hm.HookKeyboard()
        # print("--hook-- manual ")
        self.mouse_event_count = 0
        self.kb_event_count = 0

        self.running = True
        time_in = current_time()
        while self.running:
            pythoncom.PumpWaitingMessages()
            tsleep(0.001)

        hm.UnhookMouse()
        hm.UnhookKeyboard()
        self.rem_time_secs = round(current_time() - time_in, 2)
        print('---unhook---')
        self.session_save_stats("~" + str(self.rem_time_secs))
Example #3
0
def residue_mapping(ctx, input, chunksize, output, sleep):
    dfs = read_csv(input, sep='\t', keep_default_na=False,
                   na_values=['NULL', 'null', ''], chunksize=chunksize)
    sqlite_api = ctx.obj['custom_db']
    if output is not None:
        output = ctx.obj['folder']/output
    done = 0
    for df in dfs:
        for col in ('new_pdb_range_raw', 'new_unp_range_raw', 'conflict_pdb_index'):
            df[col] = df[col].apply(eval)
        ob = PDBs(())
        ob.tasks = [PDB(row.pdb_id).get_ranged_map_res_df(
                    row.UniProt,
                    row.new_unp_range_raw,
                    row.new_pdb_range_raw,
                    conflict_pdb_index=row.conflict_pdb_index,
                    struct_asym_id=row.struct_asym_id) for row in df.to_records()]
        with Progress(*progress_bar_args) as p:
            res = ob.run(p.track).result()
        res_mapping_df = concat(res, sort=False, ignore_index=True)
        done += len(df)
        if output is not None:
            res_mapping_df[sorted(res_mapping_df.columns)].to_csv(output, sep='\t', mode='a+', index=False, header=not output.exists())
        else:
            sqlite_api.sync_insert(sqlite_api.ResidueMappingRange, res_mapping_df.to_dict('records'))
        console.log(f'Done: {done}')
        if sleep:
            tsleep(uniform(0, 2))
Example #4
0
def calibrate3():
    '''Calibrates the coordinate for AktivitasUmum button.'''
    global tabButtonx, tabButtony

    # preparation
    button1Check()
    pag.scroll(scrollValue // 2)
    tsleep(scrollDelay)

    buttonLoc = pag.locateOnScreen(aktivitasUmumPath)

    if buttonLoc == None:
        print('Calibration UNSUCCESSFUL: tab button not found.')
    elif tabButtonx == buttonLoc[0] + aktUmumOffsetx \
            and tabButtony == buttonLoc[1] + aktUmumOffsety:
        print('Calibration Successful: Tab button is already correct!')
    else:
        print('OLD =', tabButtonx, tabButtony)

        tabButtonx = buttonLoc[0] + aktUmumOffsetx
        tabButtony = buttonLoc[1] + aktUmumOffsety

        print('NEW =', tabButtonx, tabButtony)
        print('Calibration Successful! Tab button is calibrated!')

    pag.scroll(20)
    tsleep(scrollDelay)
Example #5
0
def calibrate4():
    '''Calibrates the coordinate for tambahLaporan button.'''
    global button2x, button2y

    # preparation
    button1Check()
    pag.scroll(scrollValue // 2)
    tsleep(scrollDelay)
    pag.click(tabButtonx, tabButtony)
    checkPixel(tabButtonx, tabButtony, 220)

    buttonLoc = pag.locateOnScreen(tambahLaporanPath)

    if buttonLoc == None:
        print('Calibration UNSUCCESSFUL: tambah laporan  button not found.')
    elif button2x == buttonLoc[0] + tamLapOffsetx \
            and button2y == buttonLoc[1] + tamLapOffsety:
        print('Calibration Successful: Tambah Laporan button is already correct!')
    else:
        print('OLD =', button2x, button2y)

        button2x = buttonLoc[0] + tamLapOffsetx
        button2y = buttonLoc[1] + tamLapOffsety

        print('NEW =', button2x, button2y)
        print('Calibration Successful! Tambah Laporan button is calibrated!')

    pag.click(tabButtonx - 130, tabButtony + 240)
    checkPixel(tabButtonx - 130, tabButtony + 240, 220)
    pag.scroll(20)
    tsleep(scrollDelay)
Example #6
0
def check_switch(comment, outdev, indev, value):
    outdev.move(value)
    tsleep(0.5)
    val = indev.read(0)
    if val == value:
        print('%20s : %s' % (comment, 'OK'))
    else:
        printerror('%20s : %s' % (comment, 'FAILED : value = %s' % (val, )))
Example #7
0
 def startUpAnimation(self):
     # creating a startup animation
     vgn = 0
     for i in range(5):
         tsleep(0.2)
         for i in range(5):
             display.set_pixel(vgn, i, 9)
         vgn += 1
Example #8
0
def check_pressure(comment, outdev, outvalue, indev, inrange):
    outdev.maw(outvalue)
    tsleep(1.5)
    val = indev.read(0)
    if inrange[0] <= val <= inrange[1]:
        print('%20s : %s' % (comment, 'OK'))
    else:
        printerror('%20s : %s' % (comment, 'FAILED : p = %.4f (%r)' %
                                  (val, inrange)))
Example #9
0
 def changeScreen(self, _dir):
     if _dir == "L":
         if self.curScreen > 1:
             tsleep(0.3)
             self.curScreen -= 1
     if _dir == "R":
         if self.curScreen < self.screenCount:
             tsleep(0.3)
             self.curScreen += 1
Example #10
0
def scrollPrep():
    '''To readjust before clicking 'laporkan'.'''

    pag.moveTo(1750, button1y[2])
    pag.scroll(scrollValue)
    pag.scroll(scrollValue)
    tsleep(scrollDelay)
    pag.scroll(-scrollValue)
    tsleep(scrollDelay)
Example #11
0
 def _stop_writing(self) -> None:
     """
     Destroy writer and set boolean to stop putting frames in write queue.
     :return None:
     """
     self._writing = False
     while not self._write_q.empty():
         tsleep(.05)
     self._cam_writer.cleanup()
     self._msg_pipe.send((defs.ModelEnum.STOP, None))
Example #12
0
def checkPixel(x, y, color):
    '''Check the pixel color of x and y until the red color is different.'''
    if type(color) in (tuple, list):
        while pag.screenshot(region=(x, y, 1, 1)).getpixel((0, 0))[0] in color:
            tsleep(waitDelay)
    elif type(color) == int:
        while pag.screenshot(region=(x, y, 1, 1)).getpixel((0, 0))[0] == color:
            tsleep(waitDelay)
    else:
        print("WRONG color")
Example #13
0
def waitClockInput(button):
    '''Wait until we can click on 'Jam Mulai'.'''
    checkPixel(button1x, button1y[button], (26, 28))

    # wait until we can input the time
    while pag.screenshot(region=(blueEdgex, blueEdgey, 1, 1)
            ).getpixel((0, 0))[0] != 26:
        tsleep(waitDelay)
        pag.click(blueEdgex, blueEdgey)

    pag.click(1750, blueEdgey) # click somewhere so it can be triple clicked
    pag.click(x=blueEdgex, y=blueEdgey, clicks=3, interval=0)
Example #14
0
def sleep(base, flex=-1):
    """
    Function for setting a random sleep time. Sleep length set by this function
    can vary from base to base * 2, or base to base + flex if flex is provided.

    base - positive int
    flex - positive int; defaults to -1 to disable
    """
    global util_settings
    if flex == -1:
        tsleep(randint(base, base * 2) + util_settings['sleep_mod'])
    else:
        tsleep(randint(base, base + flex) + util_settings['sleep_mod'])
Example #15
0
def sleep(base, flex=-1):
    """
    Function for setting a random sleep time. Sleep length set by this function
    can vary from base to base * 2, or base to base + flex if flex is provided.

    base - positive int
    flex - positive int; defaults to -1 to disable
    """
    global util_settings
    if flex == -1:
        tsleep(randint(base, base * 2) + util_settings['sleep_mod'])
    else:
        tsleep(randint(base, base + flex) + util_settings['sleep_mod'])
Example #16
0
 def _distribute_frames(self) -> None:
     """
     Distribute frames in proper order to image_worker processes.
     :return None:
     """
     i = 0
     while self._process_imgs:
         ret, val = self._cam_reader.get_next_new_frame()
         if ret:
             (frame, timestamp, num_writes) = val
             self._hand_out_frame(frame, timestamp, i, num_writes)
             i = self._increment_counter(i)
         else:
             tsleep(.001)
Example #17
0
def main():
    aptS = True
    # asking people to start game
    while aptS:
        display.show("[a]")
        if button_a.is_pressed():
            aptS = False
    # clearing the display
    display.clear()
    # starting a countdown to let people know when the game is starting
    cd = 3
    while cd > 0:
        display.show(str(cd))
        tsleep(1)
        cd -= 1
        display.clear()

    # creating a reference time point to
    # be able to end the game after 20seconds of playing
    t_end = running_time() + 30000
    while True:
        if running_time() >= t_end:
            break

        # firstly, setting the head at center via the game grid
        i = 0
        while i < len(snake.snakeBody):
            # the first element of the body array is the head
            display.set_pixel(snake.snakeBody[i][0], snake.snakeBody[i][1], 4)
            i += 1
        # checking if a fruit exists, if it doesnt, rendering one
        if not (gameData.fruitExists):
            createNewFruit()

        # MOVING RELATED FUNCTIONS
        if button_a.is_pressed():
            tsleep(0.5)
            moveSnakeF("horizontal")
        if button_b.is_pressed():
            tsleep(0.5)
            moveSnakeF("vertical")

    # once the 20seconds are over, clearing the screen and ending the game
    display.clear()
    wfNG = True
    # making a simple load animation
    for x in range(5):
        tsleep(0.2)
        display.set_pixel(2, x, 9)
    # showing the people their game score and telling them how to restart
    while wfNG:
        display.show(str(snake.points))
        if button_a.is_pressed():
            # ressetting the game for a fresh one
            wfNG = False
            gameData.clearGame()
            snake.clearSnake()
            # starting a new game
            main()
 def set_fps(self, new_fps: float) -> None:
     """
     Set simulated read speed of this camera. Reader will still read from camera at max rate.
     :param new_fps: The new simulated fps.
     :return None:
     """
     with self._lock:
         self._running.clear()
         tsleep(.05)
         self._fps_target = new_fps
         self._spf_target = 1 / self._fps_target
         self._buffer = new_fps // 6
         self._start = time()
         self._num_frms = 0
         self._running.set()
Example #19
0
def insert_sifts_meta(ctx, input, chunksize, func, api_suffix, then_func, sleep):
    custom_db = ctx.obj['custom_db']
    
    @unsync
    async def insert_meta(pdb):
        df = await getattr(pdb, func)(api_suffix).then(getattr(SIFTS, then_func))
        if df is not None:
            await custom_db.async_insert(custom_db.ResidueAnnotation, df.to_dict('records'))
    
    df = read_csv(input, header=None, chunksize=chunksize, keep_default_na=False, na_values=[''])
    done = 0
    for ids in df:
        pdbs = PDBs(ids[0].unique())
        with Progress(*progress_bar_args) as p:
            pdbs.fetch(insert_meta).run(p.track).result()
        done += len(pdbs)
        console.log(f'Done: {done}')
        if sleep:
            tsleep(uniform(0, 3))
Example #20
0
    def _verifyAsicDB(self, db, ports, portMap, timeout):
        '''
        Verify in the Asic DB that port are deleted, Keep on trying till timeout
        period.

        Parameters:
            db (SonicV2Connector): database.
            ports (list): port list to check in ASIC DB.
            portMap (dict): oid<->port map.
            timeout (int): timeout period

        Returns:
            (bool)
        '''
        self.sysLog(doPrint=True,
                    msg="Verify Port Deletion from Asic DB, Wait...")
        try:
            for waitTime in range(timeout):
                self.sysLog(logLevel=syslog.LOG_DEBUG,
                            msg='Check Asic DB: {} \
                    try'.format(waitTime + 1))
                # checkNoPortsInAsicDb will return True if all ports are not
                # present in ASIC DB
                if self._checkNoPortsInAsicDb(db, ports, portMap):
                    break
                tsleep(1)

            # raise if timer expired
            if waitTime + 1 == timeout:
                self.sysLog(syslog.LOG_CRIT,
                            "!!!  Critical Failure, Ports \
                    are not Deleted from ASIC DB, Bail Out  !!!",
                            doPrint=True)
                raise Exception(
                    "Ports are present in ASIC DB after {} secs".format(
                        timeout))

        except Exception as e:
            self.sysLog(doPrint=True, logLevel=syslog.LOG_ERR, msg=str(e))
            raise e

        return True
Example #21
0
 def _start_frame_processing(self) -> None:
     """
     Create image processing threads and wait for stop signal.
     :return None:
     """
     self._process_imgs = True
     max_res = defs.common_resolutions[-1]
     max_img_arr_shape = (int(max_res[1]), int(max_res[0]), 3)
     max_img_arr_size = max_img_arr_shape[0] * max_img_arr_shape[
         1] * max_img_arr_shape[2]
     self._sems1 = list()
     self._sems2 = list()
     self._sems3 = list()
     self._shm_ovl_arrs = list()
     self._shm_img_arrs = list()
     self._np_img_arrs = list()
     self._num_writes_arrs = list()
     for i in range(self._num_img_workers):
         self._sems1.append(Semaphore(0))
         self._sems2.append(Semaphore(0))
         self._sems3.append(Semaphore(1))
         self._shm_ovl_arrs.append(Array(c_char, BYTESTR_SIZE))
         self._shm_img_arrs.append(Array('Q', max_img_arr_size))
         self._num_writes_arrs.append(Value('i', 1))
         worker_args = (self._shm_img_arrs[i], self._sems1[i],
                        self._sems2[i], self._shm_ovl_arrs[i])
         worker = Thread(target=self._img_processor,
                         args=worker_args,
                         daemon=True)
         worker.start()
     self._refresh_np_arrs()
     distributor = Thread(target=self._distribute_frames,
                          args=(),
                          daemon=True)
     distributor.start()
     handler = Thread(target=self._handle_processed_frames,
                      args=(),
                      daemon=True)
     handler.start()
     while self._process_imgs:
         tsleep(1)
Example #22
0
def id_mapping(ctx, input, column, sep, chunksize, auto_assign, sleep):
    sqlite_api = ctx.obj['custom_db']
    cols = ('ftId', 'Entry', 'isoform', 'is_canonical')
    Identifier.auto_assign_when_seq_conflict = auto_assign
    if input is None:
        total = unsync_run(sqlite_api.database.fetch_one(
            query="SELECT COUNT(DISTINCT ftId) FROM Mutation WHERE ftId NOT IN (SELECT DISTINCT ftId FROM IDMapping)"))[0]
        console.log(f"Total {total} to query")
        query = f"""
                SELECT DISTINCT ftId FROM Mutation
                WHERE ftId NOT IN (SELECT DISTINCT ftId FROM IDMapping)
                LIMIT {chunksize}
                """
        for index in range(ceil(total/chunksize)):
            res = unsync_run(sqlite_api.database.fetch_all(query=query))
            if len(res) == 0:
                break
            with Progress(*progress_bar_args) as p:
                res = Identifiers(i[0] for i in res).fetch('map2unp').run(p.track).result()
            values = [dict(zip(cols, i)) for i in res]
            if values:
                sqlite_api.sync_insert(sqlite_api.IDMapping, values)
            console.log(f'Done: {len(res)+chunksize*index}')
            if sleep:
                tsleep(uniform(1, 10))
    else:
        if column is None:
            ids = read_csv(input, sep=sep, header=None)[0].unique()
        else:
            ids = read_csv(input, sep=sep, usecols=[column])[column].unique()
        total = len(ids)
        console.log(f"Total {total} to query")
        for index in range(0, total, chunksize):
            with Progress(*progress_bar_args) as p:
                res = Identifiers(ids[index:index+chunksize]).fetch('map2unp').run(p.track).result()
            values = [dict(zip(cols, i)) for i in res]
            if values:
                sqlite_api.sync_insert(sqlite_api.IDMapping, values)
            console.log(f'Done: {len(res)+index}')
            if sleep:
                tsleep(uniform(1, 10))
 def _read_cam(self) -> None:
     """
     Continuously check camera for new frames and put into queue.
     :return None:
     """
     while not self._end.is_set():
         if self._running.is_set():
             ret, frame, dt = self._get_a_frame()
             if not ret:
                 break
             self._tracker.update_fps()
             metric = (time() - self._start) // self._spf_target
             frm_diff = int(metric - self._num_frms)
             if frm_diff > 0:
                 self._internal_frame_q.add_to_q((frame, dt, frm_diff))
                 self._num_frms += frm_diff
             elif frm_diff > -self._buffer:
                 self._internal_frame_q.add_to_q((frame, dt, 1))
                 self._num_frms += 1
         else:
             tsleep(.1)
Example #24
0
def check_compressor_errors(comment, errdev, compressor, indev):
    if compressor.status(0)[0] == ERROR:
        compressor.reset()
    compressor.maw('on')
    tsleep(1.0)
    if indev.read() == 'on':
        errdev.move('on')
        tsleep(1.0)
        st = errdev.read()
        if st == 'on':
            if compressor.status(0)[0] == ERROR:
                print('%20s : OK' % (comment, ))
                compressor.reset()
            else:
                printerror('20%s : %s' % (comment, 'FAILED : compressor not in'
                                          ' ERROR state'))
            errdev.move('off')
        else:
            printerror('%20s : %s' % (comment, 'FAILED : compressor not '
                                      'switched on'))
    else:
        printwarning('%20s : %s' % (comment, 'SKIPPED'))
Example #25
0
def isiUmum(search, timeStart, timeEnd, info):
    '''Input an activity in 'Aktivitas Umum.'''
    # click 'Aktivitas Umum'
    button1Check()
    pag.scroll(scrollValue // 2)
    tsleep(scrollDelay)
    pag.click(tabButtonx, tabButtony)
    checkPixel(tabButtonx, tabButtony, 220)

    # click 'Tambahkan Laporan'
    pag.click(button2x, button2y)
    checkPixel(button2x, button2y, (26, 28))

    # check until the data can be inputed
    checkNotPixel(button2x - 280, button2y + 50, 246)
    pag.click(button2x - 280, button2y + 50)
    pag.typewrite(search + "\n\t" + timeStart + "\t" + timeEnd + "\t\t" + info
            + submit())

    # check until can go back to 'Aktivitas Utama'
    checkPixel(tabButtonx - 60, tabButtony + 440, (26, 28))
    if not testVar: # check the first green icon on the right
        for _ in range(0, 10):
            if pag.screenshot(region=(button2x, button2y + 41, 1, 1)).getpixel((0, 0))[0] == 26:
                break
            tsleep(waitDelay)

    # set the location of 'Aktivitas Utama' button
    tombolUtama = (tabButtonx - 130,)
    if testVar:
        tombolUtama += (tabButtony + 240,)
    else:
        tombolUtama += (tabButtony + 195,)

    # go back to 'Aktivitas Utama'
    if pag.screenshot(region=(tombolUtama[0], tombolUtama[1], 1, 1)).getpixel((0, 0))[0] == 220:
        pag.click(tombolUtama[0], tombolUtama[1])

    checkPixel(tombolUtama[0], tombolUtama[1], 220)
 def sleep(t):
     return tsleep(t / 1000)
Example #27
0
"""
Created on Thu May 12 11:41:58 2016

@author: xf05id1
"""

from time import sleep as tsleep

print('2. testing pseudo motors motion:')

print('testing ssa')
print('Testing relative motion within motion range')
print('- Moving h_gap +0.1 mm')
movr(slt_ssa.h_gap, .1)
print('- Moving h_gap -0.1 mm..')
movr(slt_ssa.h_gap, -.1)

#for complete test, checking all h_gap, h_cen, v_gap, v_cen motions
print('Testing emergency stop, pressing Ctrl+C within 1 s.')
try:
    movr(slt_ssa.h_gap, 5)
except KeyboardInterrupt:
    print('canceled', slt_ssa.h_gap.position)
else:
    raise RuntimeError("YOU DID NOT ABORT THE MOVE")
print('shortly after canceled', slt_ssa.h_gap.position)
tsleep(1)
print('1 s later', slt_ssa.h_gap.position)
tsleep(1)
print('2 s later', slt_ssa.h_gap.position)
Example #28
0
def sleep_fast():
    """
    Function for sleeping for a very short period of time. For use mainly between
    a succession of mouseclick events.
    """
    tsleep(uniform(0.2, 0.5))
def mp_producer(parms):
    idWorker,  nIter, sDBPath, loopTbms ,sKey = parms
    # ritardo per evitare conflitti su DB
    tsleep(idWorker*10+1)
    start_time = ttime()
    now = datetime.datetime.now()
    strnow = now.strftime("%Y%m%d%H%M%S")
    main_logger = createLogger(idWorker,"mp_producer")
    main_logger.info("[%d]############################# Starts at %s" % (idWorker,strnow))
    #with plock:
    #    print "[%d]############################# Starts at %s" % (idWorker,strnow)


    #inizializzo le info sui tracciati dai file di configurazione
    inizio_GLEST = bbtConfig.getfloat('Import','inizio_GLEST')
    fine_GLEST = bbtConfig.getfloat('Import','fine_GLEST')
    inizio_GLSUD = bbtConfig.getfloat('Import','inizio_GLSUD')
    fine_GLSUD = bbtConfig.getfloat('Import','fine_GLSUD')
    inizio_CE = bbtConfig.getfloat('Import','inizio_CE')
    fine_CE = bbtConfig.getfloat('Import','fine_CE')
    #differenza tra CE e GLEST in modo tale che GLNORD = delta_GLEST_CE - CE
    delta_GLEST_CE =  bbtConfig.getfloat('Import','delta_GLEST_CE')
    projectRefCost =  bbtConfig.getfloat('Import','project_ref_cost') # mln di euro

    # danzi.tn@20151115 recepimento modifiche su InfoAlignment fatte da Garbriele
    #LEGGO I PARAMETRI DA FILE DI CONFIGURAZIONE
    fCShiledMin = bbtConfig.getfloat('Alignment','frictionCShiledMin')
    fCShiledMode = bbtConfig.getfloat('Alignment','frictionCShiledMode')
    fCShiledMax = bbtConfig.getfloat('Alignment','frictionCShiledMax')
    #CREO OGGETTO
    fcShield = FrictionCoeff(fCShiledMin,fCShiledMode,fCShiledMax)

    #LEGGO I PARAMETRI DA FILE DI CONFIGURAZIONE
    fCCutterdMin = bbtConfig.getfloat('Alignment','frictionCCutterMin')
    fCCutterMode = bbtConfig.getfloat('Alignment','frictionCCutterMode')
    fCCutterMax = bbtConfig.getfloat('Alignment','frictionCCutterMax')
    #CREO OGGETTO
    fcCutter =  FrictionCoeff(fCCutterdMin,fCCutterMode,fCCutterMax)

    alnAll = []
    aln=InfoAlignment('Galleria di linea direzione Sud', 'GLSUD', inizio_GLSUD, fine_GLSUD,fCCutterMode, fCShiledMode)
    alnAll.append(aln)
    aln=InfoAlignment('Cunicolo esplorativo direzione Nord', 'CE', delta_GLEST_CE - fine_CE, delta_GLEST_CE - inizio_CE , fCCutterMode, fCShiledMode)
    alnAll.append(aln)
    aln=InfoAlignment('Galleria di linea direzione Nord', 'GLNORD',inizio_GLEST, fine_GLEST, fCCutterMode, fCShiledMode)
    alnAll.append(aln)
    kpiTbmList = []
    main_logger.debug("[%d]############################# Inizia a recuperare le itarazioni di %s dalla %d alla %d" % (idWorker,sKey,idWorker*nIter, (idWorker+1)*nIter))
    bbt_bbtparameterseval = get_mainbbtparameterseval(sDBPath,sKey,idWorker*nIter, (idWorker+1)*nIter)
    main_logger.debug("[%d]############################# ...recuperate %d iterazioni, memoria totale" % (idWorker,len(bbt_bbtparameterseval)))
    for iIterationNo in range(nIter):
        mainIterationNo = idWorker*nIter + iIterationNo
        tbmSegmentCum = 0
        iter_start_time = ttime()
        bbttbmkpis = []
        bbt_evalparameters = []
        iCheckEvalparameters = 0
        iCheckBbttbmkpis = 0
        # Per tutti i Tunnel
        main_logger.info("[%d]########### iteration %d - %d" % (idWorker, iIterationNo, mainIterationNo))        #with plock:
        #    print "[%d]########### iteration %d - %d" % (idWorker, iIterationNo, mainIterationNo)
        for alnCurr in alnAll:
            for tbmKey in loopTbms:
                tbmData = loopTbms[tbmKey]
                # Se la TBM e' conforme al TUnnell
                if alnCurr.tbmKey in tbmData.alignmentCode:
                    tbm = TBM(tbmData, 'V')
                    kpiTbm = KpiTbm4Tunnel(alnCurr.description, mainIterationNo)
                    iCheckBbttbmkpis += 1
                    kpiTbm.setKPI4TBM(alnCurr,tbmKey,tbm,projectRefCost)
                    # cerco i segmenti che rientrano tra inizio e fine del Tunnell
                    matches_params = [bpar for bpar in bbt_bbtparameterseval[mainIterationNo] if alnCurr.pkStart <= bpar.inizio and bpar.fine <= alnCurr.pkEnd]
                    for bbt_parameter in matches_params:
                        bbtparameter4seg = build_bbtparameterVal4seg(bbt_parameter)
                        iCheckEvalparameters += 1
                        if bbtparameter4seg == None:
                            main_logger.error("[%d] %s, %s per pk %d parametri Geo non trovati" % (idWorker, alnCurr.description, tbmKey, bbt_parameter.fine) )
                            continue
                        # danzi.tn@20151115 recepimento modifiche su InfoAlignment fatte da Garbriele
                        if iIterationNo > 2:
                            alnCurr.frictionCoeff = fcShield.rvs()
                            alnCurr.fiRi = fcCutter.rvs()
                        else:
                            alnCurr.frictionCoeff = fCShiledMode
                            alnCurr.fiRi = fCCutterMode
                        try:
                            tbmSegBefore = ttime()
                            tbmsect = TBMSegment(bbtparameter4seg, tbm, alnCurr.fiRi, alnCurr.frictionCoeff)
                            tbmSegAfter = ttime()
                            tbmSegmentCum += (tbmSegAfter - tbmSegBefore)
                        except Exception as e:
                            main_logger.error("[%d] %s, %s per pk %d TBMSegment va in errore: %s" % (idWorker, alnCurr.description, tbmKey, bbt_parameter.fine , e) )
                            main_logger.error("[%d] bbtparameter4seg = %s" % str(bbtparameter4seg))
                            continue
                        kpiTbm.setKPI4SEG(alnCurr,tbmsect,bbtparameter4seg)
                        #danzi.tn@20151114 inseriti nuovi parametri calcolati su TunnelSegment
                        bbt_evalparameters.append((strnow, mainIterationNo,alnCurr.description, tbmKey, bbt_parameter.fine,bbt_parameter.he,bbt_parameter.hp,bbt_parameter.co,bbtparameter4seg.gamma,\
                                                        bbtparameter4seg.sci,bbtparameter4seg.mi,bbtparameter4seg.ei,bbtparameter4seg.cai,bbtparameter4seg.gsi,bbtparameter4seg.rmr,\
                                                        tbmsect.pkCe2Gl(bbt_parameter.fine),\
                                                        tbmsect.TunnelClosureAtShieldEnd*100. ,\
                                                        tbmsect.rockBurst.Val,\
                                                        tbmsect.frontStability.Ns,\
                                                        tbmsect.frontStability.lambdae,\
                                                        tbmsect.penetrationRate*1000. ,\
                                                        tbmsect.penetrationRateReduction*1000. ,\
                                                        tbmsect.contactThrust, \
                                                        tbmsect.torque, \
                                                        tbmsect.frictionForce, \
                                                        tbmsect.requiredThrustForce, \
                                                        tbmsect.availableThrust, \
                                                        tbmsect.dailyAdvanceRate, \
                                                        bbt_parameter.profilo_id, \
                                                        bbt_parameter.geoitem_id, \
                                                        bbt_parameter.title, \
                                                        bbtparameter4seg.sti, \
                                                        bbtparameter4seg.k0, \
                                                        tbmsect.t0, \
                                                        tbmsect.t1, \
                                                        tbmsect.t3, \
                                                        tbmsect.t4, \
                                                        tbmsect.t5, \
                                                        tbmsect.InSituCondition.SigmaV, \
                                                        tbmsect.Excavation.Radius, \
                                                        tbmsect.Rock.E, \
                                                        tbmsect.MohrCoulomb.psi, \
                                                        tbmsect.Rock.Ucs, \
                                                        tbmsect.InSituCondition.Gsi, \
                                                        tbmsect.HoekBrown.Mi, \
                                                        tbmsect.HoekBrown.D, \
                                                        tbmsect.HoekBrown.Mb, \
                                                        tbmsect.HoekBrown.S, \
                                                        tbmsect.HoekBrown.A, \
                                                        tbmsect.HoekBrown.Mr, \
                                                        tbmsect.HoekBrown.Sr, \
                                                        tbmsect.HoekBrown.Ar, \
                                                        tbmsect.UrPi_HB(0.), \
                                                        tbmsect.Rpl, \
                                                        tbmsect.Picr, \
                                                        tbmsect.LDP_Vlachopoulos_2009(0.), \
                                                        tbmsect.LDP_Vlachopoulos_2009(tbm.Slen), \
                                                         ) )
                    kpiTbm.updateKPI(alnCurr)
                    bbttbmkpis += kpiTbm.getBbtTbmKpis()
                    sys.stdout.flush()
        iter_end_time = ttime()
        main_logger.info("[%d]#### iteration %d - %d terminated in %d seconds (%d)" % (idWorker, iIterationNo, mainIterationNo, iter_end_time-iter_start_time, tbmSegmentCum))
        main_logger.debug("[%d]### Start inserting %d (%d) Parameters and %d (21x%d) KPIs" % (idWorker, len(bbt_evalparameters),iCheckEvalparameters,len(bbttbmkpis),iCheckBbttbmkpis))
        insert_eval4Iter(sDBPath,bbt_evalparameters,bbttbmkpis)
        insert_end_time = ttime()
        main_logger.info("[%d]]### Insert terminated in %d seconds" % (idWorker,insert_end_time-iter_end_time))
    now = datetime.datetime.now()
    strnow = now.strftime("%Y%m%d%H%M%S")
    end_time = ttime()
    main_logger.info("[%d]############################# Ends at %s (%s seconds)" % (idWorker,strnow, end_time-start_time))
Example #30
0
def sleep(sec):
    tsleep(uniform(sec, sec * 2))
Example #31
0
def main():
    # getting password
    psswd = gethash(getpass(), mode="pass")

    # decrypting and loading settings
    settings = fdecrypt("files/vk.settings", psswd)
    # print(settings)
    login = "".join(re.findall(r"login=(.+)#endlogin", settings))
    password = "".join(re.findall(r"password=(.+)#endpass", settings))
    chatid = int("".join(re.findall(r"chatid=(\d+)#endchatid", settings)))
    albumid = int("".join(re.findall(r"album_id=(\d+)#endalbumid", settings)))
    userid = int("".join(re.findall(r"userid=(\d+)#enduserid", settings)))

    state_auth = False
    # getting session
    while not state_auth:
        try:
            vk_session = vk_api.VkApi(login, password, captcha_handler=captcha_handler)
            vk_session.authorization()
            vk = vk_session.get_api()
            state_auth = True
        except:
            state_auth = False
            tsleep(30)
            exception("smth goes wrong at geting api\n")

    # getting url
    url = geturl(psswd)

    # Lists of messages
    msg_man = Manager()
    list_of_cmds, list_of_alles, list_of_imnts, tl_msgs = msg_man.list(), msg_man.list(), msg_man.list(), msg_man.list()

    # accounting the speed
    iterations_vk = Value("i", 0)
    iterations_tl = Value("i", 0)

    # file`s safe work
    msgshistory = io.SharedFile("files/msgshistory.db")

    # stats Manager
    stat_man = Manager()
    curr_stat = stat_man.dict()
    curr_stat["temp"] = 0
    curr_stat["iter_tl"] = 0
    curr_stat["iter_vk"] = 0
    curr_stat["PID_VK"] = 0
    curr_stat["PID_TL"] = 0

    # starting bot
    print("Logged in, starting bot...")

    vk_process = Process(
        target=vk_run.run_vk_bot,
        args=(
            vk,
            chatid,
            albumid,
            userid,
            msgshistory,
            tl_msgs,
            list_of_alles,
            list_of_imnts,
            list_of_cmds,
            iterations_vk,
            curr_stat,
        ),
    )
    tl_process = Process(
        target=telegrambot.tlmain,
        args=(url, tl_msgs, msgshistory, list_of_alles, list_of_imnts, iterations_tl, curr_stat),
    )

    print("Starting VK bot...")
    vk_process.start()

    print("Starting TL bot...")
    tl_process.start()

    # checking if admin gave argument "--screen"
    if len(argv) > 1 and argv[1] == "--screen":
        import curses

        stdscr = curses.initscr()
        curses.noecho()
        stdscr.keypad(True)

    # crutch
    iterations_tl.value = 1
    iterations_vk.value = 1

    while True:
        out_string = """Temp: {0} C; \nSpeed_TL: {1}; \nSpeed_VK: {2};"""
        tempfile = open("/sys/class/thermal/thermal_zone0/temp", "r")
        # print('Temp: ' + str(float(tempfile.read().strip())/1000) + ' C ', end='')
        ctemp = str(float(tempfile.read().strip()) / 1000)
        tempfile.close()

        curr_stat["temp"] = ctemp
        curr_stat["iter_tl"] = iterations_tl.value
        curr_stat["iter_vk"] = iterations_vk.value

        if len(argv) > 1 and argv[1] == "--screen":
            stdscr.clear()
            stdscr.addstr(out_string.format(ctemp, iterations_tl.value, iterations_vk.value))
            stdscr.refresh()

        # checking if process is alive. If not, restarting process
        if iterations_tl.value == 0:
            tl_process.terminate()
            tl_process = Process(
                target=telegrambot.tlmain,
                args=(url, tl_msgs, msgshistory, list_of_alles, list_of_imnts, iterations_tl, curr_stat),
            )
            print("Restarting TL bot...")
            tl_process.start()
            # iterations_tl.value = 1

        if iterations_vk.value == 0:
            vk_process.terminate()
            vk_process = Process(
                target=vk_run.run_vk_bot,
                args=(
                    vk,
                    chatid,
                    albumid,
                    userid,
                    msgshistory,
                    tl_msgs,
                    list_of_alles,
                    list_of_imnts,
                    list_of_cmds,
                    iterations_vk,
                    curr_stat,
                ),
            )
            print("Restarting VK bot...")
            vk_process.start()
            # iterations_vk.value = 1

        # stdout.flush()
        iterations_tl.value = 0
        iterations_vk.value = 0
        tsleep(60)

    tl_process.join()
    vk_process.join()

    curses.nocbreak()
    stdscr.keypad(False)
    curses.echo()
    print("Exit...")
Example #32
0
"""
Created on Thu May 12 11:10:28 2016

@author: xf05id1
"""
from time import sleep as tsleep
from bluesky.suspenders import SuspendBoolLow

print('6. testing suspenders:')
gv = EpicsSignal('XF:05IDB-VA:1{Slt:SSA-GV:1}Pos-Sts')

susp_gv = SuspendBoolLow(gv)
RE.install_suspender(susp_gv)

print('going to launch xrf2d map, please ensure GV before B shutter is closed')
tsleep(5)

print(
    'running xrf 2d mapping, open GV to test start of the scan, close GV to test suspension, re-open GV to test resuming the scan'
)
hf2dxrf(xstart=26.70,
        xstepsize=0.005,
        xnumstep=3,
        ystart=15.28,
        ystepsize=.005,
        ynumstep=3,
        acqtime=.2,
        numrois=2,
        i0map_show=True,
        itmap_show=True)
 def inner_func(self, *args, **kwargs):
     result = func(self, *args, **kwargs)
     if self.throttle():
         tsleep(self.time())
     self.acquisitions.append(datetime.now())
     return result
Example #34
0
 def __init__(self, job, storage, chrome, stop=None):
     'Generate object for Facebook by giving the needed parameters'
     self.storage = storage
     self.chrome = chrome
     self.logger = self.storage.logger
     self.stop = stop
     self.stop_check = self.chrome.stop_check
     self.options = job['options']
     self.ct = Cutter()
     self.emails = self.ct.split(job['login']['Email'])
     self.passwords = self.ct.split(job['login']['Password'])
     self.passwords += [
         self.passwords[-1]
         for i in range(len(self.emails) - len(self.passwords))
     ]  # same password
     if self.emails == [] or self.passwords == []:
         raise RuntimeError(
             'At least one login account is needed for the Facebook module.'
         )
     self.loginrevolver = -1  # for multiple investigator accounts
     targets = self.extract_paths(job['target'])
     self.logger.debug('Facebook: targets: %s' % targets)
     if self.options['Network']:
         accounts = self.get_network(targets)
     if self.options['Network'] and self.options['extendNetwork']:
         check4tasks = ('About', 'Photos')
     else:
         check4tasks = ('About', 'Photos', 'Timeline')
     for i in targets:  # one target after the other
         if self.stop_check():
             break
         self.logger.debug('Facebook: now working on target: %s' % i)
         if self.options[
                 'Network']:  # if network option has been proceeded already
             account = accounts[i]  # the profiles have already been fetched
         else:
             if self.logger.level <= DEBUG:  # fragile on debug or lower logging level
                 account = self.get_landing(
                     i)  # get profiles / landing page
             else:  # error robust by default
                 try:
                     account = self.get_landing(i)
                 except:
                     self.logger.warning(
                         'Facebook: account undetected "%s"' % i)
                     continue
         for j in check4tasks:  # run other desired tasks
             if self.stop_check():
                 break
             if self.options[j]:
                 cmd = 'self.get_%s(account)' % j.lower()
                 if self.logger.level <= DEBUG:
                     exec(cmd)
                 else:
                     try:
                         exec(cmd)
                     except:
                         self.logger.warning(
                             'Facebook: could not execute "%s"' % cmd)
                         continue
     if self.chrome.chrome_proc != None:
         if self.logger.level < DEBUG:
             self.logger.trace(
                 'Facebook: finished, now sleeping for 10 seconds')
             tsleep(10)
         self.chrome.close()
     if self.chrome.is_running():
         self.logger.warning(
             'Facebook: Chrome/Chromium was still running finishing jobs')
         if self.logger.level < DEBUG:
             self.logger.trace(
                 'Facebook: now sleeping for 5 seconds before closing Chrome/Chromium'
             )
             sleep(5)
         self.chrome.close()
     self.logger.debug('Facebook: done!')
Example #35
0
def sleep_fast():
    """
    Function for sleeping for a very short period of time. For use mainly between
    a succession of mouseclick events.
    """
    tsleep(uniform(0.2, 0.5))