Beispiel #1
0
    def keyPressed(self, event):
        if event.isControlDown() and event.isShiftDown(
        ):  # like in e.g. a web browser
            sign = {
                KeyEvent.VK_MINUS: -1,
                KeyEvent.VK_PLUS: 1,
                KeyEvent.VK_EQUALS: 1
            }.get(event.getKeyCode(), 0)
            if 0 == sign: return
            # Adjust font size of all UI components
            for component in components:
                font = component.getFont()
                if not font: continue
                size = max(8.0, font.getSize2D() + sign * 0.5)
                if size != font.getSize2D():
                    component.setFont(font.deriveFont(size))

            def repaint():
                # Adjust the height of a JTable's rows (why it doesn't do so automatically is absurd)
                for table in tables:
                    if table.getRowCount() > 0:
                        r = table.prepareRenderer(table.getCellRenderer(0, 0),
                                                  0, 0)
                        table.setRowHeight(
                            max(table.getRowHeight(),
                                r.getPreferredSize().height))
                for frame in frames:
                    if frame.isVisible():
                        frame.pack()
                        frame.repaint()

            SwingUtilities.invokeLater(repaint)
def run_example(network, runner):
    """Used to conveniently create a NengoGraphics instance
    with an existing Network model.

    """
    if isinstance(network, UINetwork):
        model = network
        model_ui = network
    elif isinstance(network, NetworkImpl):
        model = network
        nengo = NengoGraphics()

        task = TrackedStatusMsg("Creating Model UI")
        model_ui = UINetwork(model)
        nengo.world.ground.addChild(model_ui)
        model_ui.openViewer()
        task.finished()

    print "Running example: " + network.name

    # All UI functions and constructors must be invoked from the Swing
    # Event Thread

    if not isinstance(runner, Runnable):
        runner = make_runnable(runner)
    SwingUtilities.invokeLater(runner)
    def addVulnerability(self, issueKey, additionalInfo=None):
        print "TEST FOUND: [%s] - %s" % (issueKey, additionalInfo)

        # Add issue to summary list
        issue = SSLIssue(issueKey, self.url, self.helpers)
        if not (additionalInfo is None):
            issue.setIssueDetail(additionalInfo)

        self.issueList.append(issue)

        # Add to Burp issue
        if self.addToSitemap:
            scanIssues = self.callbacks.getScanIssues(self.url.getProtocol() +
                                                      "://" +
                                                      self.url.getHost())
            # Check if the issue already exists
            for oldIssue in scanIssues:
                try:
                    if oldIssue.getIssueName() == issue.getIssueName():
                        # exists
                        break
                except BaseException as e:
                    pass
            else:
                # Not exists, add new issue
                SwingUtilities.invokeLater(
                    ScannerRunnable(self.callbacks.addScanIssue, (issue, )))
Beispiel #4
0
 def clearList(self, event):
     self._extender._lock.acquire()
     oldSize = self._extender._log.size()
     self._extender._log.clear()
     SwingUtilities.invokeLater(
         UpdateTableEDT(self._extender, "delete", 0, oldSize - 1))
     self._extender._lock.release()
Beispiel #5
0
    def updateComboboxList(self, serv_dict):
        # Update the combobox items after location urls have been found
        def updateComboboxList_run(serv_dict):
            # Reinitialize the two comboboxes
            try:
                self.upnpcombo_targets.removeAllItems()
                self.upnpcombo_services.removeAllItems()
                self.upnpcombo_actions.removeAllItems()
            except BaseException as e:
                print(e)
            # First check if any UPnP service was found
            if not serv_dict:
                self.upnpcombo_targets.addItem("No UPnP services found")
                return
            # Build a dict of found IPs and location urls
            for scdp_url in serv_dict:
                parsed_scdp_url = urlparse(scdp_url)
                scdp_ip = parsed_scdp_url.netloc.split(":")[0]
                if scdp_ip in self.ip_service_dict:
                    # Append the new number to the existing array at this slot
                    self.ip_service_dict[scdp_ip].append(scdp_url)
                else:
                    # Create a new array in this slot
                    self.ip_service_dict[scdp_ip] = [scdp_url]

            # Add all the found IPs to the targets combo box
            for ip in self.ip_service_dict:
                self.upnpcombo_targets.addItem(ip)

            # Select the first element in the combobox by default - this will trigger the other comoboboxes to update
            self.upnpcombo_targets.setSelectedIndex(0)

        # Call the runnable method to update the plugin UI with results
        SwingUtilities.invokeLater(
            PyRunnable(updateComboboxList_run, serv_dict))
        def matchRegex(baseURL, res):
            toRet = []
            for (name, regStr, ret) in self.regexTableModel.data:
                matchObj = re.findall(regStr, res, re.M | re.I)
                for i in matchObj:
                    try:
                        if i.find('http://') == 0 or i.find('https://') == 0:
                            url = i
                        elif i[0] == '/':
                            url = host + i
                        else:
                            url = host + '/' + i

                        if url not in pageType:
                            pageType[url] = name
                            SwingUtilities.invokeLater(
                                CrawlerRunnable(self.resultTableModel.addRow,
                                                ([name, url], )))

                            if ret:
                                toRet.append(url)
                    except:
                        print("Error when trying to save result ", i,
                              sys.exc_info()[0],
                              sys.exc_info()[1])
            return toRet
