Пример #1
0
def main():
    assert len(sys.argv) == 2

    strategy_module = sys.argv[1]

    path_manager = FilePathManager.getInstance()
    path_manager.setStrategiesFolderPath(STRATEGY_PATH)

    client = TesterFactory.getDefaultInstance()
    client.setSystemListener(SystemListener())
    client.connect("file://" + JNLP, LOGIN, PASSWORD)

    client.setSubscribedInstruments({Instrument.EURUSD})
    client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(), 5000)
    client.setDataInterval(
        ITesterClient.DataLoadingMethod.ALL_TICKS, Date(*STARTDATE).getTime(), Date(*ENDDATE).getTime()
    )
    client.downloadData(DownloadListener())

    Thread.sleep(5000)

    while 1:
        strategy_class = load_strategy_from_module(strategy_module)

        if strategy_class:
            strategy = strategy_class()
            client.startStrategy(strategy, ProgressListener())

        watch_file_for_changes(strategy_module)
    def setUpClass(self):
        rg = ResourceGroupCi()
        self.resource_group = rg.resourceName
        self.client = AzureClient.new_instance(rg.subscription)

        webjob_ci = TriggeredWebJobCi()
        webjob_ci.container = rg
        webjob_ci.file = File(Thread.currentThread().getContextClassLoader().getResource("webjob.zip").toURI())

        continuous_webjob_ci = ContinuousWebJobCi()
        continuous_webjob_ci.container = rg
        continuous_webjob_ci.file = File(Thread.currentThread().getContextClassLoader().getResource("continuous_webjob.zip").toURI())

        webapp_ci = WebAppCi()
        webapp_ci.appSettings = {}
        webapp_ci.customConnectionStrings = {}
        webapp_ci.sqlServerConnectionStrings = {}
        webapp_ci.sqlDatabaseConnectionStrings = {}

        self.client.create_resource_group(rg.resourceName, rg.resourceLocation)
        define_app_service_plan.create_or_update(AppServicePlanCi(), rg)
        define_web_app.create_or_update(webapp_ci, rg)

        self.client.wait_for_kudu_services(webjob_ci.appName)

        self.webjob = webjob_ci.webJobName
        self.site_name = webjob_ci.appName
        self.webjob_ci = webjob_ci

        self.continuous_webjob_ci = continuous_webjob_ci
        self.continuous_webjob = continuous_webjob_ci.webJobName
Пример #3
0
 def __init__(self, interval, function, args=[], kwargs={}):
     Thread.__init__(self)
     self.interval = interval
     self.function = function
     self.args = args
     self.kwargs = kwargs
     self.finished = Event()
Пример #4
0
    def flyOneLine(self, gg, bx, by, cy):
        vpcount = gg.vpCount = 0
        for cx in xrange(8):
            x, y = GeoUtil.getXY(22, 22, bx, by, cx, cy)
            lastZ = self.getLastZ(bx, by, cx, cy) - 150
            self.setLastZ(bx, by, cx, cy, lastZ)
            if lastZ <= -15000:
                continue

            while vpcount > gg.vpCount + 2:
                Thread.sleep(5)
                if not gg.isOnline():
                    print "no gm"
                    self.doneBlock[by * 256 + bx] = 0
                    return False
                if not self.gsge.isAlive():
                    print "gsge error"
                    self.doneBlock[by * 256 + bx] = 0
                    return False

            if gg.vpCount > vpcount:
                vpcount = gg.vpCount
            self.fly(gg, x, y, lastZ, x, y, lastZ - 16)
            vpcount += 1
        return True
Пример #5
0
    def test_interruptible(self):

        def wait_until_interrupted(cv):
            name = threading.currentThread().getName()
            with cv:
                while not JThread.currentThread().isInterrupted():
                    try:
                        cv.wait()
                    except InterruptedException as e:
                        break

        num_threads = 5
        unfair_condition = Condition()
        threads = [
            Thread(
                name="thread #%d" % i,
                target=wait_until_interrupted,
                args=(unfair_condition,)) 
            for i in range(num_threads)]

        for thread in threads:
            thread.start()
        time.sleep(0.1)

        for thread in threads:
            JThread.interrupt(thread)

        joined_threads = 0
        for thread in threads:
            thread.join(1.) # timeout just in case so we don't stall regrtest
            joined_threads += 1
        self.assertEqual(joined_threads, num_threads)
