示例#1
0
    def btnImportar_click(self, *args):
        files = self.arena2filePicker.get()
        if files == None:
            return

        status = self.importManager.createStatus("ARENA2 Importador", self)
        self.taskStatusController.bind(status)
        self.setVisibleTaskStatus(True)
        self.btnClose.setEnabled(False)

        transforms = list()
        n = 0
        ws = self.cboWorkspace.getSelectedItem()
        for transform in self.importManager.getTransformFactories():
            if self.cltTransforms.getCheckedModel().isSelectedIndex(n):
                try:
                    transform.selfConfigure(ws)
                except:
                    ex = sys.exc_info()[1]
                    status.message(
                        "No es posible configurar workspace para la regla: " +
                        str(type(transform)))
                    logger(
                        "No es posible configurar workspace para la regla." +
                        str(ex), gvsig.LOGGER_ERROR, ex)
                    return

                transforms.append(transform.create(workspace=ws))
            n += 1

        self.process = self.importManager.createImportProcess(
            files, ws, self.report, status, transforms=transforms)
        th = Thread(self.process, "ARENA2_import")
        th.start()
示例#2
0
class ThreadedRunner(Runnable):

    def __init__(self, runnable):
        self._runnable = runnable
        self._notifier = Event()
        self._result = None
        self._error = None
        self._traceback = None
        self._thread = None

    def run(self):
        try:
            self._result = self._runnable()
        except:
            self._error, self._traceback = sys.exc_info()[1:]
        self._notifier.set()

    __call__ = run

    def run_in_thread(self, timeout):
        self._thread = Thread(self, name=TIMEOUT_THREAD_NAME)
        self._thread.setDaemon(True)
        self._thread.start()
        self._notifier.wait(timeout)
        return self._notifier.isSet()

    def get_result(self):
        if self._error:
            raise self._error, None, self._traceback
        return self._result

    def stop_thread(self):
        self._thread.stop()
示例#3
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.")
示例#4
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()
示例#5
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()
示例#6
0
文件: upload.py 项目: arunappulal/all
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()
示例#7
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 setValueAt(self, value, row, col):
   if 3 == col:
     old = self.getValueAt(row, col)
     if old == value:
       return
     # else, update value in the underlying data structure
     accepted[row] = value
     # ... and save the evaluation CSV file in a new thread
     # to avoid potentially slow operations in the event dispatch thread
     t = Thread(writeAccepted)
     t.setPriority(Thread.NORM_PRIORITY)
     t.start()
示例#9
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()
示例#10
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
示例#11
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()
示例#12
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)
示例#13
0
 def __init__(self, srcdir, session_id, hostname="localhost", port=8000):#{{{
     self.commands = {'quit':self.quit,
                      'add_bp':self.add_breakpoint,
                      'clear_bp':self.clear_breakpoint,
                      'list_bp':None,
                      'resume':self.resume,
                      'show_classes':self.printclasses,
                      'clearall_bp':self.clearall_breakpoints}
     log('debugger started.')
     self.session_id = session_id
     self.vm = VMConnection(hostname, port)
     self.eventwatcher = Thread( VirtualMachineEventHandler(self.vm.vm, self) )
     self.eventwatcher.start()
     commandreader = Thread(CommandReader('vim_jpda_com.' + str( self.session_id ), self.handle_command ))
     commandreader.start()
示例#14
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()
示例#15
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()
示例#16
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 "Changing temperature to %3.2f" % newPos

        if not self.runningThread:
            # if a temperature checking thread is not running from a previous pos command then start a new one
            mythread = Thread(checkTemperatureThread(self))
            mythread.start()
示例#17
0
	def actionPerformed(self, e):
		'''
		Event handler for the buttons.
		'''
		cmd = e.getActionCommand()
		if cmd=='Browse...':
			folder = IJ.getDirectory("Select the image folder")
			if not folder:
				return
			self.folderTextField.setText(folder)
			images = Uploader.getImageList(folder)
			self.nrOfImagesToUpload = len(images)
			self.inputFolder = folder
			self.statusTextField.setText(str(self.nrOfImagesToUpload) + ' images to upload...')
		if cmd=='Upload Images':
			print('upload')
			if self.nrOfImagesToUpload < 1:
				return
			else:
				# convert if ome checked. Add _lbl if ground-truth checked. upload
				self.statusTextField.setText('Uploading ' + str(self.nrOfImagesToUpload) + ' images...')
				imageFolder = self.folderTextField.getText()
				uploader = Uploader.getInstance(self.biaflows)
				uploader.addObserver(self)
				self.tmpFolder = None
				if self.convertToOMETIFCheckBox.getState() or self.uploadAsGroundTruthCheckBox.getState():
					self.statusTextField.setText('Converting ' + str(self.nrOfImagesToUpload) + ' images...')
					# convert and add '_lbl' if ground truth
					self.tmpFolder = imageFolder + 'biaflows_tmp/'
					suffix = ''
					if self.uploadAsGroundTruthCheckBox.getState():
						suffix = '_lbl'
					uploader.convertImagesInFolderToOME(imageFolder, self.tmpFolder, suffix)
					imageFolder = self.tmpFolder
				# upload
				pid = self.projectIDs[self.projectChoice.getSelectedIndex()]
				sid = self.storageIDs[self.storageChoice.getSelectedIndex()]
				self.statusTextField.setText('Uploading ' + str(self.nrOfImagesToUpload) + ' images...')
				uploader.setInputFolder(imageFolder)
				uploader.setProject(str(pid))
				uploader.setStorage(str(sid))
				thread = Thread(uploader)
				thread.start()
				# cleanup
				self.statusTextField.setText('Upload started.')
示例#18
0
 def btnApplyTransform_click(self, *args):
   status = self.importManager.createStatus("ARENA2 Post transform Actualizando", self)
   self.taskStatusController.bind(status)
   self.setVisibleTaskStatus(True)
   self.btnClose.setEnabled(False)
   
   transforms = list()
   n = 0
   for transform in self.importManager.getTransformFactories():
     if self.cltTransforms.getCheckedModel().isSelectedIndex(n):
       transforms.append(transform.create(workspace=self.cboWorkspace.getSelectedItem()))
     n+=1
     
   self.process = self.importManager.createPostTransformProcess(
     self.cboWorkspace.getSelectedItem(),
     self.report,
     status,
     expressionFilter=self.filterPicker.get(),
     transforms=transforms
   )
   th = Thread(self.process, "ARENA2_posttransform")
   th.start()
示例#19
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_files
            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()
        elif actionEvent.getSource() is self._yara_rules_select_files_button:
            fileChooser = JFileChooser()
            yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"])
            fileChooser.addChoosableFileFilter(yarFilter)
            fileChooser.setFileFilter(yarFilter)
            fileChooser.setMultiSelectionEnabled(True)
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
            ret = fileChooser.showOpenDialog(None)
            if ret == JFileChooser.APPROVE_OPTION:
                self._yara_rules_files.clear()
                for file in fileChooser.getSelectedFiles():
                    self._yara_rules_files.add(file.getPath())
                self._yara_rules_fileList.setListData(self._yara_rules_files)
        else:
            stdout.println("Unknown Event Received.")
    def wait_for_connection(self):
        local = None
        notifier = None
        connection = None
        try:
            local = LocalDevice.getLocalDevice()
            local.setDiscoverable(DiscoveryAgent.GIAC)
            uuid = UUID(80087355)  # "04c6093b-0000-1000-8000-00805f9b34fb"
            url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth"
            notifier = Connector.open(url)
        except Exception:
            print "Bluetooth Device is not available"
            return

        while True:
            try:
                print "waiting for connection..."
                connection = notifier.acceptAndOpen()
                processThread = JThread(ProcessConnectionThread(connection, self.arduino))
                processThread.start()
            except Exception:
                print "Bluetooth Device is not available"
                return
示例#21
0
  def btnCheckIntegrity_click(self, *args):
    
    self.btnClose.setEnabled(False)
    self.btnApplyUpdate.setEnabled(False)
    self.btnApplyTransform.setEnabled(False)
    self.btnCheckIntegrity.setEnabled(False)

    rules = list()
    n = 0
    for rule in self.importManager.getRuleFactories():
      if self.cltRules.getCheckedModel().isSelectedIndex(n):
        rules.append(rule.create(workspace=self.cboWorkspace.getSelectedItem()))
      n+=1
    if len(rules)==0 :
      self.btnClose.setEnabled(True)
      self.btnApplyUpdate.setEnabled(True)
      self.btnApplyTransform.setEnabled(True)
      self.btnCheckIntegrity.setEnabled(True)
      return 
      
    status = self.importManager.createStatus("ARENA2 Post Validando", self)
    self.taskStatusController.bind(status)
        
    self.setVisibleTaskStatus(True)

    self.process = self.importManager.createPostValidatorProcess(
      self.report,
      status=status,
      rules = rules,
      workspace=self.cboWorkspace.getSelectedItem(),
      expressionFilter=self.filterPicker.get()
    )
    self.process.add(self.showValidatorFinishMessage)
    self.process.add(self.activateButtons)
    th = Thread(self.process, "ARENA2_postvalidator")
    th.start()
示例#22
0
    def btnCheckIntegrity_click(self, *args):
        files = self.arena2filePicker.get()
        if files == None:
            return

        self.btnClose.setEnabled(False)
        self.btnImportar.setEnabled(False)
        self.btnCheckIntegrity.setEnabled(False)

        rules = list()
        n = 0
        for rule in self.importManager.getRuleFactories():
            if self.cltRules.getCheckedModel().isSelectedIndex(n):
                rules.append(
                    rule.create(workspace=self.cboWorkspace.getSelectedItem()))
            n += 1
        if len(rules) == 0:
            self.btnClose.setEnabled(True)
            self.btnImportar.setEnabled(True)
            self.btnCheckIntegrity.setEnabled(True)
            return

        status = self.importManager.createStatus("ARENA2 validando", self)
        self.taskStatusController.bind(status)

        self.setVisibleTaskStatus(True)

        self.process = self.importManager.createValidatorProcess(
            files,
            self.report,
            status=status,
            rules=rules,
            workspace=self.cboWorkspace.getSelectedItem())
        self.process.add(self.showValidatorFinishMessage)
        th = Thread(self.process, "ARENA2_validator")
        th.start()