Beispiel #7
0
def _swingRunner(func, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
    else:
        wrappedCode = _JythonCallable(func, args, kwargs)
        task = FutureTask(wrappedCode)
        SwingUtilities.invokeLater(task)
        return task.get()
Beispiel #8
0
def _swingRunner(func, *args, **kwargs):
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
    else:
        wrappedCode = _JythonCallable(func, args, kwargs)
        task = FutureTask(wrappedCode)
        SwingUtilities.invokeLater(task)
        return task.get()
Beispiel #9
0
	def addToLog(self, messageInfo, XSSimp, SQLiimp, SSTIimp, parameters, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description, req_time):
		requestInfo = self._helpers.analyzeRequest(messageInfo)
		method = requestInfo.getMethod()
		self._lock.acquire()
		row = self._log.size()
		self._log.add(LogEntry(self._callbacks.saveBuffersToTempFiles(messageInfo), requestInfo.getUrl(),method,XSSimp,SQLiimp,SSTIimp,req_time, parameters,resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp, xss_description, sqli_description, ssti_description)) # same requests not include again.
		SwingUtilities.invokeLater(UpdateTableEDT(self,"insert",row,row))
		self._lock.release()
Beispiel #10
0
def runSwingLater(func, *args, **kwargs):
    """
    Queues the given task to be run in the Event Dispatch Thread, regardless
    of whether the calling thread is the EDT itself.

    """
    runnable = RunnableWrapper(func, args, kwargs)
    SwingUtilities.invokeLater(runnable)
Beispiel #11
0
 def buttonInputReceived(self, evt):
     #        print("Wiimote Button event: ", evt)
     self.sync.acquire()
     self.evt = evt
     self.sync.release()
     SwingUtilities.invokeLater(
         self
     )  # Delegate processing to Swing thread (when we are here, we're in the WiiRemoteJ driver thread)
Beispiel #12
0
def runSwingLater(func, *args, **kwargs):
    """
    Queues the given task to be run in the Event Dispatch Thread, regardless
    of whether the calling thread is the EDT itself.

    """
    runnable = RunnableWrapper(func, args, kwargs)
    SwingUtilities.invokeLater(runnable)
Beispiel #13
0
 def __timer_noswing(self, *args):
     #print "#### >>>>>>>>>>> timer noswing enter."
     if self.timer != None:
         self.timer.cancel()
     self.__previous_cursor = self.tree.getCursor()
     SwingUtilities.invokeLater(self.__set_wait_cursor)
     self.exp = getExpansionState(self.tree)
     self.model = createTreeModel(self.mapContext)
     SwingUtilities.invokeLater(self.__timer_swing)
 def valueChanged(self, event):
   if event.getValueIsAdjusting():
     return
   # Must run later, when the event dispatch thread
   # has updated the selection
   def after():
     rowIndex = table.getSelectionModel().getLeadSelectionIndex()
     textarea.setText(applicants[rowIndex][2])
   SwingUtilities.invokeLater(after)
Beispiel #15
0
 def __timer_swing(self, *args):
     #print "#### >>>>>>>>>>> timer swing1 enter."
     if self.model != None:
         #print "#### >>>>>>>>>>> timer swing2."
         self.tree.setModel(self.model)
         self.tree.getModel().reload()
         setExpansionState(self.tree, self.exp)
         self.tree.revalidate()
         self.tree.repaint()
     SwingUtilities.invokeLater(self.__restore_cursor)
        def selectWhenRightClickEvent(event):
            def select(e):
                rowAtPoint = self.resultTable.rowAtPoint(
                    SwingUtilities.convertPoint(self.resultTablePopupMenu,
                                                Point(0, 0), self.resultTable))
                if rowAtPoint > -1:
                    self.resultTable.setRowSelectionInterval(
                        rowAtPoint, rowAtPoint)

            SwingUtilities.invokeLater(CrawlerRunnable(select, (event, )))
Beispiel #17
0
def saveTable():
    def after():
        # UI elements to alter under the event dispatch thread
        note_status.setText("Saved.")
        edit_note.setEnabled(True)
        save_note.setEnabled(False)

    # Repeatedly attempt to write the CSV until there are no more updates,
    # in which case the scheduled thread (see below) will pause for a bit before retrying.
    while requested_save_csv.getAndSet(False):
        writeCSV(csv_image_notes, header, entries)
        SwingUtilities.invokeLater(after)
    def buildNetwork(self, network):
        network.name = "Integrator"

        # Util.debugMsg("Network building started")

        f = ConstantFunction(1, 1.0)
        input = FunctionInput("input", [f], Units.UNK)

        # uiViewer.addNeoNode(uiInput);

        ef = NEFEnsembleFactoryImpl()
        integrator = ef.make("integrator", 500, 1, "integrator1", False)
        interm = integrator.addDecodedTermination("input", [[tau]], tau, False)
        fbterm = integrator.addDecodedTermination("feedback", [[1.0]], tau, False)

        network.addNode(integrator)
        time.sleep(1)
        network.addNode(input)
        time.sleep(1)
        # UINEFEnsemble uiIntegrator = new UINEFEnsemble(integrator);
        # uiViewer.addNeoNode(uiIntegrator);
        # uiIntegrator.collectSpikes(true);

        # UITermination uiInterm =
        # uiIntegrator.showTermination(interm.getName());
        # UITermination uiFbterm =
        # uiIntegrator.showTermination(fbterm.getName());

        network.addProjection(input.getOrigin(FunctionInput.ORIGIN_NAME), interm)
        time.sleep(0.5)
        network.addProjection(integrator.getOrigin(NEFEnsemble.X), fbterm)
        time.sleep(0.5)

        # Test removing projections
        network.removeProjection(interm)
        time.sleep(0.5)
        # add the projection back
        network.addProjection(input.getOrigin(FunctionInput.ORIGIN_NAME), interm)
        time.sleep(0.5)
        # Add probes
        integratorXProbe = network.simulator.addProbe("integrator", NEFEnsemble.X, True)
        time.sleep(0.5)
        # Test adding removing probes
        network.simulator.removeProbe(integratorXProbe)
        time.sleep(0.5)
        # add the probe back
        network.simulator.addProbe("integrator", NEFEnsemble.X, True)
        time.sleep(0.5)

        SwingUtilities.invokeLater(make_runnable(self.doPostUIStuff))
Beispiel #19
0
def showTable(rows,
              title="Table",
              column_names=None,
              dataType=Number,
              width=400,
              height=500,
              showTable=True,
              windowClosing=None,
              onCellClickFn=None,
              onRowClickFn=None):
    """
     rows: list of lists of numbers.
     title: for the JFrame
     column_names: list of strings, or None
     width: defaults to 400 px
     height: defaults to 500 px
     showTable: whether to show the JFrame.
     windowClosing: an optional function to execute when the table's JFrame is closed.
     onClickCellFn: an optional function to execute when a table's cell is clicked, and receiving 3 args: row index, col index, cell value.
     onRowCellFn: an optinal function to execute when a table's row is clicked, and receiving as args the whole row.
     
     return: a tuple with the JTable and the JFrame
  """
    table_data = DataTable(rows,
                           column_names=column_names,
                           onCellClickFn=onCellClickFn,
                           onRowClickFn=onRowClickFn)
    table = JTable(table_data)
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
    #table.setAutoCreateRowSorter(True) # to sort the view only, not the data in the underlying TableModel
    sorter = TableRowSorter(table_data)
    sorter.setComparator(0, Comparator.naturalOrder())
    sorter.setComparator(1, Comparator.naturalOrder())
    sorter.setComparator(2, Comparator.naturalOrder())
    table.setRowSorter(sorter)

    frame = JFrame(title) if windowClosing is None else JFrame(
        title, windowClosing=windowClosing)
    jsp = JScrollPane(table)
    jsp.setMinimumSize(Dimension(width, height))
    frame.getContentPane().add(jsp)

    def show():
        frame.pack()
        frame.setVisible(True)

    if showTable:
        SwingUtilities.invokeLater(show)

    return table, frame
    def undoAction(self):
        """Undo the action."""
        if not self.finished:
            messages.showError("Action was never done, so it can't be undone")
            return

        """Does the action layer, starts an appropriate thread"""
        if self.spawn_thread and SwingUtilities.isEventDispatchThread():
            threading.Thread(target=self.undoInternal).start()
        elif self.spawn_thread or SwingUtilities.isEventDispatchThread():
            # In the thread we want to be
            self.undoInternal()
        else:
            SwingUtilities.invokeLater(RunWrapper(self.undoInternal))
Beispiel #21
0
def runSwing(func, *args, **kwargs):
    """
    Runs the given function in the Event Dispatch Thread.
    If this is invoked inside the EDT, the given function will be run normally.
    Otherwise, it'll be queued to be run later.
    
    :return: None

    """
    if SwingUtilities.isEventDispatchThread():
        func(*args, **kwargs)
    else:
        runnable = RunnableWrapper(func, args, kwargs)
        SwingUtilities.invokeLater(runnable)
Beispiel #22
0
def runSwing(func, *args, **kwargs):
    """
    Runs the given function in the Event Dispatch Thread.
    If this is invoked inside the EDT, the given function will be run normally.
    Otherwise, it'll be queued to be run later.
    The return value from the target function will not be available.

    :return: None

    """
    if SwingUtilities.isEventDispatchThread():
        func(*args, **kwargs)
    else:
        runnable = RunnableWrapper(func, args, kwargs)
        SwingUtilities.invokeLater(runnable)
Beispiel #23
0
def _swingRunner(func, *args, **kwargs):
    # the naming of this function, along with _swingWaitForResult, is kinda
    # misleading; both functions will "wait" for the result (due to the get()).
    # the difference between the two is that this function "wraps" invokeLater,
    # while _swingWaitForResult "wraps" invokeAndWait.
    #
    # the real world difference is that this function appends to the end of the
    # event dispatch thread, while _swingWaitForResult puts its Task at the
    # beginning of the queue.
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
    else:
        wrappedCode = _JythonCallable(func, args, kwargs)
        task = FutureTask(wrappedCode)
        SwingUtilities.invokeLater(task)
        return task.get()
Beispiel #24
0
def _swingRunner(func, *args, **kwargs):
    # the naming of this function, along with _swingWaitForResult, is kinda
    # misleading; both functions will "wait" for the result (due to the get()).
    # the difference between the two is that this function "wraps" invokeLater,
    # while _swingWaitForResult "wraps" invokeAndWait.
    #
    # the real world difference is that this function appends to the end of the
    # event dispatch thread, while _swingWaitForResult puts its Task at the
    # beginning of the queue.
    if SwingUtilities.isEventDispatchThread():
        return func(*args, **kwargs)
    else:
        wrappedCode = _JythonCallable(func, args, kwargs)
        task = FutureTask(wrappedCode)
        SwingUtilities.invokeLater(task)
        return task.get()
Beispiel #25
0
def filterTable():
    global table_entries  # flag global variable as one to modify here
    try:
        text = search_field.getText()
        if 0 == len(text):
            table_entries = entries  # reset: show all rows
        else:
            pattern = re.compile(text)
            # Search in filepath and notes
            table_entries = [
                row for row in entries
                if pattern.search(row[-2]) or pattern.search(row[-1])
            ]
        SwingUtilities.invokeLater(
            lambda: table.updateUI())  # executed by the event dispatch thread
    except:
        print "Malformed regex pattern"
Beispiel #26
0
    def valueChanged(self, event):
        if event.getValueIsAdjusting():
            return
        askToSaveUnsavedChanges()

        # Must run later in the context of the event dispatch thread
        # when the latter has updated the table selection
        def after():
            rowIndex = getSelectedRowIndex()
            path.setText(table_entries[rowIndex][-2])
            path.setToolTipText(
                path.getText())  # for mouse over to show full path
            textarea.setText(table_entries[rowIndex][-1])
            textarea.setEditable(False)
            edit_note.setEnabled(True)
            save_note.setEnabled(False)
            note_status.setText("Saved.")  # as in entries and the CSV file

        SwingUtilities.invokeLater(after)
Beispiel #27
0
 def processHttpMessage(self, tool_flag, message_is_request, message_info):
     if tool_flag not in [
             IBurpExtenderCallbacks.TOOL_PROXY,
             IBurpExtenderCallbacks.TOOL_REPEATER,
             IBurpExtenderCallbacks.TOOL_TARGET,
     ]:
         return
     if message_is_request:
         return
     if not self._is_pre_analyze_validation_pass(tool_flag):
         return
     request_info, response_info = self._analyze_message(message_info)
     if not self._is_pre_process_validation_pass(request_info,
                                                 response_info):
         return
     SwingUtilities.invokeLater(
         ExecuteApplicationCommandInGuiThread(
             self._create_process_http_dialog_command(
                 tool_flag, request_info, message_info)))
Beispiel #28
0
def checkAuthorization(self, messageInfo, originalHeaders, checkUnauthorized):
    oldResponse = messageInfo.getResponse()
    message = makeMessage(self, messageInfo, True, True)
    requestResponse = makeRequest(self, messageInfo, message)
    newResponse = requestResponse.getResponse()
    analyzedResponse = self._helpers.analyzeResponse(newResponse)
    
    oldStatusCode = originalHeaders[0]
    newStatusCode = analyzedResponse.getHeaders()[0]
    oldContentLen = getResponseContentLength(self, oldResponse)
    newContentLen = getResponseContentLength(self, newResponse)

    # Check unauthorized request
    if checkUnauthorized:
        messageUnauthorized = makeMessage(self, messageInfo, True, False)
        requestResponseUnauthorized = makeRequest(self, messageInfo, messageUnauthorized)
        unauthorizedResponse = requestResponseUnauthorized.getResponse()
        analyzedResponseUnauthorized = self._helpers.analyzeResponse(unauthorizedResponse)  
        statusCodeUnauthorized = analyzedResponseUnauthorized.getHeaders()[0]
        contentLenUnauthorized = getResponseContentLength(self, unauthorizedResponse)

    EDFilters = self.EDModel.toArray()

    impression = checkBypass(self, oldStatusCode,newStatusCode,oldContentLen,newContentLen,EDFilters,requestResponse,self.AndOrType.getSelectedItem())

    if checkUnauthorized:
        EDFiltersUnauth = self.EDModelUnauth.toArray()
        impressionUnauthorized = checkBypass(self, oldStatusCode,statusCodeUnauthorized,oldContentLen,contentLenUnauthorized,EDFiltersUnauth,requestResponseUnauthorized,self.AndOrTypeUnauth.getSelectedItem())

    self._lock.acquire()
    
    row = self._log.size()
    method = self._helpers.analyzeRequest(messageInfo.getRequest()).getMethod()
    
    if checkUnauthorized:
        self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), method, self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,self._callbacks.saveBuffersToTempFiles(requestResponseUnauthorized),impressionUnauthorized)) # same requests not include again.
    else:
        self._log.add(LogEntry(self.currentRequestNumber,self._callbacks.saveBuffersToTempFiles(requestResponse), method, self._helpers.analyzeRequest(requestResponse).getUrl(),messageInfo,impression,None,"Disabled")) # same requests not include again.
    
    SwingUtilities.invokeLater(UpdateTableEDT(self,"insert",row,row))
    self.currentRequestNumber = self.currentRequestNumber + 1
    self._lock.release()