Пример #6
0
 def tick(self, framerate=0):
     """
     Call once per program cycle, returns ms since last call.
     An optional framerate will add pause to limit rate.
     """
     while self._repaint_sync.get():
         try:
             self._thread.sleep(1)
         except InterruptedException:
             Thread.currentThread().interrupt()
             break
     self._time = System.nanoTime()//1000000
     if framerate:
         time_pause = (1000//framerate) - (self._time-self._time_init)
         if time_pause > 0:
             try:
                 self._thread.sleep(time_pause)
             except InterruptedException:
                 Thread.currentThread().interrupt()
             self._time = System.nanoTime()//1000000
     if self._pos:
         self._pos -= 1
     else:
         self._pos = 9
     self._time_diff[self._pos] = self._time-self._time_init
     self._time_init = self._time
     return self._time_diff[self._pos]
Пример #7
0
    def __init__(self):
        """
        Initialize tests
        """
        Logger.getLogger("net.spy.memcached").setLevel(Level.DEBUG);
        self.clients = []
        if USE_GLOBAL_CLIENT:
            # use global client
            self.client = global_client
        else:
            cfb = ConnectionFactoryBuilder()
            self.client = ArcusClient.createArcusClient(arcus_cloud, service_code, cfb)

        print 'Wait for per-thread client to be connected to Arcus cloud (%d seconds)' % DEFAULT_CONNECTION_WAIT
        Thread.currentThread().sleep(DEFAULT_CONNECTION_WAIT * 1000)
        
        self.flush_counter = 0

        self.tests = []
       
        # insert operations
        self.tests.append(Test(1, "KeyValue").wrap(self.KeyValue))
        self.tests.append(Test(2, "Collection_Btree").wrap(self.Collection_Btree))
        self.tests.append(Test(3, "Collection_Set").wrap(self.Collection_Set))
        self.tests.append(Test(4, "Collection_List").wrap(self.Collection_List))
Пример #8
0
def main(opts):
        
    # set up our channel
    conn_factory = ConnectionFactory()
    conn_factory.setUri(config['RABBITMQ_URI'])
    conn = conn_factory.newConnection()
    channel = conn.createChannel()
    channel.queueDeclare(opts.queue_name, False, False, False, None)
    channel.basicQos(1); # tells the channel we're only going to deliver one response before req acknowledgement 
    
    workers = [PdfExtractor(channel, opts) for i in xrange(opts.workers)]    
    
    log.info("creating pool with %d threads" % opts.workers)
    tpool = Executors.newFixedThreadPool(opts.workers)

    log.info("executing threads")
    futures = tpool.invokeAll(workers)

    log.info("shutting down thread pool")
    tpool.shutdown()

    try:
        if not tpool.awaitTermination(50, TimeUnit.SECONDS):
            log.info("thread pool not shutting down; trying again")
            tpool.shutdownNow()
            if not tpool.awaitTermination(50, TimeUnit.SECONDS):
                log.error("Pool did not terminate")
    except InterruptedException:
        log.info("exception during thread pool shutdown; trying again")
        tpool.shutdownNow()
        Thread.currentThread().interrupt()    
Пример #9
0
def run_stitch(filePath):
	basePath,baseName = os.path.split(filePath)
	imagePrefix = os.path.splitext(baseName)[0]
	resizeName = basePath + "/" + baseName + "_tiles/resized/"
	checkName = basePath + "/" + baseName + "_tiles/resized/" + imagePrefix + "_seq/"
	activeName = basePath + "/" + baseName + "_tiles"
	IJ.log("Stitching " + filePath + "...")
	if (not os.path.isdir(checkName)):
		thread = Thread.currentThread()
		originalThread = thread.getName()
		thread.setName("Run$_stitch_process")
		options = "choose=" + resizeName + " select=" + activeName + "/tile_info.txt image_prefix=" + imagePrefix
		Macro.setOptions(Thread.currentThread(),options)
		try:
			IJ.run("Stitch wrapper",options)
			IJ.log("succeeded")
			returnVal = 0
		except:
			IJ.log("failed")
			os.rmdir(checkName)
			returnVal = 1
		thread.setName(originalThread)
		Macro.setOptions(thread,None)
	else:
		IJ.log("skipped")
		returnVal = 2

	return returnVal
Пример #10
0
    def actionPerformed(self, actionEvent):
        global yara_rules
        global yara_path

        if actionEvent.getSource() is self.menuItem:
            yara_path = self._yara_exe_txtField.getText()
            yara_rules = self._yara_rules_txtField.getText()
            t = Thread(self)
            t.start()
        elif actionEvent.getSource() is self._yara_clear_button:
            # Delete the LogEntry objects from the log
            row = self._log.size()
            self._lock.acquire()
            self._log.clear()

            # Update the Table
            self.fireTableRowsDeleted(0, row)

            # Clear data regarding any selected LogEntry objects from the request / response viewers
            self._requestViewer.setMessage([], True)
            self._responseViewer.setMessage([], False)
            self._currentlyDisplayedItem = None
            self._lock.release()
        else:
            stdout.println("Unknown Event Received.")
Пример #11
0
 def run(self):
     i=0
     while PVUtil.getLong(pvs[2]) ==1:
         Thread.sleep(500)
         timerLabel.setPropertyValue("foreground_color", 
                     ColorFontUtil.YELLOW if i%2==0 else ColorFontUtil.RED)
         i=i+1
     timerLabel.setPropertyValue("foreground_color", ColorFontUtil.BLACK)
 def run(self):
     while True:
         connection = httplib.HTTPConnection("sleepingbeauty.herokuapp.com")
         connection.request("GET", "/rough_movements/last_time.txt")
         response = connection.getresponse()
         if response.status == 200:
             self.arduino.send_rough_data(int(response.read()))
         JThread.currentThread().sleep(ROUGH_TIME);
Пример #13
0
class Clock(object):
    """
    **pyj2d.time.Clock**
    
    * Clock.get_time
    * Clock.tick
    * Clock.tick_busy_loop
    * Clock.get_fps
    """

    def __init__(self):
        """
        Return Clock.
        """
        self.time = System.nanoTime()/1000000
        self.time_init = self.time
        self.time_diff = [25]*10
        self.pos = 0
        self.thread = Thread()

    def get_time(self):
        """
        Return time (in ms) between last two calls to tick().
        """
        return self.time_diff[self.pos]

    def tick(self, framerate=0):
        """
        Call once per program cycle, returns ms since last call.
        An optional framerate will add pause to limit rate.
        """
        if self.pos < 9:
            self.pos += 1
        else:
            self.pos = 0
        self.time = System.nanoTime()/1000000
        self.time_diff[self.pos] = (self.time-self.time_init)
        self.time_init = self.time
        if framerate:
            time_diff = sum(self.time_diff)/10
            time_pause = long( ((1.0/framerate)*1000) - time_diff )
            if time_pause > 0:
                self.thread.sleep(time_pause)
        return self.time_diff[self.pos]

    def tick_busy_loop(self, framerate=0):
        """
        Calls tick() with optional framerate.
        Returns ms since last call.
        """
        time_diff = self.tick(framerate)
        return time_diff

    def get_fps(self):
        """
        Return fps.
        """
        return 1000/(sum(self.time_diff)/10)
Пример #14
0
	def run(self):
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY)
		firstTime = 1
		while not self.stop_event.isSet():
			if not firstTime:
				sys.stdout.write("\010" + self.maskChar)
			firstTime = 0
			Thread.currentThread().sleep(1)
				