示例#23
0
class App(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.modKey = pyj2d.event.modKey
        self.mousePressed = self.mousePress
        self.mouseReleased = self.mouseRelease
        self.mouseEntered = self.mouseEnter
        self.mouseExited = self.mouseExit
        self.mouseMoved = self.mouseMove
        self.mouseDragged = self.mouseDrag
        self.mouseWheelMoved = self.mouseWheelMove
        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.button] = True
        self.event._updateQueue(event, MouseEvent.MOUSE_PRESSED)

    def mouseRelease(self, event):
        self.event.mousePress[event.button] = False
        self.event._updateQueue(event, MouseEvent.MOUSE_RELEASED)

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

    def mouseExit(self, event):
        self.event.mousePress[1], self.event.mousePress[2], self.event.mousePress[3] = False, False, False
        for keycode in self.modKey:
            if self.event.keyPress[keycode]:
                self.event.keyPress[keycode] = False

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

    def mouseDrag(self, event):
        self.event._updateQueue(event, MouseEvent.MOUSE_MOVED)

    def mouseWheelMove(self, event):
        self.event._updateQueue(event, MouseEvent.MOUSE_PRESSED)

    def keyPress(self, event):
        if event.keyCode in self.modKey:
            self.event.keyPress[event.keyCode] = True
        self.event._updateQueue(event, KeyEvent.KEY_PRESSED)

    def keyRelease(self, event):
        if event.keyCode in self.modKey:
            self.event.keyPress[event.keyCode] = False
        self.event._updateQueue(event, KeyEvent.KEY_RELEASED)

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

    def stop(self):
        self.program.quit = True
        self.thread = None
示例#24
0
 def go(self):
     thread = Thread(self)
     thread.start()
示例#25
0
文件: mixer.py 项目: jggatc/pyj2d
class Channel(Runnable):
    """
    **pyj2d.mixer.Channel**
    
    * Channel.play
    * Channel.stop
    * Channel.pause
    * Channel.unpause
    * Channel.set_volume
    * Channel.get_volume
    * Channel.get_busy
    * Channel.get_sound
    """

    _mixer = None

    def __init__(self, id):
        self._id = id
        self._sound = None
        self._stream = None
        self._data = jarray.zeros(self._mixer._bufferSize, 'b')
        self._data_len = 0
        self._active = False
        self._pause = False
        self._loops = 0
        self._volume = 1.0
        self._lvolume = 1.0
        self._rvolume = 1.0
        self._mixer._register_channel(self)
        self._nonimplemented_methods()
        self._thread = Thread(self)
        self._thread.start()

    def _set_sound(self, sound):
        self._sound = sound
        self._stream = AudioSystem.getAudioInputStream(sound._sound_object)

    def run(self):
        return

    def _get(self):
        try:
            self._data_len = self._stream.read(self._data)
        except IOException:
            self._data_len = 0
        if self._data_len > 0:
            return (self._data, self._data_len, self._lvolume*self._sound._volume, self._rvolume*self._sound._volume)
        else:
            if not self._loops:
                self.stop()
            else:
                self._stream.close()
                self._set_sound(self._sound)
                if self._loops != -1:
                    self._loops -= 1
            return (self._data, self._data_len, 1.0, 1.0)

    def _play(self):
        self._volume = 1.0
        self._lvolume = 1.0
        self._rvolume = 1.0
        self._active = True

    def _play_repeat(self, loops):
        if loops > 0:
            self._loops = loops
        else:
            self._loops = -1
        self._play()

    def play(self, sound, loops=0, maxtime=0, fade_ms=0):
        """
        Play sound on channel.
        Argument sound to play and loops is number of repeats or -1 for continuous.
        """
        if self._sound:
            self.stop()
        self._set_sound(sound)
        if not loops:
            self._play()
        else:
            self._play_repeat(loops)
        return None

    def stop(self):
        """
        Stop sound on channel.
        """
        try:
            self._stream.close()
            self._stream = None
        except AttributeError:
            pass
        self._sound = None
        self._pause = False
        self._loops = 0
        self._active = False
        return None

    def pause(self):
        """
        Pause sound on channel.
        """
        if self._active:
            self._active = False
            self._pause = True
        return None

    def unpause(self):
        """
        Unpause sound on channel.
        """
        if self._pause:
            if self._stream:
                self._active = True
                self._pause = False
        return None

    def set_volume(self, volume, volume2=None):
        """
        Set channel volume of sound playing.
        Argument volume of value 0.0 to 1.0, setting for both speakers when single, stereo l/r speakers with second value.
        """
        if volume < 0.0:
            volume = 0.0
        elif volume > 1.0:
            volume = 1.0
        self._lvolume = volume
        if volume2:
            if volume2 < 0.0:
                volume2 = 0.0
            elif volume2 > 1.0:
                volume2 = 1.0
            self._rvolume = volume2
        else:
            self._rvolume = self._lvolume
            self._volume = volume
        return None

    def get_volume(self):
        """
        Get channel volume for current sound.
        """
        return self._volume

    def get_busy(self):
        """
        Check if channel is processing sound.
        """
        return self._active

    def get_sound(self):
        """
        Get sound open by channel.
        """
        return self._sound

    def _nonimplemented_methods(self):
        """
        Non-implemented methods.
        """
        self.fadeout = lambda *arg: None
        self.queue = lambda *arg: None
        self.get_queue = lambda *arg: None
        self.set_endevent = lambda *arg: None
        self.get_endevent = lambda *arg: 0
示例#26
0
"""    main.py
 Purpose: Final demo
 Author: Tiago Pimentel
        [email protected]
         Joao Felipe
        [email protected]
         Matheus Camargo
        [email protected]
 CSE 467 -- Embedded Computing Systems
 WUSTL, Spring 2013
 Date: Apr., 29, 2013

 Description:
    This is the main of the interface with internet/bluetooth for android

"""

from java.lang import Thread as JThread
from Arduino import Arduino

if __name__=='__main__':
    wait_thread = JThread(Arduino())
    wait_thread.start()
    
    
示例#27
0
from org.csstudio.opibuilder.scriptUtil import PVUtil, ConsoleUtil
from java.lang import Thread, Runnable


class MyTask(Runnable):
    def run(self):        
        display.getWidget("Start_Button_Py").setPropertyValue("visible", False)
        display.getWidget("Start_Button_JS").setPropertyValue("visible", False)
        display.getWidget("Progress_Bar").setPropertyValue("visible", True)
        
        for i in range(100, 0, -1):
            if not display.isActive():
                return
            if i%10==0:
                widget.setPropertyValue("text", "I'm going to finish in %s seconds..." % (i/10))
            pvs[1].setValue(100 - i)
            Thread.sleep(100)
        pvs[1].setValue(100)
        widget.setPropertyValue("text", "I'm done! Hit the button again to start me.")
        display.getWidget("Progress_Bar").setPropertyValue("visible", False)
        display.getWidget("Start_Button_Py").setPropertyValue("visible", True)
        display.getWidget("Start_Button_JS").setPropertyValue("visible", True)

thread =Thread(MyTask());
thread.start()
示例#28
0
class RockingMotorDuringCounting(ScannableMotionBase, Runnable):
    '''Create PD for continuous rocking motion of the specified scannable within the limits during scan'''
    def __init__(self, name, pd, lowerlimit, upperlimit):
        self.setName(name)
        self.setInputNames([name])
        self.pd=pd
        self.upperlimit=upperlimit
        self.lowerlimit=lowerlimit
        self.setLevel(5)
        self.runThread=False
        self.thread=None
        
    def atPointStart(self):
        '''start rocking motion'''
        self.start()
         
    def atPointEnd(self):
        '''stop rocking motion'''
        self.stop()
    
    def start(self):
        '''start rocking'''
        self.rawAsynchronousMoveTo(1.0)
        
    def stop(self):
        '''stop roking'''
        self.rawAsynchronousMoveTo(0.0)
    
    def run(self):
        '''rocking motion of the specified pd during scan'''
        moveToUpperLimit=True
        while(self.runThread):
            if not self.isBusy():
                if (moveToUpperLimit):
                    if (abs(float(float(self.getPosition())-float(self.upperlimit)))>0.01):
                        print "move to upper limit " + str(self.upperlimit)
                        moveToUpperLimit=True
                        self.pd.asynchronousMoveTo(self.upperlimit)
                        continue
                    else:
                        print "moving to lower limit"
                        self.pd.asynchronousMoveTo(self.lowerlimit)
                        moveToUpperLimit=False
                        continue
                    
                else:
                    if (abs(float(float(self.getPosition())-float(self.lowerlimit)))>0.01):
                        print "move to lower limit " + str(self.lowerlimit)
                        moveToUpperLimit=False
                        self.pd.asynchronousMoveTo(self.lowerlimit)
                        continue
                    else:
                        print "moving to upper limit"
                        self.pd.asynchronousMoveTo(self.upperlimit)
                        moveToUpperLimit=True
                        continue
            sleep(0.1)
                   
    def rawGetPosition(self):
        '''This method not applies for the object, but returns pd position to satisfy framework interface'''
        return self.pd.getPosition()
      
    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()         
            
    
    def isBusy(self):
        '''always return origianl pd's status'''
        return self.pd.isBusy();


    def toString(self):
        return self.name + " : " + str(self.getPosition())
              
            
    def getLowerLimit(self):
        return self.lowerlimit
    
    def setLowerLimit(self, value):
        self.lowerlimit=value
    
    def getUpperLimit(self):
        return self.upperlimit
    
    def setUpperLimit(self, value):
        self.upperlimit=value
