def sendCommand(self, requestId, cmd, directTo): Utils.out("ConsoleController > sendCommand > 'cmd'") Utils.out(cmd) if cmd == 'clear': self.resetOutput() self._commandHistory.append(cmd) self.resetHistoryIndex() self.clearCmd() return cmdModified = cmd requestHttpMethod = self._parent.getRequestHttpService(requestId) #If I use virtual persistence and there's already a pwd set if Utils.shellController._virtualPersistence and self.pwd(): #Then always prepend 'cd <pwd>' to any command executed. In reality we # always enter in the same directory, but because this shell keeps track # of where the user thinks he is, and always goes to that directory first # the illusion of a persistence is created cmdVirtual = "cd " + self.pwd() cmdModified = cmdVirtual + "; " + cmd requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start() self._commandHistory.append(cmd) self.resetHistoryIndex() self.clearCmd() if Utils.shellController._virtualPersistence: if cmd.startswith('cd '): Utils.out("ConsoleController > sendCommand: detected 'cd '") #ask for pwd cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX) requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start() if Utils.shellController._tabCompletion: #ask 'ls -1a' for tab-completion # The first command, pwd is set here, but cmdVirtual ain't. But this # also means we are at the entry directory anyway, so we can just ask ls # and get the correct tab completion anyway try: cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX) except: cmdTabComplete = Commands.ls(Commands.OS_LINUX) requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start() else: if Utils.shellController._tabCompletion: cmdTabComplete = Commands.ls(Commands.OS_LINUX) requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete) Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
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()
def __init__(self, func, nbConsumers, targetRuns, reporter=None): self.thread = Thread( __Metronom.__Producer(func, nbConsumers, targetRuns, reporter), "TheMetronomProducer") logger.info( "Metronom - INIT - started for func=%s with %d consumers..." % (func.__class__.__name__, nbConsumers))
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.")
def invokeAsynchronous(function, args=None, kwargs=None, description=None): """Invokes (calls) the given Python function on a different thread. This means that calls to invokeAsynchronous will return immediately, and then the given function will start executing asynchronously on a different thread. This is useful for long-running data intensive functions, where running them synchronously (in the GUI thread) would make the GUI non-responsive for an unacceptable amount of time. Args: function (object): A Python function object that will get invoked with no arguments in a separate thread. args: A list or tuple of Python objects that will be provided to the called function as arguments. Equivalent to the * operator. Optional. kwargs: A dictionary of keyword argument names to Python object values that will be provided to the called function as keyword arguments. Equivalent to the ** operator. Optional. description (str): A description to use for the asynchronous thread. Will be displayed on the current scope's diagnostic view for scripts. For Vision and the Designer, this would be the "Scripts" tab of the Diagnostics popup. For Perspective and the Gateway scope, this would be the Gateway's Running Scripts status page. Optional. Returns: Thread: The executing thread. """ print(function, args, kwargs, description) return Thread()
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 __init__(self): """ Return Clock. """ self.time = System.nanoTime() / 1000000 self.time_init = self.time self.time_diff = [25] * 10 self.pos = 0 self.thread = Thread()
def 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()
def __init__(self, console, history_file=default_history_file): Runtime.getRuntime().addShutdownHook(Thread(self)) self.history_file = history_file self.history = [] self.loadHistory() self.console = console self.index = len(self.history) - 1 self.last = ""
def __init__(self): # To store ordered by timestamp key self.heapQueue = [] # When we have to wake up a scenario, put in this queue self.sleeperQueue = Queue() # start the sleeper self.thread = Thread(TimeSleeper.__Sleeper(self), "TimeSleeper").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()
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 asynchronousMoveTo(self, newPos): self.iambusy = 1 self.setPoint = float(newPos) self.ca.caput("ME01D-EA-TCTRL-01:RAMPST_S", 0) # ramp off time.sleep(1) # message does not get through epics if there is no wait self.ca.caput("ME01D-EA-TCTRL-01:RANGE_S", 5) # heater at 50 W time.sleep(1) self.ca.caput("ME01D-EA-TCTRL-01:SETP_S", float(newPos)) # set set point newThread = checkTemperatureThread(self) t = Thread(newThread) t.start()
def 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()
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()
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()
def run(self): startButton.setEnabled(False) stopButton.setEnabled(True) resetButton.setEnabled(False) bar.setVisible(True) hourText.setEnabled(False) minText.setEnabled(False) secText.setEnabled(False) hour = PVUtil.getLong(hourPV) min = PVUtil.getLong(minPV) sec = PVUtil.getLong(secPV) #remember the values to be reset resetButton.setVar("hour", hour) resetButton.setVar("min",min) resetButton.setVar("sec",sec) timerLabel.setPropertyValue("foreground_color", ColorFontUtil.BLACK) timerLabel.setPropertyValue("text", "Time Left:") stopped=False total = hour*3600+min*60+sec for i in range(total,-1,-1): if not display.isActive(): return if PVUtil.getLong(pvs[0])==0: stopped = True break pvs[1].setValue(100-100*i/total) hourPV.setValue(int(i/3600)) minPV.setValue(int(i%3600/60)) secPV.setValue(int(i%60)) Thread.sleep(1000) timerLabel.setPropertyValue("foreground_color", ColorFontUtil.RED) if stopped: timerLabel.setPropertyValue("text", "Interrupted!") else: timerLabel.setPropertyValue("text", "Time's Up!!!") widget.executeAction(0) pvs[2].setValue(1) Thread(Blink()).start() startButton.setEnabled(True) stopButton.setEnabled(False) resetButton.setEnabled(True) bar.setVisible(False) hourText.setEnabled(True) minText.setEnabled(True) secText.setEnabled(True)
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 test_make_synchronized(self): doneSignal = CountDownLatch(10) class SynchedRunnable(Runnable): i = 0 def run(self): self.i += 1 doneSignal.countDown() run = synchronize.make_synchronized(run) runner = SynchedRunnable() for _ in xrange(10): Thread(runner).start() doneSignal. await () self.assertEquals(10, runner.i)
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()
def __init__(self, profilePath): self.__class__.cv_smpp.acquire() if self.__class__.smscDriver == None: try: self.__class__.smscDriver = _SMSCDriver(profilePath) self.__class__.smscDriverThread = Thread( self.__class__.smscDriver, "SMSCDriver") # self.__class__.smscDriverThread.setDaemon(True) except Exception, ex: logger.error('Error loading SMSC Profile : %s, reason: %s' % (profilePath, ex)) raise logger.debug('SMSC Server starting') self.__class__.smscDriverThread.start() logger.info('SMSC Server started in the thread %s' % (self.__class__.smscDriverThread.getName())) self.__class__.started = True
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.')
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 BigEndian format of AIFF and AU, use size of float type. The mixing is done by Mixer.class, compiled with 'javac Mixer.java'. For JAR creation include with 'jar uvf 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, float) 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._byteRate = ( self._audio_format.getSampleRate() * self._audio_format.getChannels() * (self._audio_format.getSampleSizeInBits()/8) ) self._bufferSize = self._mixer.getBufferSize() self._byteArray = jarray.zeros(self._bufferSize, 'b') for id in range(self._channel_max): self._get_channel(id) self.music = Music() self._initialized = True self._thread = Thread(self) self._thread.start() return None
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 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()
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 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()
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()
params.maxPlateauwidthSpringMesh = 200 params.useLegacyOptimizer = True # 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)
def collectData(self): mythread = Thread(collectDataThread(self)) mythread.start()