Пример #15
0
def delay(time):
    """
    **pyj2d.time.delay**
    
    Pause for given time (in ms). Return ms paused.
    """
    start = System.nanoTime()/1000000
    Thread.sleep(time)
    return (System.nanoTime()/1000000) - start
Пример #16
0
 def setUp(self):
     self.orig_context = Thread.currentThread().contextClassLoader
     class AbstractLoader(ClassLoader):
         def __init__(self):
             ClassLoader.__init__(self)
             c = self.super__defineClass("ContextAbstract", CONTEXT_ABSTRACT, 0,
                     len(CONTEXT_ABSTRACT), ClassLoader.protectionDomain)
             self.super__resolveClass(c)
     Thread.currentThread().contextClassLoader = AbstractLoader()
Пример #17
0
 def flip(self):
     """
     Repaint display.
     """
     self._rect_list = self._surface_rect
     try:
         SwingUtilities.invokeAndWait(self)
     except InterruptedException:
         Thread.currentThread().interrupt()
Пример #18
0
    def run(self):
  	me = Thread.currentThread( );
	me.setPriority(Thread.MIN_PRIORITY);
        while self.thread == Thread.currentThread():
            try:
                Thread.sleep(1)
            except InterruptedException:
                return
            self._draw()
Пример #19
0
 def __init__(self):
     if java.lang.Thread.currentThread().name == "main":
         # Do not clobber the thread name if the user set it to
         # something different
         kw = dict(name="MainThread")
     else:
         kw = {}
     Thread.__init__(self, **kw)
     import atexit
     atexit.register(self.__exitfunc)
Пример #20
0
 def shutdown_and_await_termination(pool, timeout):
     pool.shutdown()
     try:
         if not pool.awaitTermination(timeout, TimeUnit.SECONDS):
             pool.shutdownNow()
             if not pool.awaitTermination(timeout, TimeUnit.SECONDS):
                 print >> sys.stderr, "Pool did not terminate"
     except InterruptedException, ex:
         pool.shutdownNow()
         Thread.currentThread().interrupt()
Пример #21
0
def sleep(SLEEP_MINUTES):
        # time.sleep() cannot wake up again, so use Java Thread.sleep() instead
        # time.sleep(SLEEP_MINUTES*60)
    if isJython():

        from java.lang import Thread
        Thread.sleep(SLEEP_MINUTES * 60 * 1000)
    else:
        import time
        time.sleep(SLEEP_MINUTES * 60)
Пример #22
0
 def execute(self, runnable):
     runner = Runner(runnable)
     thread = Thread(runner, name='RobotFrameworkTimeoutThread')
     thread.setDaemon(True)
     thread.start()
     thread.join(int(self._timeout * 1000))
     if thread.isAlive():
         thread.stop()
         raise TimeoutError(self._error)
     return runner.get_result()
Пример #23
0
    def __init__(self, tName, workerConfig):
        JThread.__init__(self)

        self.logger = Logger.getLogger("wtGundamWarrior")
        # self.logger.setLevel(Level.DEBUG)

        self.config = workerConfig
        self.wq = self.config.workerQueue
        self.threadName = tName
        self.stopThread = False
        self.wrkItmsProcessed = 0
Пример #24
0
def main():
    sessionManager = createSessionManager()
    session = sessionManager.getSession(DOCBASE_NAME)
    myCabinet = createOrGetCabinet(session)
    sessionManager.release(session)

    count = countIndex()
    for i in range(count):
        work = workthread.workthread(i, myCabinet, sessionManager, DOCBASE_NAME)
        t = Thread(work, "workthread %d" % i)
        t.start()