示例#29
0
if __name__ == "__main__":

    from java.lang import Thread
    import datetime
    from strategies import random_signal_combos_generator, Strategy
    from signals import available_signals

    definition = {"symbol": "ES", "secType": "FUT", "expiry": "200712", "exchange": "GLOBEX", "currency": "USD"}
    signal_combos = random_signal_combos_generator(available_signals, 50)
    start_time = datetime.time(9, 30)  # times for the test data
    end_time = datetime.time(15, 45)  # should exit after this
    strategies = [Strategy(signals=combo, start=start_time, end=end_time) for combo in signal_combos]
    split = len(strategies) / 2  # divide over tasks
    start = datetime.datetime.now()
    t1 = Thread(TestRunner(1, definition, strategies[:split]))
    t1.start()
    t2 = Thread(TestRunner(2, definition, strategies[split:]))
    t2.start()
    t1.join()  # join here after t1 has finished
    t2.join()  # join here after t2 has finished
    end = datetime.datetime.now()
    print "finished crunching %s strategies, time: %s, %s seconds per " "strategy" % (
        len(strategies),
        str(end - start),
        round((end - start).seconds * 1.0 / len(strategies), 2),
    )

    for sss in strategies:
        rp = sss.report
        print rp["result_for_capacity_percentage"], rp["long_trades"], rp["short_trades"], rp[
            "sum_all_results_with_commission"
	def collectData(self):
		self.isCollecting = 1
		newThread = collectDataThread(self)
		t = Thread(newThread)
		t.start()
示例#31
0
文件: vpn.py 项目: cygmris/enos
class VPNService(Container, MultiPointVPNService):
    def __init__(self):
        Resource.__init__(self, "MultiPointVPNService")
        print "MultiPoint VPN Service is starting"
        self.vpnIndex = {}
        self.vpnIndexById = {}
        self.topology = None
        self.coretopology = None
        self.lock = threading.Lock()
        self.properties['mat'] = True  # Default.
        self.loadService()
        self.saveThread = Thread(target=self.autosave)
        self.saveThread.start()
        if self.topology != None:
            self.setscc()

    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)

    def settopos(self, popstoponame, coretoponame):
        self.properties['topology'] = popstoponame
        self.topology = Container.getContainer(self.properties['topology'])
        self.properties['coretopology'] = coretoponame
        self.coretopology = Container.getContainer(
            self.properties['coretopology'])
        # We can now set up the callback
        self.setscc()
        self.saveService()

    def shutdown(self):
        self.saveThread.stop()
        if self.sccThread != None:
            self.sccThread.stop()
            self.SCC.clearCallback()
        MultiPointVPNServiceFactory.delete()

    def autosave(self):
        while True:
            if not self.topology == None:
                self.saveService()
                for (x, vpn) in self.vpnIndex.items():
                    vpn.saveVPN()
            time.sleep(60)

    def saveService(self):
        self.properties['sid'] = self.sid
        if self.topology != None:
            self.properties['topology'] = self.topology.getResourceName()
        if self.coretopology != None:
            self.properties[
                'coretopology'] = self.coretopology.getResourceName()
        try:
            self.save()
        except:
            print "Failed to save VPN Service\n", sys.exc_info()[0]

    def loadService(self):
        stored = Container.getContainer(self.getResourceName())
        mapResource(obj=self, resource=stored)
        if 'topology' in self.properties:
            self.topology = Container.getContainer(self.properties['topology'])
        if 'coretopology' in self.properties:
            self.coretopology = Container.getContainer(
                self.properties['coretopology'])
        vpns = self.loadResources({"resourceType": "VPN"})
        for v in vpns:
            vpn = VPN(v.getResourceName())
            vpn.loadVPN(self)
            self.vpnIndex[v.getResourceName()] = vpn
            self.vpnIndexById[vpn.vid] = vpn
        if not 'mat' in self.properties:
            self.properties['mat'] = True

    def newVid(self):
        with self.lock:
            while True:
                v = random.randint(1, 65535)
                if not v in self.vpnIndexById:
                    return v

    def getSite(self, s):
        global sites
        if s in sites:
            return sites[s]
        else:
            return None

    def getHost(self, s):
        return tbns[s]

    def addVpn(self, vpn):
        self.vpnIndex[vpn.name] = vpn
        self.vpnIndexById[vpn.vid] = vpn
        self.saveResource(vpn)

    def createVPN(self, vpnname):
        if vpnname in self.vpnIndex:
            return None
        vpn = VPN(vpnname, vs=self)
        self.vid = self.newVid()
        self.addVpn(vpn)
        return vpn

    def deleteVPN(self, vpnname):
        if not vpnname in self.vpnIndex:
            print "vpn name %s not found" % vpnname
            return
        vpn = self.vpnIndex[vpnname]
        for h in vpn.hostsites.keys():
            self.delhostbymac(vpn, h)
        for s in vpn.vpnsites.values():
            self.delsite(vpn, s)
        for p in vpn.pops.values():
            self.delpop(vpn, p)
        self.vpnIndex.pop(vpn.name)
        self.vpnIndexById.pop(vpn.vid)
        self.deleteResource(vpn)
        print "VPN %s removed successfully." % (vpn.name)
        return True

    def getVPN(self, vpnname):
        if not vpnname in self.vpnIndex:
            return None
        return self.vpnIndex[vpnname]

    def addPOP(self, vpn, pop):
        if not vpn.addpop(pop):
            return False
        return True

    def deletePOP(self, vpn, pop):
        if not vpn.delpop(pop):
            return False
        return True

    def addSite(self, vpn, site, vlan):
        if not vpn.addsite(site, vlan):
            # possible issues: duplicated site
            return False
        return True

    def deleteSite(self, vpn, site):
        if not vpn.delsite(site):
            return False
        return True

    def addhostbymac(self, vpn, site, mac):
        if not vpn.addhostbymac(site, mac):
            print "Error while adding host."
            return
        print "Host %s has been added into VPN %s successfully at site %s" % (
            mac, vpn.name, site['name'])

    def delhostbymac(self, vpn, mac):
        if not vpn.delhostbymac(mac):
            print "Error while deleting host."
            return
示例#32
0
 def startChangingFiles(self, startMarFileNo, delay):
     stopThread = False
     newThread = ChangeMarFile(startMarFileNo, delay)
     t = Thread(newThread)
     t.start()
示例#33
0
class JGLBabalCanvas(Canvas, Runnable, KeyListener, ComponentListener):

    def __init__(self, w, h, map_file=None):
        self.initSize = Dimension(w, h)
        self.GL = jgl.GL()
        self.GLU = jgl.GLU(self.GL)
        self.GL.glXMakeCurrent(self, 0, 0)
        self.game = Game(map_file)
        self._resized = 0
        self._image = None
        self._image_source = None
        self.addKeyListener(self)
        self.addComponentListener(self)
        gl_draw.init(self.GL, self.GLU, self.game)

    def start(self):
        self.game.reset_timer()
        self.thread = Thread(self)
        self.thread.start()

    def stop(self):
        self.thread = None

    def preferredSize(self):
        return self.initSize

    def minimumSize(self):
        return self.initSize

    def update(self, g):
        self.paint(g)

    def paint(self, g):
        #print 'START paint'
        if self._image:
            g.drawImage(self._image, 0, 0, self)
        #print 'END paint'
    paint = make_synchronized(paint)

    def _draw(self):
        #print 'START draw'
        self.game.update()
        gl_draw.draw()
        if self._resized:
            self._image_source = self.GL.glXGetImageSource()
            self._image_source.setAnimated(1)
            self._image = self.createImage(self._image_source)
            self._resized = 0
            self.repaint()
        elif self._image_source:
            self._image_source.newPixels()                
        #print 'END draw'
    _draw = make_synchronized(_draw)            

    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()

    def keyPressed(self, e):
        code = e.getKeyCode()
        if code == KeyEvent.VK_LEFT:
            self.game.begin_left()
        elif code == KeyEvent.VK_RIGHT:
            self.game.begin_right()
        elif code == KeyEvent.VK_UP:
            self.game.begin_accel()
        elif code == KeyEvent.VK_DOWN:
            self.game.begin_decel()
        elif code == KeyEvent.VK_SPACE:
            self.game.begin_jump()
    keyPressed = make_synchronized(keyPressed)

    def keyReleased(self, e):
        code = e.getKeyCode()
        if code == KeyEvent.VK_LEFT:
            self.game.end_left()
        elif code == KeyEvent.VK_RIGHT:
            self.game.end_right()
        elif code == KeyEvent.VK_UP:
            self.game.end_accel()
        elif code == KeyEvent.VK_DOWN:
            self.game.end_decel()
        elif code == KeyEvent.VK_SPACE:
            self.game.end_jump()
    keyReleased = make_synchronized(keyReleased)

    def keyTyped(self, e):
        if e.getKeyChar() == 'p' or e.getKeyChar() == 'P':
            self.game.toggle_pause()
    keyTyped = make_synchronized(keyTyped)

    def componentResized(self, e):
        size = self.getSize()
        gl_draw.reshape(size.width, size.height)
        self._resized = 1
    componentResized = make_synchronized(componentResized)

    def componentMoved(self, e):
        pass # required for ComponentListener interface

    def componentHidden(self, e):
        pass # required for ComponentListener interface

    def componentShown(self, e):
        pass # required for ComponentListener interface
示例#34
0
 def startChangingFiles(self, startMarFileNo, delay):
     stopThread = False
     newThread = ChangeMarFile(startMarFileNo, delay)
     t = Thread(newThread)
     t.start()
