Urwid main event loop
547916
def main(self):
        
        self.loop = urwid.MainLoop(self.top, self.palettes[self.palette_names[0]], screen=self.tui,
                                   handle_mouse=False, input_filter=self.handle_keys,
                                   unhandled_input=self.unhandled)
        self.loop.run()
375169
def inputhook_wx1():
    
    try:
        app = wx.GetApp()  # @UndefinedVariable
        if app is not None:
            assert wx.Thread_IsMain()  # @UndefinedVariable

            # Make a temporary event loop and process system events until
            # there are no more waiting, then allow idle events (which
            # will also deal with pending or posted wx events.)
            evtloop = wx.EventLoop()  # @UndefinedVariable
            ea = wx.EventLoopActivator(evtloop)  # @UndefinedVariable
            while evtloop.Pending():
                evtloop.Dispatch()
            app.ProcessIdle()
            del ea
    except KeyboardInterrupt:
        pass
    return 0
349617
function run(route, index, path, query, res, next) {
    mm.create(route.action).then(
        function (presenter) {
            var ele = new Element('div');

            function finish() {
                var model = presenter.model;
                res.html = ele.outerHTML;
                res.data = model.store;
                res.routeIndex = index;
                next();
            }

            presenter
                .enter(ele, path, query)
                .then(finish, next);
        },
        next
    ).then(null, next);
}
1342348
function open(selector) {
            if (p["--debug"] && host.runtime == host.RUNTIME_NODEJS) {
                return debug(p);
            }
            if (p["--ui"] && !ui) {
                if (!nw) {
                    allume.update(allume.STATUS_ERROR, MSG_UI_UNAVAILABLE);
                    return;
                }

                // spawn nw.js process for allume with parameters
                var findpath = nw.findpath;
                childProcess = childProcess || require("child_process");
                path = path || require("path");

                var PATH_NW = findpath();
                var PATH_APP = path.join(__dirname, "..");
                var PATH_CWD = process.cwd();
                var env = Object.create(process.env);
                env.PWD = process.cwd();

                process.argv.splice(1, 1);
                process.argv[0] = PATH_APP;
                for (var a in process.argv) {
                    process.argv[a] = process.argv[a].replace(/"/g, "\"");
                }

                var ls = childProcess.spawn(PATH_NW, process.argv, {"cwd": PATH_CWD, "env" : env});

                ls.stdout.on("data", function(data) {
                    console.log(data.toString().trim());
                });

                ls.stderr.on("data", function(data) {
                    console.error(data.toString().trim());
                });

                return;
            }

            var requests = [];
            var request = selector;
            if (p["--config"]) {
                var json;
                try {
                    json = JSON.parse(p["--config"].json);
                }
                catch(e) {
                    var e = new Error("Make sure the data you pass to the --config switch is valid JSON data.");
                    e.name = "error-invalid-configuration";
                    if (typeof document !== "undefined" && firstOpen) {
                        allume.update(e);
                    }
                    else {
                        console.error(e);
                    }
                    firstOpen = false;
                    return;
                }
                request = { "package" : selector, "configuration" : json };
            }
            requests.push(request);

            if (requests) {
                using.apply(using, requests).then(function () {
                    if (firstOpen) {
                        allume.hide();
                        firstOpen = false;
                    }
                }, function (loader) {
                    usingFailed(loader);
                    var e = new Error(err);
                    e.name = errName;
                    if (typeof document !== "undefined" && firstOpen) {
                        allume.update(e);
                        firstOpen = false;
                    }
                    else {
                        console.error(e);
                    }
                });
            }
        }
1030702
function checkUriRaw(i) {
  const start = i;
  let l;

  while (i < tokensLength) {
    if (checkInterpolation(i) || checkVariable(i)) break;
    else if (l = checkUriRawCharacters(i)) i += l;
    else break;
  }

  tokens[start].uri_raw_end = i;

  return i - start;
}
821635
def main():
    

    # Parse arguments and configure application instance.
    arguments, parser = parse_arguments()

    # Start iterating
    store = RevisionStore()
    sys.stdout.write("Iterating over %d items.\n" % arguments.number)

    for i in xrange(arguments.number):
        key = chr(65 + (i % 26))
        value = [key * (i % 26), key * (i % 13), key * (i % 5)]

        store.add(key, value)

    # Wait for an enter
    if arguments.pause:
        sys.stdout.write("Done!")
        sys.stdin.readline()
171309
private void sendEvent(String url, Map<String, Object> data)
    {
        // Dynamically look for an Observation Manager and only send the event if one can be found.
        try {
            ObservationManager observationManager = this.observationManagerProvider.get();
            observationManager.notify(new InvalidURLEvent(url), data);
        } catch (Exception e) {
            // Failed to find an Observation Manager, continnue, but log a warning since it's not really normal
            this.logger.warn("The Invalid URL Event for URL [{}] (source [{}]) wasn't sent as no Observation Manager "
                + "Component was found", url, data.get(EVENT_DATA_SOURCE));
        }
    }