Пример #25
0
 def delay(self, time):
     """
     **pyj2d.time.delay**
     
     Pause for given time (in ms). Return ms paused.
     """
     start = System.nanoTime()//1000000
     try:
         Thread.sleep(time)
     except InterruptedException:
         Thread.currentThread().interrupt()
     return (System.nanoTime()//1000000) - start
Пример #26
0
def startUpload(sessionManager, folder):
    count = 0
    apppath = os.path.dirname(os.path.abspath(sys.argv[0]))
    fobj = open(os.path.join(apppath, "DataFileInfo.csv"))
    lines = fobj.readlines()
    fobj.close()
    Tasks = []
    ThreadTasks = []
    totalCount = 0
    for line in lines[1:]:
        words = line.strip().split(",")
        fileName = words[4]
        countStr = words[-3]
        type = words[-1]
        count = int(countStr)
        totalCount = totalCount + count
        Tasks.append((fileName, count, type))

    eachThreadCount = totalCount / THREAD_COUNT
    for i in range(THREAD_COUNT - 1):
        ThreadTasks.append([])
        tasksLeftToAssign = eachThreadCount
        for j in range(len(Tasks)):
            (f, c, t) = Tasks[j]
            if c >= tasksLeftToAssign:
                ThreadTasks[i].append((f, tasksLeftToAssign, t))
                c = c - tasksLeftToAssign 
                tasksLeftToAssign = 0
            if c < tasksLeftToAssign and c > 0:
                ThreadTasks[i].append((f, c, t))
                tasksLeftToAssign = tasksLeftToAssign - c
                c = 0
            Tasks[j] = (f, c, t)
            if tasksLeftToAssign == 0:
                break

    ThreadTasks.append([])
    for (f, c, t) in Tasks:
        if c > 0:
            ThreadTasks[THREAD_COUNT - 1].append((f, c, t))

    i = 0
    for tt in ThreadTasks:
        for (f, c, t) in tt:
            src = os.path.join(apppath, f)
            tgt = os.path.join(apppath, "%s_src_thread_%d.txt" % (f, i))
            shutil.copyfile(src, tgt)
        i = i + 1

    for i in range(THREAD_COUNT):
        work = workthread.workthread(i, folder, sessionManager, DOCBASE_NAME, ThreadTasks[i])
        t = Thread(work, "workthread %d" % i)
        t.start()
 def run(self):
     before_time = None
     after_time = None
     time_diff = None
     sleep_time = None
     over_sleep_time = 0
     no_delays = 0
     excess = 0
     
     game_start_time = System.nanoTime()
     prev_stats_time = game_start_time
     before_time = game_start_time
     
     running = True
     
     while running:
         self.game_update()
         self.game_render()
         self.paint_screen()
         
         after_time = System.nanoTime()
         time_diff = after_time - before_time
         sleep_time = (self.period - time_diff) - over_sleep_time
         
         if sleep_time > 0:
             try:
                 Thread.sleep(sleep_time)
             except InterruptedException as e:
                 pass
             over_sleep_time = (System.nanoTime() - after_time) - sleep_time
         else:
             excess -= sleep_time
             over_sleep_time = 0
             
             if (no_delays + 1) >= self.NO_DELAYS_PER_YIELD:
                 Thread.yield()
                 no_delays = 0
         
         before_time = System.nanoTime()
         
         skips = 0
         
         while excess > self.period and skips < self.MAX_FRAME_SKIPS:
             excess -= self.period
             self.game_update()
             skips += 1
         
         self.frames_skipped += skips
         
         self.store_stats()
     
     self.print_stats()
     System.exit(0)
Пример #28
0
 def run(self):
     while self._initialized:
         channel_active = [self._channels[id] for id in self._channel_pool if self._channels[id]._active]
         if not channel_active:
             try:
                 self._thread.sleep(1)
             except InterruptedException:
                 Thread.currentThread().interrupt()
                 self.quit()
             continue
         if len(channel_active) > 1:
             for channel in channel_active:
                 try:
                     data, data_len, lvol, rvol = channel._get()
                 except AttributeError:
                     continue
                 self._mixer.setAudioData(data, data_len, lvol, rvol)
             data_len = self._mixer.getAudioData(self._byteArray)
             if data_len > 0:
                 try:
                     self._mixer.write(self._byteArray, 0, data_len)
                 except IllegalArgumentException:
                     nonIntegralByte = data_len % self._audio_format.getFrameSize()
                     if nonIntegralByte:
                         data_len -= nonIntegralByte
                         try:
                             self._mixer.write(self._byteArray, 0, data_len)
                         except (IllegalArgumentException, LineUnavailableException):
                             pass
                 except LineUnavailableException:
                     pass
         else:
             try:
                 data, data_len, lvol, rvol = channel_active[0]._get()
             except AttributeError:
                 data_len = 0
             if data_len > 0:
                 if lvol < 1.0 or rvol < 1.0:
                     data = self._mixer.processVolume(data, data_len, lvol, rvol)
                 try:
                     self._mixer.write(data, 0, data_len)
                 except IllegalArgumentException:
                     nonIntegralByte = data_len % self._audio_format.getFrameSize()
                     if nonIntegralByte:
                         data_len -= nonIntegralByte
                         try:
                             self._mixer.write(data, 0, data_len)
                         except (IllegalArgumentException, LineUnavailableException):
                             pass
                 except LineUnavailableException:
                     pass
     self._quit()
Пример #29
0
 def run(self):
     print("broad time...")
     if len(self.reg_obj_ip) > reg.i:
         reg.i += 5
         for k in self.reg_obj_ip:
             if k.isConnected() and not (k.isClosed()):
                 K = PrintStream(k.getOutputStream())
                 K.println("BroadCast Message....")
             else:
                 self.reg_obj_ip.remove(k)
     else:
         print("here")
         Thread.sleep(5000)
Пример #30
0
    def asynchronousMoveTo(self, newPos):
        self.iambusy = 1
        self.setPoint = float(newPos)
        self.ca.caput("ME01D-EA-TCTRL-01:RAMPST_S", 0)  # ramp off
        time.sleep(1)  # message does not get through epics if there is no wait
        self.ca.caput("ME01D-EA-TCTRL-01:RANGE_S", 5)  # heater at 50 W
        time.sleep(1)
        self.ca.caput("ME01D-EA-TCTRL-01:SETP_S",
                      float(newPos))  # set set point

        newThread = checkTemperatureThread(self)
        t = Thread(newThread)
        t.start()
 def asynchronousMoveTo(self, new_position):
     output_move = 99
     Thread.sleep(delayTime)
     try:
         if self.incli.isConfigured():
             self.incli.caput(new_position)
         else:
             self.incli.configure()
             self.incli.caput(new_position)
             self.incli.clearup()
     except Exception, e:
         print "error in moveTo", e.getMessage(), e, output_move
         raise e
Пример #32
0
 def rawAsynchronousMoveTo(self, new_position):
     '''start rocking between two limiting positions, 1 to start rocking, 0 to stop rocking'''
     if (float(new_position) != 1.0):
         if (float(new_position) != 0.0):
             print "must be 0 or 1: 1 to start rocking, 0 to stop rocking."
     if (float(new_position) == 1.0):
         self.thread = Thread(self, "Thread: " + self.getName())
         self.runThread = True
         self.thread.start()
     if (float(new_position) == 0.0):
         self.runThread = False
         self.thread = None
         self.pd.stop()
Пример #33
0
    def setUp(self):
        self.orig_context = Thread.currentThread().contextClassLoader

        class AbstractLoader(ClassLoader):
            def __init__(self):
                ClassLoader.__init__(self)
                c = self.super__defineClass("ContextAbstract",
                                            CONTEXT_ABSTRACT, 0,
                                            len(CONTEXT_ABSTRACT),
                                            ClassLoader.protectionDomain)
                self.super__resolveClass(c)

        Thread.currentThread().contextClassLoader = AbstractLoader()
Пример #34
0
 def asynchronousMoveTo(self, new_position):
     output_move = 99
     Thread.sleep(delayTime)
     try:
         if self.incli.isConfigured():
             self.incli.caput(new_position)
         else:
             self.incli.configure()
             self.incli.caput(new_position)
             self.incli.clearup()
     except Exception, e:
         print "error in moveTo", e.getMessage(), e, output_move
         raise e
Пример #35
0
    def __controlled_rampup_call__(self):
        '''
           Attempt to control thread starvation 
        '''

        # Block or not (depending of the configuration)
        self.token = GrinderQueue.take()

        # Token means we are using ramping mode (no thread mode)
        if self.token:
            # check abort, stop and options set on token (sleep for batch mode)
            if self.__checkTokenReceived():
                return

        try:

            # Increase the number of active session for this process
            with self.__class__.lockSession:
                self.__class__.activeSession += 1
                logger.trace('[CONTROL] active sessions: %d' %
                             (self.__class__.activeSession))

                # if number of active session is above a configurable threshold
                #  - clear the current waiting operation
                #  - sleep a bit to let some breath
                if self.__class__.activeSession >= Configuration.threshold_thread_active:

                    self.__class__.controlSessionCount += 1
                    logger.info(
                        '[CONTROL] Active sessions (%d) above threshold (%d) - clearing waiting tokens '
                        % (self.__class__.activeSession,
                           Configuration.threshold_thread_active))

                    # Clear the queue
                    GrinderQueue.clear()

                    # Block all inactive thread (normally none or a few)
                    Thread.sleep(Configuration.thread_wait_milli)

                    # return here execute the finally part.
                    return

            # The real work is done here ...
            self.__lanch_scenario__()

        # Release the active session counter in ANY case
        finally:
            with self.__class__.lockSession:
                self.__class__.activeSession -= 1
                logger.trace('[CONTROL] active sessions: %d' %
                             (self.__class__.activeSession))
Пример #36
0
    def run(self):
        while display.isActive():
            scanInfos = client.server.getScanInfos()
            findActive = False
            markedDone = False
            for scanInfo in scanInfos:
                if scanInfo.getId() == long(
                        display.getVar("LatestPointScanID")):
                    statusLabel.setPropertyValue(
                        "text",
                        scanInfo.getState().toString())
                if scanInfo.getState().isDone():
                    #mark table to dark gray if it is done.
                    if scanInfo.getId() == long(
                            display.getVar(
                                "LatestPointScanID")) and not markedDone:
                        for i in range(table.getRowCount()):
                            Display.getDefault().asyncExec(
                                SetRowColor(i, ColorFontUtil.DARK_GRAY))
                        markedDone = True
                    continue
                if scanInfo.getState().isActive():
                    scanNameLabel.setPropertyValue("text", scanInfo.getName())
                    commandLabel.setPropertyValue("text",
                                                  scanInfo.getCurrentCommand())
                    progressBar.setPropertyValue(
                        "pv_value",
                        scanInfo.getPercentage() / 100.0)
                    #Mark scanned points as green
                    if scanInfo.getId() == long(
                            display.getVar("LatestPointScanID")):
                        markedDone = False
                        for i in range(table.getRowCount()):
                            xpos = float(table.getCellText(i, 1))
                            ypos = float(table.getCellText(i, 2))
                            if (
                                    xpos == PVUtil.getDouble(pvs[1])
                                    and ypos == PVUtil.getDouble(pvs[2])
                                    and scanInfo.getPercentage() >=
                                    i * 100.0 / table.getRowCount()
                            ):  #To make sure the matched position is set from this scan
                                Display.getDefault().asyncExec(
                                    SetRowColor(i, ColorFontUtil.GREEN))

                    findActive = True

            if not findActive:
                scanNameLabel.setPropertyValue("text", "None")
                commandLabel.setPropertyValue("text", "")
                progressBar.setPropertyValue("pv_value", 0)
            Thread.sleep(200)
Пример #37
0
class Applet(JApplet, Runnable):

    def init(self):
        self.setBackground(Color.BLACK)
        self.jpanel = Panel(_app_size)
        self.getContentPane().add(self.jpanel)
        pyj2d.env.japplet = self
        self.event = pyj2d.event
        self.mousePressed = self.mousePress
        self.mouseReleased = self.mouseRelease
        self.mouseEntered = self.mouseEnter
        self.mouseExited = self.mouseExit
        self.mouseMoved = self.mouseMove
        self.keyPressed = self.keyPress
        self.keyReleased = self.keyRelease
        self.setFocusable(True)
        self.program = Program()
        self.thread = Thread(self)
        self.thread.start()

    def mousePress(self, event):
        self.event.mousePress = event
        self.event._updateQueue(event)

    def mouseRelease(self, event):
        self.event.mousePress = None
        self.event._updateQueue(event)

    def mouseEnter(self, event):
        self.requestFocus()

    def mouseExit(self, event):
        self.event.mousePress = None

    def mouseMove(self, event):
        self.event._updateQueue(event)

    def keyPress(self, event):
        self.event._updateQueue(event)

    def keyRelease(self, event):
        self.event._updateQueue(event)

    def run(self):
        self.program.update()
        self.stop()

    def stop(self):
        self.program.quit = True
        self.thread = None
Пример #38
0
 def btnApplyUpdate_click(self, *args):
     
   status = self.importManager.createStatus("ARENA2 Post Actualizando", self)
   self.taskStatusController.bind(status)
   self.setVisibleTaskStatus(True)
   self.btnClose.setEnabled(False)
   
   self.process = self.importManager.createPostUpdateProcess(
     self.cboWorkspace.getSelectedItem(),
     self.report,
     status
   )
   th = Thread(self.process, "ARENA2_postupdate")
   th.start()
Пример #39
0
 def run(self):
     if not self.arduino:
         self.connect_arduino()
     JThread.currentThread().sleep(START_TIME);
     self.serial_write("Time"+self.get_time()+"a")
     threads = [
         JThread(RoughMovementThread(self)),
         JThread(ReallyRoughMovementThread(self)),
         JThread(LightSwitchThread(self)),
         JThread(ArduinoListenerThread(self)),
         JThread(BluetoothWaitThread(self)),
     ]
     for thread in threads:
         thread.start()
Пример #40
0
class __Metronom:
    def __init__(self, q, func, nbConsumers,debug):
        print func
        self.t = Thread(__Metronom.__Producer(q,func,nbConsumers,debug), "TheMetronomProducer")         
        self.t.start()
        print "Metronom is started for func=%s with %d consumers..." % (func.__class__.__name__,nbConsumers)      
        self.debug=debug
        #self.isalive = True

    class __Producer(Runnable):
        '''
          A runnable inner class that just product tempo (Oject()) every Cadencer tempo 
        '''
        def __init__(self, q, func,nbConsumers,debug):
            self._queue = q
            self._cadencer = func
            self.nbConsumers=nbConsumers 
            self._inc=0
            self.debug=debug

                    
        def run(self):
            #print self._name
            while True:
                (time_to_sleep,is_break) = self._cadencer.next()
                # Condition to stop : -1
                if time_to_sleep<0:
                    break
                
                # Reset queue when changing rate
                if is_break:
                    self._queue.clear()
                    
                if self.debug:
                    print "Sleeping time for %d ms" % (time_to_sleep)
                Thread.sleep(long(time_to_sleep))
                self._inc = self._inc+1
                if self.debug:
                    print "Putting message %d " % time_to_sleep
                self._queue.put(time_to_sleep)
                if self.debug:
                    print "Bottle object sent"
                
            if self.debug:
                print "OK - i quit and i force consumers to stop ..."
            # The trick is to poison all consumer to force them to stop
            for k in range(self.nbConsumers):
                self._queue.put(-1)
                Thread.sleep(5)
Пример #41
0
 def update(self, rect_list=None):
     """
     Repaint display.
     Optional rect or rect list to specify regions to repaint.
     """
     if isinstance(rect_list, list):
         self._rect_list = rect_list
     elif rect_list:
         self._rect_list = [rect_list]
     else:
         self._rect_list = self._surface_rect
     try:
         SwingUtilities.invokeAndWait(self)
     except InterruptedException:
         Thread.currentThread().interrupt()
Пример #42
0
 def wait(self):
     """
     Return an event from the queue, or wait for an event if none present.
     """
     while True:
         try:
             self._lock()
             evt = self.eventQueue.pop(0)
             self.eventNum -= 1
             self.eventQueue.append(None)
             self._unlock()
             return evt
         except IndexError:
             self._unlock()
             Thread.sleep(10)
Пример #43
0
    def asynchronousMoveTo(self, newPos):
        self.iambusy = True
        self.setPoint = float(newPos)
        #repeat as sometimes the message does not get through
        self.ca.caput("ME01D-EA-TCTRL-01:SETP_S",
                      float(newPos))  # set set point
        time.sleep(4)
        self.ca.caput("ME01D-EA-TCTRL-01:SETP_S",
                      float(newPos))  # set set point
        time.sleep(4)

        print "Set temperature to ", newPos

        mythread = Thread(checkTemperatureThread(self))
        mythread.start()
Пример #44
0
 def wait(self):  #0.23
     """
     Return an event from the queue, or wait for an event if none present.
     """
     while True:
         if self.eventNum:
             self._lock()
             evt = self.JEvent(self.eventQueue.pop(0))
             self.eventNum -= 1
             self.eventQueue.append(None)
             self._unlock()
             return evt
         else:
             self._unlock()
             Thread.sleep(10)
Пример #45
0
    def btnAccept_click(self, *args):
        status = self.importManager.createStatus("ARENA2 tablas", self)
        self.taskStatusController.bind(status)
        self.setVisibleTaskStatus(True)
        self.btnClose.setEnabled(False)

        process = self.importManager.createTablesProcess(
            self.connectionPicker.get(),
            status,
            createBaseTables=self.chkCreateBaseTables.isSelected(),
            createDicTables=self.chkCreateDicTables.isSelected(),
            loadDics=self.chkLoadDic.isSelected(),
            createWorkspace=self.chkCreateWorkspace.isSelected())
        th = Thread(process, "ARENA2_createtables")
        th.start()
Пример #46
0
        def sendCommand(self, requestId, cmd, directTo):
            Utils.out("ConsoleController > sendCommand > 'cmd'")
            Utils.out(cmd)
            if cmd == 'clear':
                self.resetOutput()
                self._commandHistory.append(cmd)
                self.resetHistoryIndex()
                self.clearCmd()
                return
            cmdModified = cmd
            requestHttpMethod = self._parent.getRequestHttpService(requestId)
            #If I use virtual persistence and there's already a pwd set
            if Utils.shellController._virtualPersistence and self.pwd():
                #Then always prepend 'cd <pwd>' to any command executed. In reality we
                # always enter in the same directory, but because this shell keeps track
                # of where the user thinks he is, and always goes to that directory first
                # the illusion of a persistence is created
                cmdVirtual = "cd " + self.pwd()
                cmdModified = cmdVirtual + "; " + cmd
            requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified)
            Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start()
            self._commandHistory.append(cmd)
            self.resetHistoryIndex()
            self.clearCmd()

            if Utils.shellController._virtualPersistence:
                if cmd.startswith('cd '):
                    Utils.out("ConsoleController > sendCommand: detected 'cd '")
                    #ask for pwd
                    cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start()
                if Utils.shellController._tabCompletion:
                    #ask 'ls -1a' for tab-completion
                    # The first command, pwd is set here, but cmdVirtual ain't. But this
                    # also means we are at the entry directory anyway, so we can just ask ls
                    # and get the correct tab completion anyway
                    try:
                        cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX)
                    except:
                        cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
            else:
                if Utils.shellController._tabCompletion:
                    cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