示例#35
0
def DiscoveryMain(Framework):

    urlString = Framework.getDestinationAttribute(PARAM_SERVER_URL)
    credentialsId = Framework.getDestinationAttribute(PARAM_CREDENTIALS_ID)

    connectionRetryNumber = Framework.getParameter(
        PARAM_CONNECTION_RETRY_NUMBER)
    continuousMonitoring = Framework.getParameter(
        PARAM_EVENT_BASED_DISCOVERY_ENABLED)
    historyHours = Framework.getParameter(PARAM_HYSTORY_HOURS)

    isJobMonitoringSupported = _vmware_vim_base.isJobStateMonitoringSupported(
        Framework)

    if not isJobMonitoringSupported:
        Framework.reportWarning(
            'You are running job on UCMDB 8.03 or earlier, it cannot be gracefully stopped, only by restarting the probe.'
        )

    try:
        client = None
        try:
            clientFactory = vmware_vim.ClientFactory(Framework, urlString,
                                                     credentialsId)
            client = clientFactory.createClient()

            if client:
                agent = client.getAgent()

                apiVersion = vmware_vim.getApiVersion(agent)
                logger.debug("Target API version: %s" % apiVersion)

                logger.debug("Client type: %s" % agent.getClientType())

                crossClientHelper = vmware_vim.getCrossClientHelper(agent)

                module = vmware_vim.getVmwareModuleByApiVersion(apiVersion)

                monitor = module.getEventMonitor(agent, crossClientHelper,
                                                 Framework)
                monitor.setContinuousMonitoring(continuousMonitoring)
                monitor.setHistoryHours(historyHours)
                monitor.setRetryNumber(connectionRetryNumber)
                #monitor.setPageSize(5)
                #monitor.setFilterRecreationIntervalMinutes(5)

                vmMigratedEventListener = module.getVmMigratedEventListener(
                    agent, crossClientHelper)
                vmMigratedEventReporter = module.getVmMigratedEventReporter(
                    crossClientHelper, Framework)
                vmMigratedEventListener._addReporter(vmMigratedEventReporter)
                monitor.addListener(vmMigratedEventListener)

                vmPoweredOnEventListener = module.getVmPoweredOnEventListener(
                    agent, crossClientHelper)
                vmPoweredOnEventReporter = module.getVmPoweredOnEventReporter(
                    crossClientHelper, Framework)
                vmPoweredOnEventListener._addReporter(vmPoweredOnEventReporter)
                monitor.addListener(vmPoweredOnEventListener)

                if isJobMonitoringSupported:
                    jobMonitoringTask = _vmware_vim_base.JobStateCheckTask(
                        monitor, Framework)
                    jobMonitoringThread = Thread(jobMonitoringTask)
                    jobMonitoringThread.start()

                monitor.start()

        finally:
            client and client.close()

    except AxisFault, axisFault:
        faultType = _vmware_vim_base.getFaultType(axisFault)
        if faultType == 'InvalidLogin':
            msg = errormessages.makeErrorMessage(
                _vmware_vim_base.VimProtocol.DISPLAY, None,
                errormessages.ERROR_INVALID_USERNAME_PASSWORD)
            logger.debug(msg)
            Framework.reportError(msg)
        elif faultType == 'NoPermission':
            priviledgeId = axisFault.getPrivilegeId()
            msg = "User does not have required '%s' permission" % priviledgeId
            logger.debug(msg)
            errormessages.resolveAndReport(
                msg, _vmware_vim_base.VimProtocol.DISPLAY, Framework)
        else:
            msg = axisFault.dumpToString()
            logger.debug(msg)
            errormessages.resolveAndReport(
                msg, _vmware_vim_base.VimProtocol.DISPLAY, Framework)
示例#36
0
t1 = MyThread()
t1.start()
t1.join()
assert t1.count == 1, 'subclassing java.lang.Thread'

print_test('pass subclass back to java', 2)

class MyRun(Runnable):
	count = 0
	def run(self):
		self.count = self.count+1

run = MyRun()
t = Thread(run)
t.start()
t.join()
assert run.count == 1, 'subclassing java.lang.Thread'

print_test("invoke super's constructor", 2)

class MyThread(Thread):
	def __init__(self):
		self.name = "Python-"+self.name

t = MyThread()
assert t.name[:14] == "Python-Thread-", 'automatic constructor call'

class MyThread(Thread):
	def __init__(self):
		Thread.__init__(self, "Python-Thread")
示例#37
0
文件: App.py 项目: jggatc/pyj2d
class App(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.modKey = pyj2d.event.modKey
        self.mousePressed = self.mousePress
        self.mouseReleased = self.mouseRelease
        self.mouseEntered = self.mouseEnter
        self.mouseExited = self.mouseExit
        self.mouseMoved = self.mouseMove
        self.mouseDragged = self.mouseDrag
        self.mouseWheelMoved = self.mouseWheelMove
        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.button] = True
        self.event._updateQueue(event, MouseEvent.MOUSE_PRESSED)

    def mouseRelease(self, event):
        self.event.mousePress[event.button] = False
        self.event._updateQueue(event, MouseEvent.MOUSE_RELEASED)

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

    def mouseExit(self, event):
        self.event.mousePress[1], self.event.mousePress[2], self.event.mousePress[3] = False, False, False
        for keycode in self.modKey:
            if self.event.keyPress[keycode]:
                self.event.keyPress[keycode] = False

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

    def mouseDrag(self, event):
        self.event._updateQueue(event, MouseEvent.MOUSE_MOVED)

    def mouseWheelMove(self, event):
        self.event._updateQueue(event, MouseEvent.MOUSE_PRESSED)

    def keyPress(self, event):
        if event.keyCode in self.modKey:
            self.event.keyPress[event.keyCode] = True
        self.event._updateQueue(event, KeyEvent.KEY_PRESSED)

    def keyRelease(self, event):
        if event.keyCode in self.modKey:
            self.event.keyPress[event.keyCode] = False
        self.event._updateQueue(event, KeyEvent.KEY_RELEASED)

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

    def stop(self):
        self.program.quit = True
        self.thread = None
示例#38
0
 def switch(self):      # actually do function value change
     if self.throttle != None :
         t = Thread( Sequence( self.throttle ) )
         t.start()      
         self.onOffValue = not self.onOffValue
         self.setIcon()
示例#39
0
class CarbonCacheClient:
    def __init__(self, host, port, scenario_name=None):
        self.scenario_name = scenario_name
        self.host = host
        self.port = port
        self.sharedInstance = None
        self._numberFormat = NumberFormat.getInstance()
        self._numberFormat.setMinimumFractionDigits(1)
        self._numberFormat.setMaximumFractionDigits(3)
        self._nbCallSuccessSoFar = 0
        self._nbCall = 0
        self._nbCallError = 0
        self._nbCallErrorSoFar = 0
        self._nbCall_tps = 0
        self._injection_rate = 0
        self._sumTime = 0
        self._maxTime = 0
        self._lastRefresh = System.currentTimeMillis()
        self.CarbonCache = Thread(
            CarbonCacheClient.__AggregateReportThread(self, host, port),
            "TheCarbonCache")
        self.CarbonCache.start()

    def __repr__(self):
        return '[host=%s][port=%s][testname=%s]' % (self.host, self.port,
                                                    self.scenario_name)

    class __AggregateReportThread(Thread):
        def __init__(self, Reporter, host, port):
            self.Reporter = Reporter
            self.socket = socket.socket()
            try:
                self.socket.connect((host, port))
            except:
                print "unable to connect to Carbon Cache on %s Port %s" % (
                    host, port)
                raise

            def __del__(self):
                self.socket.close()

        def run(self):
            while True:
                timestamp = int(time.time())
                OneMessageSet = ""
                Thread.sleep(10000)
                ReportSet = self.Reporter.GetReportStructured()
                for ValueName in ReportSet:
                    message = "%s.%s %s %d\n" % (
                        self.Reporter.getClientIdentifier(), ValueName,
                        ReportSet[ValueName], timestamp)
                    OneMessageSet += message

                self.socket.sendall(OneMessageSet)

    def getClientLabel(self):
        return self.scenario_name or "grindertool"

    def getClientIdentifier(self):
        return self.scenario_name or "grindertool"

    def GetReportStructured(self):
        currentTime = System.currentTimeMillis()
        deltaTime = (currentTime - self._lastRefresh)
        NbCall_tps = 0.0
        avgTime = 0.0
        maxTime = 0.0

        if (deltaTime > 0):
            NbCall_tps = float(self._nbCall_tps * 1000) / deltaTime
            avg = 0
            if self._nbCall_tps > 0:
                avg = long(self._sumTime / self._nbCall_tps)
            avgTime = avg
            maxTime = self._maxTime
        else:
            NbCall_tps = 0
            avgTime = 0
            maxTime = 0

        self._maxTime = 0

        #         NowRunning = self._nbStarted - self._nbFinished
        #
        #         DeltaStarted = self._nbStarted - self._nbStartedTotal
        #         self._nbStartedTotal = self._nbStarted
        #
        #         DeltaStopped = self._nbFinished - self._nbStoppedTotal
        #         self._nbStoppedTotal = self._nbFinished

        DeltaSuccess = self._nbCall - self._nbCallSuccessSoFar
        self._nbCallSuccessSoFar = self._nbCall

        DeltaError = self._nbCallError - self._nbCallErrorSoFar
        self._nbCallErrorSoFar = self._nbCallError

        Reply = {
            "Cadence.InjRate": "%f" % (self._injection_rate),
            #             "Session.Started"  : "%d" % (DeltaStarted),
            #             "Session.Finished" : "%d" % (DeltaStopped),
            "Session.Running": "%d" % (self._nbRunningSessions),
            "NbCall.Success": "%d" % (DeltaSuccess),
            "NbCall.Error": "%d" % (DeltaError),
            "NbCall.tps": "%f" % (NbCall_tps),
            "Time.Avg": "%f" % (avgTime),
            "Time.Max": "%f" % (maxTime)
        }

        self._lastRefresh = currentTime

        return Reply

    def addNbStartedCount(self):
        self._nbStarted += 1

    def addNbFinishedCount(self):
        self._nbFinished += 1

    def addNbCallCount(self):
        self._nbCall += 1
        self._nbCall_tps += 1

    def addNbCallErrorCount(self):
        self._nbCallError += 1

    def setTime1(self, startTime, TimerName):
        NowTime = System.currentTimeMillis()
        lock = Lock()
        lock.acquire()
        duration = NowTime - startTime
        self._sumTime += duration
        if duration > self._maxTime:
            self._maxTime = duration
        lock.release()

    def setTPS(self, tps):
        self._injection_rate = tps

    def incrementSessions(self):
        self._nbRunningSessions += 1

    def decrementSessions(self):
        self._nbRunningSessions -= 1

    def setConcurrentSessions(self, nbSessions):
        self._nbRunningSessions = nbSessions