Beispiel #29
0
    def updateComboboxList(self, cb_list):
        # Update the combobox items after location urls have been found
        def updateComboboxList_run(cb_list):
            scope_list = []
            cb_dict = {}
            # Reinitialize the two comboboxes
            self.upnpcombo_targets.removeAllItems()
            self.upnpcombo_services.removeAllItems()
            # First check if any UPnP service was found
            if not cb_list:
                self.upnpcombo_targets.addItem("None UPnP service found")
                return
            # Build a dict of found IPs and location urls
            for cb_url in cb_list:
                parsed_cb_url = urlparse(cb_url)
                cb_ip = parsed_cb_url.netloc.split(":")[0]
                if cb_ip in cb_dict:
                    # Append the new number to the existing array at this slot
                    cb_dict[cb_ip].append(cb_url)
                else:
                    # Create a new array in this slot
                    cb_dict[cb_ip] = [cb_url]
            # All the found UPnP services are considered in scope
            self.scope_dict.clear()
            for ip in cb_dict:
                self.scope_dict[ip] = cb_dict[ip]
            # Set the found IPs on the ip list combobox
            for scope_ip in self.scope_dict:
                self.upnpcombo_targets.addItem(scope_ip)
            # Set the found location urls in the upnp list combobox
            selected_ip = self.upnpcombo_targets.getSelectedItem()
            self.upnpcombo_services.removeAllItems()
            for scope_url in self.scope_dict[selected_ip]:
                self.upnpcombo_services.addItem(scope_url)

            # Select the first element in the combobox by default
            self.upnpcombo_services.setSelectedIndex(0)
            self.confirmbutton.setEnabled(True)

        # Call the runnable method to update the plugin UI with results
        SwingUtilities.invokeLater(PyRunnable(updateComboboxList_run, cb_list))