Пример #47
0
    def setUp(self):
        super(PyLuceneThreadTestCase, self).setUp()

        self.classLoader = Thread.currentThread().getContextClassLoader()

        writer = self.getWriter(analyzer=StandardAnalyzer())

        doc1 = Document()
        doc2 = Document()
        doc3 = Document()
        doc4 = Document()
        doc1.add(Field("field", "one", TextField.TYPE_STORED))
        doc2.add(Field("field", "two", TextField.TYPE_STORED))
        doc3.add(Field("field", "three", TextField.TYPE_STORED))
        doc4.add(Field("field", "one", TextField.TYPE_STORED))

        writer.addDocument(doc1)
        writer.addDocument(doc2)
        writer.addDocument(doc3)
        writer.addDocument(doc4)
        writer.commit()
        writer.close()

        self.testData = [('one', 2), ('two', 1), ('three', 1),
                         ('five', 0)] * 500
        self.lock = threading.Lock()
        self.totalQueries = 0
Пример #48
0
 def test_path_in_pyclasspath(self):
     jar = self.prepareJar('classimport_Lib.jar')
     compiled = self.compileToJar(jar, 'Lib')
     Thread.currentThread().contextClassLoader = test_support.make_jar_classloader(jar)
     with test_support.DirsOnSysPath():
         sys.path = ['__pyclasspath__/Lib']
         self.checkImports('__pyclasspath__/Lib', compiled)