示例#40
0
class Debugger:
    def __init__(self, srcdir, session_id, hostname="localhost", port=8000):#{{{
        self.commands = {'quit':self.quit,
                         'add_bp':self.add_breakpoint,
                         'clear_bp':self.clear_breakpoint,
                         'list_bp':None,
                         'resume':self.resume,
                         'show_classes':self.printclasses,
                         'clearall_bp':self.clearall_breakpoints}
        log('debugger started.')
        self.session_id = session_id
        self.vm = VMConnection(hostname, port)
        self.eventwatcher = Thread( VirtualMachineEventHandler(self.vm.vm, self) )
        self.eventwatcher.start()
        commandreader = Thread(CommandReader('vim_jpda_com.' + str( self.session_id ), self.handle_command ))
        commandreader.start()
        #self.send_vim_keys("<Esc>:call Jy_DebuggerReady()<CR>")
    #}}}

    def vm_callback(self, next_event):#{{{
        if isinstance(next_event, BreakpointEvent):
            fileinfo = open('/home/mike/Desktop/cfiletemp.txt', 'w')
            #fileinfo=tempfile.TemporaryFile()
            log( next_event.location().sourceName() + ":" + str( next_event.location().lineNumber() ) )
            fileinfo.write( next_event.location().sourceName() + ":" + str( next_event.location().lineNumber() ) )
            result = self.eval_vim_command("JumpTo('" +fileinfo.name + "')")
            log(result)
            fileinfo.close()
        log(str(next_event))#}}}

    def quit(self, *args):#{{{
        log('quitting.')
        self.vm.vm.dispose()
        sys.exit(0)#}}}

    def printclasses(self, *args):#{{{
        for c in self.vm.vm.allClasses():
            try: sourcename = c.sourceName()
            except: sourcename = "(unknown)"
            log(c.name() + ' ' + sourcename)#}}}

    def resume(self, *args):
        self.vm.vm.resume()

    def add_breakpoint(self, *args):#{{{
        log('add breakpoint: ' + ','.join(args))
        filename, linenumber = args[0], int(args[1])
        classes = get_classrefs_from_filename(self.vm.vm, args[0])
        log(classes)
        if len(classes) == 1:
            locs = [l for l in classes[0].allLineLocations() if l.lineNumber()==linenumber]
            log(locs)
            if locs:
                bp_req = self.vm.vm.eventRequestManager().createBreakpointRequest(locs[0])
                bp_req.setSuspendPolicy(EventRequest.SUSPEND_NONE)
                bp_req.enable()
                log('added breakpoint.')#}}}

    def clearall_breakpoints(self, *args):#{{{
        self.vm.vm.eventRequestManager().deleteAllBreakPoints()
        log('clearall breakpoint: ' + ','.join(args))#}}}

    def clear_breakpoint(self, *args):#{{{
        log('clear breakpoint: ' + ','.join(args))#}}}

    def handle_command(self, command):#{{{
        log(command)
        commandargs = command.split('|')
        commandfunc = None
        try:
            if commandargs: commandfunc = self.commands.get(commandargs[0],None)
            if commandfunc: commandfunc(*commandargs[1:])
            else: log("received unknown command: " + ','.join(commandargs))
        except Exception:
            log(traceback.format_exc())
        except Throwable, t:
            log(t.getMessage()) #}}}
示例#41
0
class EpicsPVWithMonitorListener(PseudoDevice, MonitorListener, Runnable):
	'''create a scannable that monitors the EPICS PV value changes and update its value passively. 
	This value is used by a running thread to control the scan processing this object participates in.
	'''
	def __init__(self, name, pvstring, unitstring, formatstring):
		self.setName(name)
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(5)
		self.outcli=CAClient(pvstring)
		self.currenttemp=float(self.rawGetPosition())
		self.monitor=None
		self.thread=None
		self.runThread=False

	def atScanStart(self):
		'''prepare to start scan: creating channel, monitor, and start control thread'''
		if not self.outcli.isConfigured():
			self.outcli.configure()
			self.monitor=self.outcli.camonitor(self)
			self.thread=Thread(self,"Thread: "+self.getName())
			self.runThread=True
			self.thread.start()
	def atScanEnd(self):
		'''clean up after scan finished successfully: remove monitor, destroy channel, and stop control thread'''
		if self.outcli.isConfigured():
			self.outcli.removeMonitor(self.monitor)
			self.monitor=None
			self.outcli.clearup()
			self.runThread=False
			self.thread=None
			
	def rawGetPosition(self):
		''' return current position.'''
		output=0.0
		if not self.outcli.isConfigured():
			self.outcli.configure()
			output=float(self.outcli.caget())
			self.outcli.clearup()
		else:
			output=float(self.outcli.caget())
		return float(output)

	def rawAsynchronousMoveTo(self,position):
		'''Not implemented, this is only a monitoring object'''
		print "object " + self.getName()+" cannot be moved."
		return

	def rawIsBusy(self):
		'''monitoring object never busy'''
		return 0

	def monitorChanged(self, mevent):
		self.currenttemp = float(mevent.getDBR().getDoubleValue()[0])

	def run(self):
	#	print "Thread: " + self.getName() + " started"
		while (self.runThread):
			if (JythonServerFacade.getInstance().getScanStatus() == JythonStatus.RUNNING and self.currenttemp >= float(MAXTEMP)):
				JythonServerFacade.getInstance().pauseCurrentScan()	
				print "Scan paused as temperature " + self.getName() +" returns: "+str(self.currenttemp)
			elif (JythonServerFacade.getInstance().getScanStatus() == JythonStatus.PAUSED and self.currenttemp <= float(MINTEMP)):
				print "Scan resumed as temperature " + self.getName() +" returns: "+str(self.currenttemp)
				JythonServerFacade.getInstance().resumeCurrentScan()
			sleep(10)


	def stop(self):
		'''clean up after scan finished successfully: remove monitor, destroy channel, 
		and stop control thread on emergence stop or unexpected crash. If required, can be used to manually clean up the object.'''
		if not self.monitor == None:
			self.outcli.removeMonitor(self.monitor)
			self.monitor=None
		if self.outcli.isConfigured():	
			self.outcli.clearup()
		if not self.thread == None:
			self.runThread=False
			self.thread=None
示例#42
0
 def refresh(self):
     thread = Thread(RefreshRunnable(self))
     thread.start()
	def rawAsynchronousMoveTo(self,new_position):
	
		self.iambusy = 1
		newThread = moveScannableThread(self,new_position)
		t = Thread(newThread)
		t.start()