Beispiel #30
0
 def on_change(evt):
     if not self._textareas[name].hasFocus():
         return
     try:
         if name == "raw":
             SwingUtilities.invokeLater(lambda: self._refresh_queries(
                 self._textareas['raw'].getText()))
         elif name.startswith('gql_query#'):
             id = int(name.split("#")[1])
             content = json.loads(self._textareas['raw'].getText())
             if id == 0 and not isinstance(content, list):
                 content['query'] = self._textareas[name].getText()
             else:
                 content[id]['query'] = self._textareas[name].getText()
             SwingUtilities.invokeLater(lambda: self._textareas['raw'].
                                        setText(json.dumps(content)))
         elif name.startswith('gql_variables#'):
             id = int(name.split("#")[1])
             content = json.loads(self._textareas['raw'].getText())
             if id == 0 and not isinstance(content, list):
                 content['variables'] = json.loads(
                     self._textareas[name].getText())
             else:
                 content[id]['variables'] = json.loads(
                     self._textareas[name].getText())
             SwingUtilities.invokeLater(lambda: self._textareas['raw'].
                                        setText(json.dumps(content)))
     except ValueError:
         pass  # Avoid crashing for JSON not valid incompatibilities
Beispiel #31
0
def addOrUpdateEntry(imp):
    """
  This function runs in response to an image being opened,
  and finds out whether a new entry should be added to the table (and CSV file)
  or whether an existing entry ought to be added,
  or whether there's nothing to do because it's a new image not opened from a file.
  
  imp: an ImagePlus
  """
    # Was the image opened from a file?
    fi = imp.getOriginalFileInfo()
    if not fi:
        # Image was created new, not from a file: ignore
        return
    filepath = os.path.join(fi.directory,
                            fi.fileName) if not fi.url else fi.url
    # Had we opened this file before?
    index = image_paths.get(filepath, None)
    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    if index is None:
        # File isn't yet in the table: add it
        entries.append([fi.fileName, now, now, filepath, ""])
        image_paths[filepath] = len(entries) - 1
    else:
        # File exists: edit its last seen date
        entries[index][2] = now
    # Rerun filtering if needed
    filterTable()

    # Update table to reflect changes to the underlying data model
    def repaint():
        table.updateUI()
        table.repaint()

    SwingUtilities.invokeLater(
        repaint)  # must run in the event dispatch thread
    # Request writing changes to the CSV file
    requested_save_csv.set(True)