1276297
def process(self, event):
        
        uid = str(uuid.uuid4())
        hostname = os.environ.get('VENT_HOST')
        if not hostname:
            hostname = ''

        try:
            # TODO should directories be treated as bulk paths to send to a
            #      plugin?
            if not event.is_directory:
                spath = event.src_path
                # wait for long copies to finish
                historicalSize = -1
                while (historicalSize != os.path.getsize(spath)):
                    historicalSize = os.path.getsize(spath)
                    time.sleep(0.1)

                if os.path.getsize(spath) == 0:
                    spath = str(spath)
                    print('file drop ignoring empty file: {0}'.format(spath))
                    if spath.startswith('/files/trace_'):
                        key = spath.split('_')[1]
                        # Rabbit settings
                        exchange = 'topic-poseidon-internal'
                        exchange_type = 'topic'
                        routing_key = 'poseidon.algos.decider'

                        message = {}
                        message[key] = {'valid': False, 'source': 'file_drop'}
                        message = json.dumps(message)

                        # Send Rabbit message
                        try:
                            connection = pika.BlockingConnection(
                                pika.ConnectionParameters(host='rabbit')
                            )

                            channel = connection.channel()
                            channel.exchange_declare(
                                exchange=exchange, exchange_type=exchange_type
                            )
                            channel.basic_publish(exchange=exchange,
                                                  routing_key=routing_key,
                                                  body=message)
                            connection.close()
                        except Exception as e:
                            print('failed to send rabbit message because: ' +
                                  str(e))

                    return

                # check if the file was already queued and ignore
                exists = False
                print(uid + ' started ' + spath)
                jobs = self.r.keys(pattern='rq:job*')
                for job in jobs:
                    print(uid + ' ***')
                    description = self.r.hget(
                        job, 'description').decode('utf-8')
                    print(uid + ' ' + description)
                    if description.startswith("watch.file_queue('"):
                        print(uid + ' ' +
                              description.split("watch.file_queue('" +
                                                hostname + '_')[1][:-2])
                        print(uid + ' ' + spath)
                        if description.split("watch.file_queue('" +
                                             hostname +
                                             '_')[1][:-2] == spath:
                            print(uid + ' true')
                            exists = True
                    elif description.startswith("watch.gpu_queue('"):
                        print(uid + ' ' +
                              description.split('"file": "')[1].split('"')[0])
                        print(uid + ' ' + spath)
                        if description.split('"file": "')[1].split('"')[0] == spath:
                            print(uid + ' true')
                            exists = True
                    print(uid + ' ***')

                if not exists:
                    # !! TODO this should be a configuration option in the
                    #         vent.template
                    print(uid + " let's queue it " + spath)
                    # let jobs be queued for up to 30 days
                    self.q.enqueue('watch.file_queue',
                                   hostname + '_' + spath,
                                   ttl=2592000)
                print(uid + ' end ' + spath)
        except Exception as e:  # pragma: no cover
            print('file drop error: ' + str(e))
431465
def run_twisted(self, args):
        
        server = self

        from twisted.internet import reactor
        from twisted.web import resource
        from twisted.web.static import File
        from twisted.web.server import Site
        from autobahn.twisted.websocket import (WebSocketServerFactory,
                                                WebSocketServerProtocol)
        from autobahn.twisted.resource import WebSocketResource

        class DevWebSocketHandler(WebSocketServerProtocol):
            def onConnect(self, request):
                super(DevWebSocketHandler, self).onConnect(request)
                server.on_open(self)

            def onMessage(self, payload, isBinary):
                server.on_message(self, payload)

            def onClose(self, wasClean, code, reason):
                super(DevWebSocketHandler,self).onClose(wasClean, code, reason)
                server.on_close(self)

            def write_message(self, message, binary=False):
                self.sendMessage(message, binary)

        #: Set the call later method
        server.call_later = reactor.callLater
        server.add_callback = reactor.callFromThread

        factory = WebSocketServerFactory(u"ws://0.0.0.0:{}".format(self.port))
        factory.protocol = DevWebSocketHandler

        class MainHandler(resource.Resource):
            def render_GET(self, req):
                return str(server.index_page)

        root = resource.Resource()
        root.putChild("", MainHandler())
        root.putChild("dev", WebSocketResource(factory))
        reactor.listenTCP(self.port, Site(root))
        print("Twisted Dev server started on {}".format(self.port))
        reactor.run()