示例#44
0
文件: mixer.py 项目: jggatc/pyj2d
class Mixer(Runnable):
    """
    **pyj2d.mixer**
    
    * pyj2d.mixer.init
    * pyj2d.mixer.quit
    * pyj2d.mixer.get_init
    * pyj2d.mixer.stop
    * pyj2d.mixer.pause
    * pyj2d.mixer.unpause
    * pyj2d.mixer.set_num_channels
    * pyj2d.mixer.get_num_channels
    * pyj2d.mixer.set_reserved
    * pyj2d.mixer.find_channel
    * pyj2d.mixer.get_busy
    * pyj2d.mixer.Sound
    * pyj2d.mixer.Channel
    """

    def __init__(self):
        self._mixer = None
        Sound._mixer = self
        Channel._mixer = self
        self.Sound = Sound
        self.Channel = Channel
        self._channel_max = 8
        self._channels = {}
        self._sounds = {}
        self._channel_reserved = []
        self._channel_paused = []
        self._channel_reserves = [id for id in range(self._channel_max-1,-1,-1)]
        self._channel_pool = []
        self._lines = {}
        self._line_num = 0
        self._thread = None
        self._initialized = False
        self._nonimplemented_methods()

    def init(self, frequency=22050, size=-16, channels=2, buffer=4096):
        """
        Mixer initialization.
        Argument sampled frequency, bit size, channels, and buffer.
        Currently implements PCM 16-bit audio.
        Plays WAV, AIFF, and AU sampled audio.
        To specify the BigEndian format of AIFF and AU, use -16L for size.
        The mixing is done by Mixer.class, compiled with 'javac Mixer.java'.
        When a JAR is created, include with 'jar uvf Pyj2d_App.jar pyj2d/Mixer.class'.
        """
        if not self._initialized:
            encoding = {True:AudioFormat.Encoding.PCM_SIGNED, False:AudioFormat.Encoding.PCM_UNSIGNED}[size<0]
            channels = {True:1, False:2}[channels<=1]
            framesize = int((abs(size)/8) * channels)
            isBigEndian = isinstance(size,long)
            self._audio_format = AudioFormat(encoding, int(frequency), int(abs(size)), channels, framesize, int(frequency), isBigEndian)
            self._bufferSize = buffer
            try:
                self._mixer = AudioMixer(self._audio_format, self._bufferSize)
            except TypeError:
                self._mixer = None
                return None
            if not self._mixer.isInitialized():
                return None
            self._bufferSize = self._mixer.getBufferSize()
            self._byteArray = jarray.zeros(self._bufferSize, 'b')
            self._initialized = True
            self._thread = Thread(self)
            self._thread.start()
        return None

    def pre_init(self, frequency=22050, size=-16, channels=2, buffer=4096):
        """
        Mixer initialization.
        """
        self.init(frequency, size, channels, buffer)
        return None

    def quit(self):
        """
        Stop mixer processing and release resources.
        """
        self._initialized = False

    def _quit(self):
        self.stop()
        try:
            self._mixer.quit()
        except AttributeError:
            pass
        self._mixer = None

    def get_init(self):
        """
        Get the audio format initialized.
        """
        if self._initialized:
            frequency = int(self._audio_format.sampleRate)
            format = self._audio_format.sampleSizeInBits * {True:1,False:-1}[self._audio_format.bigEndian]
            channels = self._audio_format.channels
            return (frequency, format, channels)
        else:
            return None

    def stop(self):
        """
        Stop mixer channels.
        """
        for id in self._channel_pool:
            self._channels[id].stop()
        return None

    def pause(self):
        """
        Pause mixer channels.
        """
        for id in self._channel_pool:
            try:
                if self._channels[id]._active:
                    self._channel_paused.append(id)
                    self._channels[id].pause()
            except AttributeError:
                continue
        return None

    def unpause(self):
        """
        Unpause mixer channels.
        """
        for id in self._channel_paused:
            self._channels[id].unpause()
        self.channel_paused = []
        return None

    def set_num_channels(self, count):
        """
        Set maximum mixer channels.
        Argument channel count.
        """
        if count >= self._channel_max:
            for id in range(self._channel_max, count):
                self._channels[id] = None
            self._channel_max = count
        elif count >= 0:
                for id in range(count, self._channel_max):
                    self._channels[id].stop()
                    del self._channels[id]
                self._channel_max = count
        return None

    def get_num_channels(self):
        """
        Get maximum mixer channels.
        """
        return self._channel_max

    def set_reserved(self, count):
        """
        Reserve channel.
        Argument reserved channel count.
        """
        if count > self._channel_max:
            count = self._channel_max
        reserved_len = len(self._channel_reserved)
        if reserved_len:
            if reserved_len >= count:
                for i in range(reserved_len-count):
                    id = self._channel_reserved.pop()
                    self._channels[id]._reserved = False
                    self._channel_pool.append(id)
                count = 0
            else:
                count -= len(self._channel_reserved)
        for id in range(reserved_len, count+reserved_len):
            try:
                self._channels[id]._reserved = True
            except AttributeError:
                self._channels[id] = Channel(id)
            try:
                self._channel_pool.remove(id)
            except ValueError:
                pass
            self._channel_reserved.append(id)
        return None

    def find_channel(self, force=False):
        """
        Get an inactive mixer channel.
        Optional force attribute return longest running channel if all active.
        """
        try:
            channel = self._channel_reserves.pop()
            try:
                return self._channels[channel]
            except KeyError:
                channel = Channel(channel)
                return channel
        except IndexError:
            for id in self._channel_pool:
                if not self._channels[id]._active:
                    return self._channels[id]
            else:
                if force:
                    channel = None
                    longest = 0
                    for id in self._channel_pool:
                        try:
                            duration = self._channels[id]._stream.getMicrosecondPosition()
                            if duration > longest:
                                longest = duration
                                channel = self._channels[id]
                        except AttributeError:
                            channel = self._channels[id]
                            break
                    try:
                        channel.stop()
                        return channel
                    except AttributeError:
                        return None
                else:
                    return None

    def get_busy(self):
        """
        Check if mixer channels are actively processing.
        """
        for id in self._channel_pool:
            try:
                if self._channels[id]._active:
                    return True
            except AttributeError:
                continue
        return False

    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()

    def _register_channel(self, channel):
        id = channel._id
        if id < self._channel_max:
            try:
                if self._channels[id]._sound:
                    channel._sound = self._channels[id]._sound
                    channel._stream = self._channels[id]._stream
                    self._channels[id] = channel
            except KeyError:
                self._channels[id] = channel
                self._channel_pool.append(id)
        else:
            raise AttributeError("Channel not available.")

    def _register_sound(self, sound):
        self._sounds[sound._id] = sound

    def _nonimplemented_methods(self):
        """
        Non-implemented methods.
        """
        self.fadeout = lambda *arg: None
示例#45
0
class ContinuousRocking(ScannableGroup, Runnable):
    '''Create PD for continuous rocking motion of the specified scannable within its limits during a scan. '''
    def __init__(self, name, pd, upperlimit, lowerlimit):
        self.setName(name)
        self.setInputNames([name])
        self.pd=pd
        self.setUpperGdaLimits(upperlimit)
        self.setLowerGdaLimits(lowerlimit)
        self.setLevel(5)
        self.runThread=False
        self.thread=None
        
    def atScanStart(self):
        '''prepare to start scan: start rocking motion thread'''
        ScannableMotionBase.atScanStart()
        self.thread=Thread(self, "Thread: "+self.getName())
        self.runThread=True
        self.thread.start()
         
    def atScanEnd(self):
        '''clean up after scan finished successfully: stop rocking motion thread'''
        ScannableMotionBase.atScanEnd()
        self.runThread=False
        #self.thread.interrupt()
        self.thread=None
        self.pd.stop()         

    def run(self):
        '''rocking motion of the specified scannable during scan. This call must be non-blocking.'''
        while(self.runThread):
            if (JythonServerFacade.getInstance().getScanStatus() == JythonStatus.RUNNING):
                if not self.pd.isBusy():
                    self.pd.asynchronousMoveTo(self.getUpperGdaLimits()[0])
            if (JythonServerFacade.getInstance().getScanStatus() == JythonStatus.RUNNING):
                if not self.pd.isBusy():
                    self.pd.asynchronousMoveTo(self.getLowerGdaLimits()[0])
    
    def setLowerGdaLimits(self, lowerlimit):
        ScannableMotionBase.setLowerGdaLimits(lowerlimit)
        
    def getLowerGdaLimits(self):
        return ScannableMotionBase.getLowerGdaLimits()
    
    def setUpperGdaLimits(self, upperlimit):
        ScannableMotionBase.setUpperGdaLimits(upperlimit)
    
    def getUpperGdaLimits(self):
        return ScannableMotionBase.getUpperGdaLimits()
    
    def setRockingScannable(self, scnb):
        self.pd = scnb
        
    def getRockingScannable(self):
        return self.pd
    
    def rawGetPosition(self):
        '''This method not applies for the object, but returns pd position to satisfy framework interface'''
        return self.pd.getPosition()
      
    def rawAsynchronousMoveTo(self,new_position):
        '''No action, just pass'''
        pass
    
    def rawIsBusy(self):
        '''always return False'''
        return 0

    def toString(self):
        return self.name + " : " + str(self.getPosition())
              
    def stop(self):
        '''stop control thread on emergence stop or unexpected crash and clean up after scan finished successfully.
         If required, can be used to manually clean up the object.'''
        if not self.thread == None:
            self.runThread=False
            self.thread=None
            self.pd.stop()   
            
def DiscoveryMain(Framework):

    urlString = Framework.getDestinationAttribute(PARAM_SERVER_URL)
    credentialsId = Framework.getDestinationAttribute(PARAM_CREDENTIALS_ID)

    connectionRetryNumber = Framework.getParameter(PARAM_CONNECTION_RETRY_NUMBER)
    continuousMonitoring = Framework.getParameter(PARAM_EVENT_BASED_DISCOVERY_ENABLED)
    historyHours = Framework.getParameter(PARAM_HYSTORY_HOURS)

    isJobMonitoringSupported = _vmware_vim_base.isJobStateMonitoringSupported(Framework)

    if not isJobMonitoringSupported:
        Framework.reportWarning('You are running job on UCMDB 8.03 or earlier, it cannot be gracefully stopped, only by restarting the probe.')
    
    try:
        client = None
        try:
            clientFactory = vmware_vim.ClientFactory(Framework, urlString, credentialsId)
            client = clientFactory.createClient()
            
            if client:
                agent = client.getAgent()
                
                apiVersion = vmware_vim.getApiVersion(agent)
                logger.debug("Target API version: %s" % apiVersion)
                
                logger.debug("Client type: %s" % agent.getClientType())
                        
                crossClientHelper = vmware_vim.getCrossClientHelper(agent)
                
                module = vmware_vim.getVmwareModuleByApiVersion(apiVersion)
    
                monitor = module.getEventMonitor(agent, crossClientHelper, Framework)
                monitor.setContinuousMonitoring(continuousMonitoring)
                monitor.setHistoryHours(historyHours)
                monitor.setRetryNumber(connectionRetryNumber)
                #monitor.setPageSize(5)
                #monitor.setFilterRecreationIntervalMinutes(5)
                
                vmMigratedEventListener = module.getVmMigratedEventListener(agent, crossClientHelper)
                vmMigratedEventReporter =  module.getVmMigratedEventReporter(crossClientHelper, Framework)
                vmMigratedEventListener._addReporter(vmMigratedEventReporter)
                monitor.addListener(vmMigratedEventListener)
    
                vmPoweredOnEventListener = module.getVmPoweredOnEventListener(agent, crossClientHelper)
                vmPoweredOnEventReporter =  module.getVmPoweredOnEventReporter(crossClientHelper, Framework)
                vmPoweredOnEventListener._addReporter(vmPoweredOnEventReporter)
                monitor.addListener(vmPoweredOnEventListener)
    
                if isJobMonitoringSupported:
                    jobMonitoringTask = _vmware_vim_base.JobStateCheckTask(monitor, Framework)
                    jobMonitoringThread = Thread(jobMonitoringTask)
                    jobMonitoringThread.start()
                
                monitor.start()

        finally:
            client and client.close()
    
    except AxisFault, axisFault:
        faultType = _vmware_vim_base.getFaultType(axisFault)
        if faultType == 'InvalidLogin':
            msg = errormessages.makeErrorMessage(_vmware_vim_base.VimProtocol.DISPLAY, None, errormessages.ERROR_INVALID_USERNAME_PASSWORD)
            logger.debug(msg)
            Framework.reportError(msg)
        elif faultType == 'NoPermission':
            priviledgeId = axisFault.getPrivilegeId()
            msg = "User does not have required '%s' permission" % priviledgeId
            logger.debug(msg)
            errormessages.resolveAndReport(msg, _vmware_vim_base.VimProtocol.DISPLAY, Framework)
        else:
            msg = axisFault.dumpToString()
            logger.debug(msg)
            errormessages.resolveAndReport(msg, _vmware_vim_base.VimProtocol.DISPLAY, Framework)