Beispiel #32
0
def dot(u, v):
    return sum(mul(u, v))


def zfloat(n1, n2, n3=None):
    return zerofloat(n1, n2) if n3 is None else zerofloat(n1, n2, n3)


def rfloat(n1, n2, n3=None):
    r = randfloat(random, n1, n2) if n3 is None else randfloat(
        random, n1, n2, n3)
    sub(r, 0.5, r)
    mul(2.0, r, r)
    return r


##############################################################################
# Do everything on Swing thread.

import sys
from java.lang import Runnable
from javax.swing import SwingUtilities


class RunMain(Runnable):
    def run(self):
        main(sys.argv)


SwingUtilities.invokeLater(RunMain())
from   java.lang      import Runnable;
from   javax.swing    import JFrame;
from   javax.swing    import SwingUtilities;
class ToBeDetermined( Runnable ) :
    def __init__( self ) :
        self.frame = JFrame( 'ToBeDetermined' , defaultCloseOperation = JFrame.EXIT_ON_CLOSE );        
    def run( self ) :
        self.frame.setVisible( 1 );   # Have the application make itself visible

SwingUtilities.invokeLater( ToBeDetermined() );
raw_input();

Beispiel #34
0
 def wrapped(*args, **kwargs):
     SwingUtilities.invokeLater(Runnable(func, *args, **kwargs))