Пример #49
0
class JavaIntegrationTestCase(unittest.TestCase):
    """Verifies that Thread.__tojava__ correctly gets the underlying Java thread"""

    def test_interruptible(self):

        def wait_until_interrupted(cv):
            name = threading.currentThread().getName()
            with cv:
                while not JThread.currentThread().isInterrupted():
                    try:
                        cv.wait()
                    except InterruptedException, e:
                        break

        num_threads = 5
        unfair_condition = Condition()
        threads = [
            Thread(
                name="thread #%d" % i,
                target=wait_until_interrupted,
                args=(unfair_condition,)) 
            for i in xrange(num_threads)]

        for thread in threads:
            thread.start()
        time.sleep(0.1)

        for thread in threads:
            JThread.interrupt(thread)

        joined_threads = 0
        for thread in threads:
            thread.join(1.) # timeout just in case so we don't stall regrtest
            joined_threads += 1
        self.assertEqual(joined_threads, num_threads)
Пример #50
0
 def testEnrollInClass(self):
     """Integration Test for TurnitinReviewServiceImpl.enrollInClass
     TODO Change source code to make this test have better results to 
     verify against (ie. return the rMessage and rCode for instance)
     """
     user_serv = ComponentManager.get("org.sakaiproject.user.api.UserDirectoryService")
     tiiclassid = str(uuid.uuid1())
     tiiasnnid = str(uuid.uuid1())
     tiiemail = str(uuid.uuid1()) + "@sakaiproject.org"
     # SWG TODO Why does this fail if you create the Class first?
     self.tiireview_serv.createClass(tiiclassid)
     Thread.sleep(1000)
     self.tiireview_serv.createAssignment(tiiclassid, tiiasnnid )
     Thread.sleep(1000)
     self.tiireview_serv.enrollInClass(user_serv.getUserId("stud01"), 
                                     tiiemail, tiiclassid)