示例#47
0
文件: vpn.py 项目: esnet/enos
class VPNService(Container,MultiPointVPNService):
    def __init__(self):
        Resource.__init__(self,"MultiPointVPNService")
        print "MultiPoint VPN Service is starting"
        self.vpnIndex = {}
        self.vpnIndexById = {}
        self.topology = None
        self.coretopology = None
        self.lock = threading.Lock()
        self.properties['mat'] = True # Default.
        self.loadService()
        self.saveThread = Thread(target=self.autosave)
        self.saveThread.start()
        if self.topology != None:
            self.setscc()

    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)

    def settopos(self, popstoponame, coretoponame):
        self.properties['topology'] = popstoponame
        self.topology = Container.getContainer(self.properties['topology'])
        self.properties['coretopology'] = coretoponame
        self.coretopology = Container.getContainer(self.properties['coretopology'])
        # We can now set up the callback
        self.setscc()
        self.saveService()

    def shutdown(self):
        self.saveThread.stop()
        if self.sccThread != None:
            self.sccThread.stop()
            self.SCC.clearCallback()
        MultiPointVPNServiceFactory.delete()

    def autosave(self):
        while True:
            if not self.topology == None:
                self.saveService()
                for (x,vpn) in self.vpnIndex.items():
                    vpn.saveVPN()
            time.sleep(60)

    def saveService(self):
        self.properties['sid'] = self.sid
        if self.topology != None:
            self.properties['topology'] = self.topology.getResourceName()
        if self.coretopology != None:
            self.properties['coretopology'] = self.coretopology.getResourceName()
        try:
            self.save()
        except:
            print "Failed to save VPN Service\n", sys.exc_info()[0]

    def loadService(self):
        stored = Container.getContainer(self.getResourceName())
        mapResource (obj=self,resource=stored)
        if 'topology' in self.properties:
            self.topology = Container.getContainer(self.properties['topology'])
        if 'coretopology' in self.properties:
            self.coretopology = Container.getContainer(self.properties['coretopology'])
        vpns = self.loadResources({"resourceType":"VPN"})
        for v in vpns:
            vpn = VPN(v.getResourceName())
            vpn.loadVPN(self)
            self.vpnIndex[v.getResourceName()] = vpn
            self.vpnIndexById[vpn.vid] = vpn
        if not 'mat' in self.properties:
            self.properties['mat'] = True

    def newVid(self):
        with self.lock:
            while True:
                v = random.randint(1,65535)
                if not v in self.vpnIndexById:
                    return v

    def getSite(self,s):
        global sites
        if s in sites:
            return sites[s]
        else:
            return None

    def getHost(self,s):
        return tbns[s]

    def addVpn(self,vpn):
        self.vpnIndex[vpn.name] = vpn
        self.vpnIndexById[vpn.vid] = vpn
        self.saveResource(vpn)

    def createVPN(self,vpnname):
        if vpnname in self.vpnIndex:
            return None
        vpn = VPN(vpnname,vs=self)
        self.vid = self.newVid()
        self.addVpn(vpn)
        return vpn

    def deleteVPN(self,vpnname):
        if not vpnname in self.vpnIndex:
            print "vpn name %s not found" % vpnname
            return
        vpn = self.vpnIndex[vpnname]
        for h in vpn.hostsites.keys():
            self.delhostbymac(vpn, h)
        for s in vpn.vpnsites.values():
            self.delsite(vpn, s)
        for p in vpn.pops.values():
            self.delpop(vpn, p)
        self.vpnIndex.pop(vpn.name)
        self.vpnIndexById.pop(vpn.vid)
        self.deleteResource(vpn)
        print "VPN %s removed successfully." % (vpn.name)
        return True

    def getVPN(self,vpnname):
        if not vpnname in self.vpnIndex:
            return None
        return self.vpnIndex[vpnname]

    def addPOP(self,vpn, pop):
        if not vpn.addpop(pop):
            return False
        return True

    def deletePOP(self,vpn, pop):
        if not vpn.delpop(pop):
            return False
        return True

    def addSite(self, vpn, site, vlan):
        if not vpn.addsite(site, vlan):
            # possible issues: duplicated site
            return False
        return True

    def deleteSite(self, vpn, site):
        if not vpn.delsite(site):
            return False
        return True

    def addhostbymac(self, vpn, site, mac):
        if not vpn.addhostbymac(site, mac):
            print "Error while adding host."
            return
        print "Host %s has been added into VPN %s successfully at site %s" % (mac, vpn.name, site['name'])

    def delhostbymac(self,vpn, mac):
        if not vpn.delhostbymac(mac):
            print "Error while deleting host."
            return
示例#48
0
t1.join()
assert t1.count == 1, 'subclassing java.lang.Thread'

print_test('pass subclass back to java', 2)


class MyRun(Runnable):
    count = 0

    def run(self):
        self.count = self.count + 1


run = MyRun()
t = Thread(run)
t.start()
t.join()
assert run.count == 1, 'subclassing java.lang.Thread'

print_test("invoke super's constructor", 2)


class MyThread(Thread):
    def __init__(self):
        self.name = "Python-" + self.name


t = MyThread()
assert t.name[:14] == "Python-Thread-", 'automatic constructor call'

class RockingMotion(ScannableMotionBase, Runnable):
    '''Create PD for continuous rocking motion of the specified scannable within the limits during scan'''
    def __init__(self, name, pd, lowerlimit, upperlimit):
        self.setName(name)
        self.setInputNames([name])
        self.pd=pd
        self.upperlimit=upperlimit
        self.lowerlimit=lowerlimit
        self.setLevel(5)
        self.runThread=False
        self.thread=None
        
    def atScanStart(self):
        '''prepare to start scan: start rocking motion thread'''
        self.thread=Thread(self, "Thread: "+self.getName())
        self.runThread=True
        self.thread.start()
         
    def atScanEnd(self):
        '''clean up after scan finished successfully: stop rocking motion thread'''
        self.runThread=False
        #self.thread.interrupt()
        self.thread=None
        self.pd.stop()         
    
    def start(self):
        '''start rocking'''
        self.rawAsynchronousMoveTo(1.0)
        
    def stop(self):
        '''stop roking'''
        self.rawAsynchronousMoveTo(0.0)
    
    def run(self):
        '''rocking motion of the specified pd during scan'''
        moveToUpperLimit=True
        while(self.runThread):
            if not self.rawIsBusy():
                if (moveToUpperLimit):
                    if (abs(float(float(self.getPosition())-float(self.upperlimit)))>0.01):
                        print "move to upper limit " + str(self.upperlimit)
                        moveToUpperLimit=True
                        self.pd.asynchronousMoveTo(self.upperlimit)
                        continue
                    else:
                        print "moving to lower limit"
                        self.pd.asynchronousMoveTo(self.lowerlimit)
                        moveToUpperLimit=False
                        continue
                    
                else:
                    if (abs(float(float(self.getPosition())-float(self.lowerlimit)))>0.01):
                        print "move to lower limit " + str(self.lowerlimit)
                        moveToUpperLimit=False
                        self.pd.asynchronousMoveTo(self.lowerlimit)
                        continue
                    else:
                        print "moving to upper limit"
                        self.pd.asynchronousMoveTo(self.upperlimit)
                        moveToUpperLimit=True
                        continue
                   
    def rawGetPosition(self):
        '''This method not applies for the object, but returns pd position to satisfy framework interface'''
        return self.pd.getPosition()
      
    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()         
            
    
    def rawIsBusy(self):
        '''always return origianl pd's status'''
        return self.pd.isBusy();


    def toString(self):
        return self.name + " : " + str(self.getPosition())
              
            
    def getLowerLimit(self):
        return self.lowerlimit
    
    def setLowerLimit(self, value):
        self.lowerlimit=value
    
    def getUpperLimit(self):
        return self.upperlimit
    
    def setUpperLimit(self, value):
        self.upperlimit=value