Beispiel #35
0
  equal = False
  while not equal and digits>0:
    almost = Almost(digits)
    equal = almost.equal(xa,xb)
    if not equal:
      digits -= 1
  return digits

def dot(u,v):
  return sum(mul(u,v))

def zfloat(n1,n2):
  return zerofloat(n1,n2)

def rfloat(n1,n2):
  r = randfloat(random,n1,n2)
  sub(r,0.5,r)
  mul(2.0,r,r)
  return r

##############################################################################
# Do everything on Swing thread.

import sys
from java.lang import Runnable
from javax.swing import SwingUtilities
class RunMain(Runnable):
  def run(self):
    main(sys.argv)
SwingUtilities.invokeLater(RunMain())
Beispiel #36
0
def later(f, *args, **kwargs):
    SwingUtilities.invokeLater(Later(f, args, kwargs))
    return f
Beispiel #37
0
    def restoreState(self):
        parentFrame = JFrame()
        fileChooser = JFileChooser()
        fileChooser.setDialogTitle("State import file")
        userSelection = fileChooser.showDialog(parentFrame, "Restore")

        if userSelection == JFileChooser.APPROVE_OPTION:
            importFile = fileChooser.getSelectedFile()

            with open(importFile.getAbsolutePath(), 'r') as csvfile:

                csvreader = csv.reader(csvfile, delimiter='\t', quotechar='|')

                for row in csvreader:

                    tempRequestResponseHost = row[0]
                    tempRequestResponsePort = row[1]
                    tempRequestResponseProtocol = row[2]
                    tempRequestResponseRequest = base64.b64decode(row[3])
                    tempRequestResponseResponse = base64.b64decode(row[4])

                    tempRequestResponseHttpService = self._extender._helpers.buildHttpService(
                        tempRequestResponseHost, int(tempRequestResponsePort),
                        tempRequestResponseProtocol)
                    tempRequestResponse = IHttpRequestResponseImplementation(
                        tempRequestResponseHttpService,
                        tempRequestResponseRequest,
                        tempRequestResponseResponse)

                    tempOriginalRequestResponseHost = row[5]
                    tempOriginalRequestResponsePort = row[6]
                    tempOriginalRequestResponseProtocol = row[7]
                    tempOriginalRequestResponseRequest = base64.b64decode(
                        row[8])
                    tempOriginalRequestResponseResponse = base64.b64decode(
                        row[9])

                    tempOriginalRequestResponseHttpService = self._extender._helpers.buildHttpService(
                        tempOriginalRequestResponseHost,
                        int(tempOriginalRequestResponsePort),
                        tempOriginalRequestResponseProtocol)
                    tempOriginalRequestResponse = IHttpRequestResponseImplementation(
                        tempOriginalRequestResponseHttpService,
                        tempOriginalRequestResponseRequest,
                        tempOriginalRequestResponseResponse)

                    checkAuthentication = True
                    if row[10] != '':
                        tempUnauthorizedRequestResponseHost = row[10]
                        tempUnauthorizedRequestResponsePort = row[11]
                        tempUnauthorizedRequestResponseProtocol = row[12]
                        tempUnauthorizedRequestResponseRequest = base64.b64decode(
                            row[13])
                        tempUnauthorizedRequestResponseResponse = base64.b64decode(
                            row[14])
                        tempUnauthorizedRequestResponseHttpService = self._extender._helpers.buildHttpService(
                            tempUnauthorizedRequestResponseHost,
                            int(tempUnauthorizedRequestResponsePort),
                            tempUnauthorizedRequestResponseProtocol)
                        tempUnauthorizedRequestResponse = IHttpRequestResponseImplementation(
                            tempUnauthorizedRequestResponseHttpService,
                            tempUnauthorizedRequestResponseRequest,
                            tempUnauthorizedRequestResponseResponse)
                    else:
                        checkAuthentication = False
                        tempUnauthorizedRequestResponse = None

                    tempEnforcementStatus = row[15]
                    tempEnforcementStatusUnauthorized = row[16]

                    self._extender._lock.acquire()

                    row = self._extender._log.size()

                    if checkAuthentication:
                        self._extender._log.add(
                            LogEntry(
                                self._extender.currentRequestNumber,
                                self._extender._callbacks.
                                saveBuffersToTempFiles(tempRequestResponse),
                                self._extender._helpers.analyzeRequest(
                                    tempRequestResponse).getMethod(),
                                self._extender._helpers.analyzeRequest(
                                    tempRequestResponse).getUrl(),
                                self._extender._callbacks.
                                saveBuffersToTempFiles(
                                    tempOriginalRequestResponse),
                                tempEnforcementStatus,
                                self._extender._callbacks.
                                saveBuffersToTempFiles(
                                    tempUnauthorizedRequestResponse),
                                tempEnforcementStatusUnauthorized))
                    else:
                        self._extender._log.add(
                            LogEntry(
                                self._extender.currentRequestNumber,
                                self._extender._callbacks.
                                saveBuffersToTempFiles(tempRequestResponse),
                                self._extender._helpers.analyzeRequest(
                                    tempRequestResponse).getMethod(),
                                self._extender._helpers.analyzeRequest(
                                    tempRequestResponse).getUrl(),
                                self._extender._callbacks.
                                saveBuffersToTempFiles(
                                    tempOriginalRequestResponse),
                                tempEnforcementStatus, None,
                                tempEnforcementStatusUnauthorized))

                    SwingUtilities.invokeLater(
                        UpdateTableEDT(self._extender, "insert", row, row))
                    self._extender.currentRequestNumber = self._extender.currentRequestNumber + 1
                    self._extender._lock.release()

                lastRow = self._extender._log.size()
                if lastRow > 0:
                    cookies = self._extender.getCookieFromMessage(
                        self._extender._log.get(lastRow - 1)._requestResponse)
                    if cookies:
                        self._extender.lastCookies = cookies
                        self._extender.fetchButton.setEnabled(True)
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     jocl_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'JOCL Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
    
    def onJava(self, e): 
     self.clockLabel.setText('running')
     self.started = Calendar.getInstance().getTimeInMillis();
     #print self.textfield1.getText()  
     #time.sleep(5)
     iters = toInt(self.textfield1.getText())
     java_smoother(iters)
     elapsed = Calendar.getInstance().getTimeInMillis() - self.started;
     self.clockLabel.setText( 'Java Elapsed: %.2f seconds' % ( float( elapsed ) / 1000.0 ) )
     

     
     
    