501923
def run(self, stdin, callbacks):
        
        assert isinstance(stdin, Input)
        assert isinstance(callbacks, EventLoopCallbacks)
        assert not self._running

        if self.closed:
            raise Exception('Event loop already closed.')

        self._running = True
        self._callbacks = callbacks

        inputstream = InputStream(callbacks.feed_key)
        current_timeout = [INPUT_TIMEOUT]  # Nonlocal

        # Create reader class.
        stdin_reader = PosixStdinReader(stdin.fileno())

        # Only attach SIGWINCH signal handler in main thread.
        # (It's not possible to attach signal handlers in other threads. In
        # that case we should rely on a the main thread to call this manually
        # instead.)
        if in_main_thread():
            ctx = call_on_sigwinch(self.received_winch)
        else:
            ctx = DummyContext()

        def read_from_stdin():
            " Read user input. "
            # Feed input text.
            data = stdin_reader.read()
            inputstream.feed(data)

            # Set timeout again.
            current_timeout[0] = INPUT_TIMEOUT

            # Quit when the input stream was closed.
            if stdin_reader.closed:
                self.stop()

        self.add_reader(stdin, read_from_stdin)
        self.add_reader(self._schedule_pipe[0], None)

        with ctx:
            while self._running:
                # Call inputhook.
                if self._inputhook_context:
                    with TimeIt() as inputhook_timer:
                        def ready(wait):
                            " True when there is input ready. The inputhook should return control. "
                            return self._ready_for_reading(current_timeout[0] if wait else 0) != []
                        self._inputhook_context.call_inputhook(ready)
                    inputhook_duration = inputhook_timer.duration
                else:
                    inputhook_duration = 0

                # Calculate remaining timeout. (The inputhook consumed some of the time.)
                if current_timeout[0] is None:
                    remaining_timeout = None
                else:
                    remaining_timeout = max(0, current_timeout[0] - inputhook_duration)

                # Wait until input is ready.
                fds = self._ready_for_reading(remaining_timeout)

                # When any of the FDs are ready. Call the appropriate callback.
                if fds:
                    # Create lists of high/low priority tasks. The main reason
                    # for this is to allow painting the UI to happen as soon as
                    # possible, but when there are many events happening, we
                    # don't want to call the UI renderer 1000x per second. If
                    # the eventloop is completely saturated with many CPU
                    # intensive tasks (like processing input/output), we say
                    # that drawing the UI can be postponed a little, to make
                    # CPU available. This will be a low priority task in that
                    # case.
                    tasks = []
                    low_priority_tasks = []
                    now = None  # Lazy load time. (Fewer system calls.)

                    for fd in fds:
                        # For the 'call_from_executor' fd, put each pending
                        # item on either the high or low priority queue.
                        if fd == self._schedule_pipe[0]:
                            for c, max_postpone_until in self._calls_from_executor:
                                if max_postpone_until is None:
                                    # Execute now.
                                    tasks.append(c)
                                else:
                                    # Execute soon, if `max_postpone_until` is in the future.
                                    now = now or _now()
                                    if max_postpone_until < now:
                                        tasks.append(c)
                                    else:
                                        low_priority_tasks.append((c, max_postpone_until))
                            self._calls_from_executor = []

                            # Flush all the pipe content.
                            os.read(self._schedule_pipe[0], 1024)
                        else:
                            handler = self._read_fds.get(fd)
                            if handler:
                                tasks.append(handler)

                    # When there are high priority tasks, run all these.
                    # Schedule low priority tasks for the next iteration.
                    if tasks:
                        for t in tasks:
                            t()

                        # Postpone low priority tasks.
                        for t, max_postpone_until in low_priority_tasks:
                            self.call_from_executor(t, _max_postpone_until=max_postpone_until)
                    else:
                        # Currently there are only low priority tasks -> run them right now.
                        for t, _ in low_priority_tasks:
                            t()

                else:
                    # Flush all pending keys on a timeout. (This is most
                    # important to flush the vt100 'Escape' key early when
                    # nothing else follows.)
                    inputstream.flush()

                    # Fire input timeout event.
                    callbacks.input_timeout()
                    current_timeout[0] = None

        self.remove_reader(stdin)
        self.remove_reader(self._schedule_pipe[0])

        self._callbacks = None
786927
protected synchronized void doStart() throws Exception
    {
        // Start Servlet Handler
        super.doStart();
        if (log.isDebugEnabled())
            log.debug("Path Filters: " + _pathFilters);
        if (log.isDebugEnabled())
            log.debug("Servlet Filters: " + _servletFilterMap);
        
        if (getHttpContext() instanceof WebApplicationContext)
            _webApplicationContext= (WebApplicationContext)getHttpContext();
        
        if (_filterChainsCached)
        {
            _chainCache = getChainCache();
            _namedChainCache = getChainCache();
        }
    }