class GameBase(Runnable):
    components = GameComponent
    canvas = Canvas
    thread = Thread
    dbg = Graphics
    db_image = BufferedImage
    
    running = False
    is_paused = False
    game_over = False
    is_applet = False
    size_changed = False
    game_time = GameTime()
    updates = 0
    
    NO_DELAYS_PER_YIELD = 16
    MAX_FRAME_SKIPS = 5
    period = None
    game_start_time = None
    frames_skipped = None
    
    gelapsed_before = System.nanoTime()
    gelapsed_after = System.nanoTime()
    
    MAX_STAT_INTERVAL = 1
    NUM_FPS = 10
    stats_interval = 0
    prev_stats_time = 0
    total_elapsed_time = 0
    time_spend_in_game = 0
    frame_count = 0
    fps_store = []
    stats_count = 0
    average_fps = 0
    total_frames_skipped = 0
    ups_store = 0
    average_ups = 0
    df = DecimalFormat("0.##")


    def set_size(self, size):
        self.canvas.setSize(size)
        self.size_changed = True


    def set_resolution(self, size):
        self.set_size(size)


    def get_resolution(self):
        return Dimension(self.db_image.getWidth(), self.db_image.getHeight())


    def get_is_active(self):
        if self.is_paused == True:
            return False
        else:
            return True


    def get_is_applet(self):
        return self.is_applet


    def set_is_applet(self, flag):
        if type(flag) is not type(True):
            raise Exception("Flag passed to set_is_applet not a boolean. Got %s instead." % type(flag))
        self.is_applet = flag


    def get_stats_avg_fps(self):
        return self.average_fps


    def get_stats_avg_ups(self):
        return self.average_ups


    def __init__(self, size, fps):
        self.set_size(size)
        Component.setPreferredSize(size)
        Component.setMinimumSize(size)
        Component.setMaximumSize(size)
        
        Component.setBackground(Color.white)
        
        Component.setFocusable(True)
        Component.requestFocus()
        
        db_image = BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB)
        
        self.fps_store = self.NUM_FPS
        self.ups_store = self.NUM_FPS
        i = 0
        if i < self.NUM_FPS:
            self.fps_store[i] = 0
            self.ups_store[i] = 0
            i += 1


    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)


    def store_stats(self):
        self.frame_count += 1
        self.stats_interval += self.period
        
        if self.stats_interval >= self.MAX_STAT_INTERVAL:
            time_now = System.nanoTime()
            self.time_spend_in_game = time_now - self.game_start_time
            
            real_elapsed_time = time_now - self.prev_stats_time
            self.total_elapsed_time += real_elapsed_time
            
            self.total_frames_skipped += self.frames_skipped
            
            if self.total_elapsed_time > 0:
                actual_fps = self.frame_count / self.total_elapsed_time
                actual_ups = (self.frame_count + self.total_frames_skipped) / self.total_elapsed_time
            
            self.fps_store[self.stats_count % self.NUM_FPS] = actual_fps
            self.ups_store[self.stats_count % self.NUM_FPS] = actual_ups
            self.stats_count += 1
            
            i = 0
            if i < self.NUM_FPS:
                total_fps = self.fps_store[i]
                total_ups = self.ups_store[i]
                i += 1
            
            if self.stats_count < self.NUM_FPS:
                self.average_fps = total_fps / self.stats_count
                self.average_ups = total_ups / self.stats_count
            else:
                self.average_fps = total_fps / self.NUM_FPS
                self.average_ups = total_ups / self.NUM_FPS
            
            self.frames_skipped = 0
            self.prev_stats_time = time_now
            self.stats_interval = 0


    def game_update(self):
        self.gelapsed_after = System.nanoTime()
        
        self.game_time.elapsed_game_time.set_span(self.gelapsed_before, self.gelapsed_after)
        self.game_time.elapsed_real_time.set_span(self.gelapsed_before, self.gelapsed_after)
        
        self.game_time.total_game_time.set_span(self.game_start_time, self.gelapsed_after)
        self.game_time.total_real_time.set_span(self.game_start_time, self.gelapsed_after)
        
        self.gelapsed_before = System.nanoTime()
        
        if self.running and self.is_paused is not True and self.game_over is not True:
            for item in self.components.getComponents():
                item.update(self.game_time)
            self.updates += 1


    def get_render(self):
        if self.db_image is None or self.size_changed:
            size = Dimension(Component.getWidth(), Component.getHeight())
            self.set_size(size)
            Component.setPreferredSize(size)
            Component.setMinimumSize(size)
            Component.setMaximumSize(size)
            self.size_changed = False
            
            try:
                self.db_image = BufferedImage(Component.getWidth(), Component.getHeight(), BufferedImage.TYPE_INT_RGB)
            except JavaException as e:
                self.db_image = None
                System.out.println("Render Error: %s" % e)
                System.out.println("Render Error: Buffer not initialized properly")
                System.out.println("Render Error: Resolving...")


    def paint_screen(self):
        bs = Canvas.getBufferStrategy()
        if bs is None:
            Canvas.createBufferStrategy(3)
        
        g = bs.getDrawGraphics()
        g.drawImage(self.db_image, 0, 0, Component.getWidth(), Component.getHeight(), None)
        g.dispose()
        bs.show()


    def start_game(self):
        if self.running:
            return
        self.thread = Thread(self)
        self.thread.start()
        self.running = True


    def stop_game(self):
        if self.running is None:
            return
        self.thread.stop()
        self.running = False


    def set_preferred_fps(self, fps):
        self.period = 1000/fps


    def reset_elapsed_time(self):
        self.game_time.elapsed_game_time.set_span(0)
        self.game_time.elapsed_real_time.set_span(0)


    def add_component(self, game_component):
        game_component.initialize()
        game_component.load_content()
        self.components.add(game_component)


    def remove_component(self, game_component):
        game_component.unload_content()
        self.components.remove(game_component)


    def resume_game(self):
        self.is_paused = False


    def pause_game(self):
        self.is_paused = True


    def print_stats(self):
        System.out.println("Frame Count/Loss: %s / %s" % (self.frame_count, self.total_frames_skipped))
        System.out.println("Average FPS: %s" % self.df.format(self.average_fps))
        System.out.println("Average UPS: %s" % self.df.format(self.average_ups))
        System.out.println("TIme Spend: %s secs" % self.time_spend_in_game)
        System.out.println("Total Updates: %s" % self.updates)
        System.out.println("dbImage: %s" % self.db_image.toString())
示例#51
0
 def collectData(self):
     mythread = Thread(collectDataThread(self))
     mythread.start()
示例#52
0
class ContinuousRocking(ScannableGroup, Runnable):
    '''Create PD for continuous rocking motion of the specified scannable within its limits during a scan. '''
    def __init__(self, name, pd, upperlimit, lowerlimit):
        self.setName(name)
        self.setInputNames([name])
        self.pd = pd
        self.setUpperGdaLimits(upperlimit)
        self.setLowerGdaLimits(lowerlimit)
        self.setLevel(5)
        self.runThread = False
        self.thread = None

    def atScanStart(self):
        '''prepare to start scan: start rocking motion thread'''
        ScannableMotionBase.atScanStart()
        self.thread = Thread(self, "Thread: " + self.getName())
        self.runThread = True
        self.thread.start()

    def atScanEnd(self):
        '''clean up after scan finished successfully: stop rocking motion thread'''
        ScannableMotionBase.atScanEnd()
        self.runThread = False
        #self.thread.interrupt()
        self.thread = None
        self.pd.stop()

    def run(self):
        '''rocking motion of the specified scannable during scan. This call must be non-blocking.'''
        while (self.runThread):
            if (JythonServerFacade.getInstance().getScanStatus() ==
                    JythonStatus.RUNNING):
                if not self.pd.isBusy():
                    self.pd.asynchronousMoveTo(self.getUpperGdaLimits()[0])
            if (JythonServerFacade.getInstance().getScanStatus() ==
                    JythonStatus.RUNNING):
                if not self.pd.isBusy():
                    self.pd.asynchronousMoveTo(self.getLowerGdaLimits()[0])

    def setLowerGdaLimits(self, lowerlimit):
        ScannableMotionBase.setLowerGdaLimits(lowerlimit)

    def getLowerGdaLimits(self):
        return ScannableMotionBase.getLowerGdaLimits()

    def setUpperGdaLimits(self, upperlimit):
        ScannableMotionBase.setUpperGdaLimits(upperlimit)

    def getUpperGdaLimits(self):
        return ScannableMotionBase.getUpperGdaLimits()

    def setRockingScannable(self, scnb):
        self.pd = scnb

    def getRockingScannable(self):
        return self.pd

    def rawGetPosition(self):
        '''This method not applies for the object, but returns pd position to satisfy framework interface'''
        return self.pd.getPosition()

    def rawAsynchronousMoveTo(self, new_position):
        '''No action, just pass'''
        pass

    def rawIsBusy(self):
        '''always return False'''
        return 0

    def toString(self):
        return self.name + " : " + str(self.getPosition())

    def stop(self):
        '''stop control thread on emergence stop or unexpected crash and clean up after scan finished successfully.
         If required, can be used to manually clean up the object.'''
        if not self.thread == None:
            self.runThread = False
            self.thread = None
            self.pd.stop()
示例#53
0
# params.dampSpringMesh 
# params.maxNumThreads
# params.visualize

currentLayerPath = os.path.join(os.path.dirname(projectPath), 'currentLayer_' + namePlugin + '.txt')
currentWrittenLayer = fc.incrementCounter(currentLayerPath, increment = nLayersAtATime)
l = AtomicInteger(currentWrittenLayer)

# fc.startThreads(elasticMontage(), wait = 1, nThreads = nThreads) /!\ it does not work I do not understand why. Probably a java6 issue because it works in other scripts in java8 ...

threads = []
for p in range(nThreads):
	thread = Thread(elasticMontage)
	threads.append(thread)
	thread.start()
	time.sleep(0.5)
	
for thread in threads:
	thread.join()


IJ.log( namePlugin + ' layer ' + str(currentWrittenLayer))
fc.resizeDisplay(layerset)
project.save()

IJ.log('Sleeping in case the saving of the large project takes some time ...')
time.sleep(20)

# save all transforms
transformsPath = os.path.join(os.path.dirname(projectPath) , namePlugin + '_Transforms.txt')
示例#54
0
 def switch(self):  # actually do function value change
     if self.throttle != None:
         t = Thread(Sequence(self.throttle))
         t.start()
         self.onOffValue = not self.onOffValue
         self.setIcon()