if ( __name__ == '__main__' ) or ( __name__ == 'main' ) :
    SwingUtilities.invokeLater( Demo() )
    raw_input();
    sys.exit();
else :
  print 'Error - script must be executed, not imported.\n';
  print 'Usage: jython %s.py\n' % __name__;
  print '   or: wsadmin -conntype none -f %s.py' % __name__;
Beispiel #39
0
def invokeLater(func, *args, **kwargs):
    """Convenience method for SwingUtilities.invokeLater()."""
    SwingUtilities.invokeLater(ProcRunnable(func, *args, **kwargs))
    return
    def onClickRun(self,event=""):
        self.DirName= FolderChooser(self.f)
        self.textAreaInputForFolder.setText(str(self.DirName))

    def onClickOut(self,event=""):
        self.OutDirName= FolderChooser(self.f)
        self.textAreaOutPutFolder.setText(str(self.OutDirName))
    
    def onClickSample(self,event):
        self.sampleSheet=FileChooser(self.f)
        self.textAreaForSheet.setText(str(self.sampleSheet))
        
    def performDemultiplex(self,event):
        NumberOfIterations=[self.Iter1.selected,self.Iter2.selected,self.Iter3.selected,self.Iter4.selected]
        LaneNumber=[self.lane1.selected,self.lane2.selected,self.lane3.selected,self.lane4.selected,self.lane5.selected,self.lane6.selected,self.lane7.selected,self.lane8.selected]
        selectedLanes = [str(i+1) for i, x in enumerate(LaneNumber) if x==True]
        lanes=','.join(selectedLanes)
        print LaneNumber,selectedLanes,lanes, lanes
        self.task = ET.Task(self,NumberOfIterations,str(self.sampleSheet),str(self.DirName),str(self.OutDirName), lanes)
        self.task.execute()

    def CancelJob(self,event):
        self.task.cancel(True)
        