480592
def run(self):
        
        while not self._request_shutdown:

            # Find out if we have any data pending from the
            # server
            try:

                # If we've been asked to stop running the
                # request loop. We'll just sit and wait
                # till we get asked to run again
                if self._state not in [STATE_AUTHENTICATING,STATE_WEBSOCKET_CONNECTED,STATE_CONNECTED]:
                    self._request_loop_notify_restart.acquire()
                    self._request_loop_notify_restart.wait(self._loop_timeout)
                    self._request_loop_notify_restart.release()
                    continue

                # If we don't have a websocket defined.
                # we don't go further either
                elif not self.ws:
                    logger.debug("No longer have a websocket. Marking disconnected")
                    self._state = STATE_DISCONNECTED
                    continue

                # Okay, we think we're okay so let's try and read some data
                data = self.ws.recv()
            except io.BlockingIOError:
                continue
            except websocket.WebSocketTimeoutException:
                continue
            except websocket.WebSocketConnectionClosedException as ex:
                logger.debug("WebSocketConnectionClosedException: Requesting disconnect:".format(ex))
                self.disconnect()

                # If the server disconnected, let's try and reconnect
                # back to the service after a random few seconds
                if self.auto_reconnect:
                    # As doing a reconnect would block and would then
                    # prevent us from ticking the websoocket, we'll
                    # go into a subthread to deal with the reconnection
                    def reconnect():
                        self.reconnect()
                    t = threading.Thread(target=reconnect)
                    t.start()

                    # FIXME: need to randomly wait
                    time.sleep(1)
                    if not data: continue
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
                continue

            try:
                logger.debug("<RCV: {}".format(data))
                message = WampMessage.loads(data)
                logger.debug("<RCV: {}".format(message.dump()))
                try:
                    code_name = message.code_name.lower()
                    handler_name = "handle_"+code_name
                    handler_function = getattr(self,handler_name)
                    handler_function(message)
                except AttributeError as ex:
                    self.handle_unknown(message)
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
272966
async def main(loop):
    """"""
    pyvlx = PyVLX('pyvlx.yaml', loop=loop)
    # Alternative:
    # pyvlx = PyVLX(host="192.168.2.127", password="velux123", loop=loop)

    # Runing scenes:
    await pyvlx.load_scenes()
    await pyvlx.scenes["All Windows Closed"].run()

    # Changing position of windows:
    await pyvlx.load_nodes()
    await pyvlx.nodes['Bath'].open()
    await pyvlx.nodes['Bath'].close()
    await pyvlx.nodes['Bath'].set_position(Position(position_percent=45))

    # Changing of on-off switches:
    # await pyvlx.nodes['CoffeeMaker'].set_on()
    # await pyvlx.nodes['CoffeeMaker'].set_off()

    # You can easily rename nodes:
    # await pyvlx.nodes["Window 10"].rename("Window 11")

    await pyvlx.disconnect()
710164
def run(self, data_cb):
        """"""
        if self._error:
            err = self._error
            if isinstance(self._error, KeyboardInterrupt):
                # KeyboardInterrupt is not destructive(it may be used in
                # the REPL).
                # After throwing KeyboardInterrupt, cleanup the _error field
                # so the loop may be started again
                self._error = None
            raise err
        self._on_data = data_cb
        if threading.current_thread() == main_thread:
            self._setup_signals([signal.SIGINT, signal.SIGTERM])
        debug('Entering event loop')
        self._run()
        debug('Exited event loop')
        if threading.current_thread() == main_thread:
            self._teardown_signals()
            signal.signal(signal.SIGINT, default_int_handler)
        self._on_data = None
793792
def start(sync_event_source, loop=None):
    """"""

    if not loop:
        loop = asyncio.get_event_loop()

    event_source = asyncio.Queue(loop=loop)

    bridge = threading.Thread(target=_multiprocessing_to_asyncio,
                              args=(sync_event_source, event_source, loop),
                              daemon=True)
    bridge.start()

    app = init_app(event_source, loop=loop)
    aiohttp.web.run_app(app,
                        host=config['wsserver']['host'],
                        port=config['wsserver']['port'])
1114947
function WSMux(urlOrWs, options) {
  EventEmitter.call(this);
  this.options = util._extend({mask: true}, options);
  this.closed = false;
  this.channels = {};
  this.pending = [];
  this._openWebsocket(urlOrWs);
}
90891
function _loop(i) {
				var eventName = eventNames[i];
				var actionGroup = instructions[eventName];

				ws.addEventListener(eventName, function (res) {

					processActionGroup({ res: res, actionGroup: actionGroup });

					// TODO handle sending messages
				});
			}