Пример #51
0
def init():
    cl = IJ.getClassLoader()
    if cl is not None:
        Thread.currentThread().setContextClassLoader(cl)
    print "init", cl
    ns = RT.var("clojure.core", "*ns*")
    warn_on_reflection = RT.var("clojure.core", "*warn-on-reflection*")
    unchecked_math = RT.var("clojure.core", "*unchecked-math*")
    compile_path = RT.var("clojure.core", "*compile-path*")
    Var.pushThreadBindings(ns, ns.get(), warn_on_reflection,
                           warn_on_reflection.get(), unchecked_math,
                           unchecked_math.get(), compile_path, "classes")
    in_ns = RT.var("clojure.core", "in-ns")
    refer = RT.var("clojure.core", "refer")
    in_ns.invoke(Symbol.intern("user"))
    refer.invoke(Symbol.intern("clojure.core"))
Пример #52
0
 def run(self, args, javaHome, jythonHome, jythonOpts):
     ''' creates a start script, executes it and captures the output '''
     (starterPath, outfilePath) = self.writeStarter(args, javaHome,
                                                    jythonHome, jythonOpts)
     try:
         process = Runtime.getRuntime().exec(starterPath)
         stdoutMonitor = StdoutMonitor(process)
         stderrMonitor = StderrMonitor(process)
         stdoutMonitor.start()
         stderrMonitor.start()
         while self.isAlive(process):
             Thread.sleep(300)
         return self.getOutput(outfilePath)
     finally:
         os.remove(starterPath)
         os.remove(outfilePath)