if __name__ == "__main__":
    SwingUtilities.invokeLater(DemultiplexGUI())

        
        
Beispiel #41
0
 def updateTextArea(self, text):
     """ generated source for method updateTextArea """
     SwingUtilities.invokeLater(Runnable())
Beispiel #42
0
def later(f):
    SwingUtilities.invokeLater(Later(f))
    return f
Beispiel #43
0
    def onJocl(self, e):
        self.clockLabel.setText('running')
        self.started = Calendar.getInstance().getTimeInMillis()
        #print self.textfield1.getText()
        #time.sleep(5)
        iters = toInt(self.textfield1.getText())
        jocl_smoother(iters)
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.clockLabel.setText('JOCL Elapsed: %.2f seconds' %
                                (float(elapsed) / 1000.0))

    def onJava(self, e):
        self.clockLabel.setText('running')
        self.started = Calendar.getInstance().getTimeInMillis()
        #print self.textfield1.getText()
        #time.sleep(5)
        iters = toInt(self.textfield1.getText())
        java_smoother(iters)
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.clockLabel.setText('Java Elapsed: %.2f seconds' %
                                (float(elapsed) / 1000.0))


if (__name__ == '__main__') or (__name__ == 'main'):
    SwingUtilities.invokeLater(Demo())
    raw_input()
    sys.exit()
else:
    print 'Error - script must be executed, not imported.\n'
    print 'Usage: jython %s.py\n' % __name__
    print '   or: wsadmin -conntype none -f %s.py' % __name__
 def postAction(self):
     """Only add the action once to the Action manager."""
     if not self.finished and isinstance(self, ReversibleAction):
         SwingUtilities.invokeLater(RunWrapper(
             lambda: nengoinstance.actionManager.addReversibleAction(self)))
Beispiel #45
0

def launch(model):
    def run():
        makeUI(model)

    return run


if txt_file is None:
    od = OpenDialog("Choose a text file listing file paths")
    txt_file = od.getPath()

if txt_file:
    model = TableModel(txt_file)
    SwingUtilities.invokeLater(launch(model))

# FOR THE I2K WORKSHOP:
# Enable changing text font size in all components by control+shift+(plus|equals)/minus
components = []
tables = []
frames = []


def addFontResizing():
    global frames
    containers = [
        frame for frame in JFrame.getFrames()
        if frame.getTitle() == "File paths" and frame.isVisible()
    ]
    frames = containers[:]
Beispiel #46
0
    frame.setSize(500, 600)
    frame.setLayout(BorderLayout())
    splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
    
    #Create and set up the content pane.
    psimures= ResourcePanel()
    psimures.setOpaque(True)
    pconfig = ConfigurationPanel()
    pconfig.setOpaque(True)      #content panes must be opaque

    # show the GUI
    splitPane.add(psimures)
    splitPane.add(pconfig)
    frame.add(splitPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
 
###########################################################################
class Runnable(Runnable):
    def __init__(self, runFunction):
        self._runFunction = runFunction


    def run(self):
        self._runFunction()

###########################################################################         
if __name__ == '__main__':
    SwingUtilities.invokeLater(Runnable(createAndShowGUI))
    ''' load the current configuration from resources.properties and 
    configuration.properties '''
Beispiel #47
0
 def filterRows():
     self.table.getModel().filter(regex_field.getText())
     SwingUtilities.invokeLater(repaint)
Beispiel #48
0
def invokeLater(fn, *args, **kwargs):
    task = FunctionCall(fn, args, kwargs)
    SwingUtilities.invokeLater(task)
Beispiel #49
0
    def buttonInputReceived(self, evt):
#        print("Wiimote Button event: ", evt)
        self.sync.acquire()
        self.evt = evt
        self.sync.release()
        SwingUtilities.invokeLater(self) # Delegate processing to Swing thread (when we are here, we're in the WiiRemoteJ driver thread)