Пример #53
0
 def call(self):
     t = Thread.currentThread()
     if t.isInterrupted() or not t.isAlive():
         return None
     t0 = System.nanoTime()
     r = self.fn(*self.args, **self.kwargs)
     return r, (System.nanoTime() - t0) / 1000000.0
Пример #54
0
 def setscc(self):
     self.SCC = SdnControllerClient()
     self.sccThread = JavaThread(self.SCC)
     self.sccThread.start()
     self.VPNcallback = VpnCallback("MP-VPN Service", self)
     setcallback(self.VPNcallback)
     self.SCC.setCallback(self.VPNcallback)
Пример #55
0
    def __enter__(self):
        """Enter the runtime context related to this object."""
        system.db.setDatasourceEnabled(self.database, True)

        for _ in range(self.retries):
            Thread.sleep(1000)
            if self.status == "Valid":
                break
            if self.status == "Faulted":
                raise IOError("The database connection {!r} is {}.".format(
                    self.database, self.status))
        else:
            raise IOError(
                "The database connection {!r} could not be enabled.".format(
                    self.database))
        return self
Пример #56
0
    def setClassLoaderAndCheck(self, orig_jar, prefix, compile_path=''):
        # Create a new jar and compile prefer_compiled into it
        orig_jar = test_support.findfile(orig_jar)
        jar = os.path.join(self.temp_dir, os.path.basename(orig_jar))
        shutil.copy(orig_jar, jar)

        code = os.path.join(self.temp_dir, 'prefer_compiled.py')
        fp = open(code, 'w')
        fp.write('compiled = True')
        fp.close()
        py_compile.compile(code)
        zip = zipfile.ZipFile(jar, 'a')
        zip.write(
            os.path.join(self.temp_dir, 'prefer_compiled$py.class'),
            os.path.join(compile_path, 'jar_pkg', 'prefer_compiled$py.class'))
        zip.close()

        Thread.currentThread(
        ).contextClassLoader = test_support.make_jar_classloader(jar)
        import flat_in_jar
        self.assertEquals(flat_in_jar.value, 7)
        import jar_pkg
        self.assertEquals(prefix + '/jar_pkg/__init__.py', jar_pkg.__file__)
        from jar_pkg import prefer_compiled
        self.assertEquals(prefix + '/jar_pkg/prefer_compiled$py.class',
                          prefer_compiled.__file__)
        self.assert_(prefer_compiled.compiled)
        self.assertRaises(NameError, __import__, 'flat_bad')
        self.assertRaises(NameError, __import__, 'jar_pkg.bad')
Пример #57
0
def invokeAsynchronous(function, args=None, kwargs=None, description=None):
    """Invokes (calls) the given Python function on a different thread.

    This means that calls to invokeAsynchronous will return immediately,
    and then the given function will start executing asynchronously on a
    different thread. This is useful for long-running data intensive
    functions, where running them synchronously (in the GUI thread)
    would make the GUI non-responsive for an unacceptable amount of
    time.

    Args:
        function (object): A Python function object that will get
            invoked with no arguments in a separate thread.
        args: A list or tuple of Python objects that will be provided to
            the called function as arguments. Equivalent to the *
            operator. Optional.
        kwargs: A dictionary of keyword argument names to Python object
            values that will be provided to the called function as
            keyword arguments. Equivalent to the ** operator. Optional.
        description (str): A description to use for the asynchronous
            thread. Will be displayed on the current scope's diagnostic
            view for scripts. For Vision and the Designer, this would be
            the "Scripts" tab of the Diagnostics popup. For Perspective
            and the Gateway scope, this would be the Gateway's Running
            Scripts status page. Optional.

    Returns:
        Thread: The executing thread.
    """
    print(function, args, kwargs, description)
    return Thread()
Пример #58
0
 def tearDown(self):
     Thread.currentThread().contextClassLoader = self.orig_context
     sys.path = self.orig_path
     shutil.rmtree(self.temp_dir)
     for module in sys.modules.keys():
         if module not in self.modules:
             del sys.modules[module]
Пример #59
0
 def wait_until_interrupted(cv):
     name = threading.currentThread().getName()
     with cv:
         while not JThread.currentThread().isInterrupted():
             try:
                 cv.wait()
             except InterruptedException, e:
                 break
Пример #60
0
 def run(self):
     for i in range(10):
         # react to user pressing Cancel
         if Thread.interrupted():
             print('The task was interrupted')
             break
         print('Counter: %d' % i)
         time.sleep(1)