context manager that pauses the UI to allow running external commands.

        If an exception occurs, the UI will be started before the exception is
        re-raised.
498611
def paused(self):
        
        self.mainloop.stop()
        try:
            yield
        finally:
            self.mainloop.start()

            # make sure urwid renders its canvas at the correct size
            self.mainloop.screen_size = None
            self.mainloop.draw_screen()
1150903
def client_pause(self, timeout):
        
        if not isinstance(timeout, int):
            raise TypeError("timeout argument must be int")
        if timeout < 0:
            raise ValueError("timeout must be greater equal 0")
        fut = self.execute(b'CLIENT', b'PAUSE', timeout)
        return wait_ok(fut)
251594
public void processAction() throws IOException {
		if (isDisposed()) {
			LOG.error("Skipping action phase. Attempt to reuse disposed ContainerHelper instance");
			return;
		}

		try {
			// Check user context has been prepared
			if (getNewConversation() == null) {
				throw new IllegalStateException(
						"User context has not been prepared before the action phase");
			}

			prepareAction();

			UIContext uic = getUIContext();
			if (uic == null) {
				throw new IllegalStateException("No user context set for the action phase.");
			}

			UIContextHolder.pushContext(uic);

			// Make sure maps are cleared up
			uic.clearScratchMap();
			uic.clearRequestScratchMap();

			prepareRequest();

			Request req = getRequest();
			getInterceptor().attachResponse(getResponse());
			getInterceptor().serviceRequest(req);

			if (req.isLogout()) {
				handleLogout();
				dispose();
			}
		} catch (ActionEscape esc) {
			LOG.debug("ActionEscape performed.");
			// Action escapes must be handled in the action phase and then
			// do nothing if they reach the render phase (which they will in
			// the servlet implementation)
			handleEscape(esc);
			dispose();
		} catch (Escape esc) {
			LOG.debug("Escape performed during action phase.");
			// We can't handle the escape until the render phase.
		} catch (Throwable t) {
			// We try not to let any exception propagate to container.
			String message = "Caught exception during action phase.";
			LOG.error(message, t);

			// We can't handle the error until the render phase.
			propogateError(t);
		} finally {
			UIContextHolder.reset();
		}
	}
712754
def _idle_loop(self):
        
        while not self._stop_update_flag:
            time.sleep(self.update_interval)
            with self.update_lock:
                try:
                    self.idle()
                except:
                    self._log.error("exception in App.idle method", exc_info=True)
                if self._need_update_flag:
                    try:
                        self.do_gui_update()
                    except:
                        self._log.error('''exception during gui update. It is advisable to 
                            use App.update_lock using external threads.''', exc_info=True)
564603
private void prepareExecutionAttempt(AsyncExecutionContextImpl<W> executionContext) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(tc, "Execution {0} enqueuing new execution attempt", executionContext.getId());
        }

        AsyncAttemptContextImpl<W> attemptContext = new AsyncAttemptContextImpl<>(executionContext);

        TimeoutState timeout = FaultToleranceStateFactory.INSTANCE.createTimeoutState(executorService, timeoutPolicy, metricRecorder);
        attemptContext.setTimeoutState(timeout);

        if (!circuitBreaker.requestPermissionToExecute()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Execution {0} Circuit Breaker open, not executing", executionContext.getId());
            }

            MethodResult<W> result = MethodResult.failure(new CircuitBreakerOpenException());
            processEndOfAttempt(attemptContext, result);
            return;
        }

        attemptContext.setCircuitBreakerPermittedExecution(true);

        timeout.start();

        ExecutionReference ref = bulkhead.submit((reservation) -> runExecutionAttempt(attemptContext, reservation), getExceptionHandler(attemptContext));

        if (!ref.wasAccepted()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Execution {0} bulkhead rejected execution", executionContext.getId());
            }

            processEndOfAttempt(attemptContext, MethodResult.failure(new BulkheadException()));
            return;
        }

        timeout.setTimeoutCallback(handleExceptions(() -> timeout(attemptContext, ref), attemptContext, executionContext));

        // Update what we should do if the user cancels the execution
        executionContext.setCancelCallback((mayInterrupt) -> {
            ref.abort(mayInterrupt);
            processEndOfAttempt(attemptContext, MethodResult.failure(new CancellationException()));
        }
6659
public void pause() {
        if (hasState(TICKING) && !hasState(PAUSED)) {
            if (DBG) Log.v(TAG, "pause. " + mEntries.size());
            mContentView.animate().cancel();
            addState(PAUSED);
            cancel(-1);
        }
    }
189875
void execute(ExecutableBuilder builder,
            int timeout,
            TimeUnit unit) throws
            CommandLineException,
            InterruptedException, ExecutionException, TimeoutException {
        Future<Void> task = executorService.submit(() -> {
            builder.build().execute();
            return null;
        });
        try {
            if (timeout <= 0) { //Synchronous
                task.get();
            } else { // Guarded execution
                try {
                    task.get(timeout, unit);
                } catch (TimeoutException ex) {
                    // First make the context unusable
                    CommandContext c = builder.getCommandContext();
                    if (c instanceof TimeoutCommandContext) {
                        ((TimeoutCommandContext) c).timeout();
                    }
                    // Then cancel the task.
                    task.cancel(true);
                    throw ex;
                }
            }
        } catch (InterruptedException ex) {
            // Could have been interrupted by user (Ctrl-C)
            Thread.currentThread().interrupt();
            cancelTask(task, builder.getCommandContext(), null);
            // Interrupt running operation.
            CommandContext c = builder.getCommandContext();
            if (c instanceof TimeoutCommandContext) {
                ((TimeoutCommandContext) c).interrupted();
            }
            throw ex;
        }
    }
418344
def resume_pry(context)
      new_binding = context.frame_binding(0)
      Debugger.stop unless @always_enabled

      @pry.binding_stack.clear
      run(false) do
        @pry.repl new_binding
      end
    end
244666
def context(self, name, ctx):
        
        self.enter_context(name, ctx)
        try:
            yield
        finally:
            self.exit_context(name)
1154217
private void allowCleanShutdown() {
        DelayingShutdownHook hook = new DelayingShutdownHook();
        Context context = (Context) this.loggerFactory;
        hook.setContext(context);
        Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
        Runtime.getRuntime().addShutdownHook(hookThread);
    }
442086
private void closeContext(DirContext ctx) {
		if (ctx != null) {
			try {
				ctx.close();
			}
			catch (Exception e) {
                LOG.debug("Exception closing context", e);
			}
		}
	}
1032064
@Override
	public void onStart(TestContext<Object> context) {
		oldErr = System.err;
		oldOut = System.out;
		try {
			System.setErr(remplacementErr);
			System.setOut(remplacementOut);
		} catch (SecurityException e) {
			// ignored
		}
	}
417736
public static void endAccessContext() {
        AccessContext.clearAccessContextOnThread();
        final AccessContext accessContext = SuspendedAccessContext.getAccessContextOnThread();
        if (accessContext != null) { // resume
            AccessContext.setAccessContextOnThread(accessContext);
            SuspendedAccessContext.clearAccessContextOnThread();
        }
    }
248262
public Resolution intercept(ExecutionContext executionContext) throws Exception {
        // Remove expired contexts.
        removeExpired(contexts);
        
        // Get wait context, if any.
        Context context = getContext(executionContext);
        LifecycleStage stage = executionContext.getLifecycleStage();
        
        if (executionContext.getActionBeanContext().getRequest().getRequestURI().contains(THREAD_URL)) {
            // The request we are processing is the one used to invoke event handler in background and to get resolution to send to user when event completes.
            // Since we are going to invoke the real event, the action bean and event must stay the same.
            // Binding and validation must be skipped since they were done in the first request.
            switch (executionContext.getLifecycleStage()) {
                // Use action bean that will process event.
                case ActionBeanResolution:
                    log.trace("injecting ActionBean");
                    // Since session can be lost from original request (Tomcat is a good example), request must be updated with the background request.
                    context.actionBean.setContext(executionContext.getActionBeanContext());
                    executionContext.setActionBean(context.actionBean);
                    // Skip normal action bean resolution.
                    return null;
                // Select event to call.
                case HandlerResolution:
                    log.trace("injecting event handler");
                    executionContext.setHandler(context.eventHandler);
                    // Skip normal handler resolution.
                    return null;
                // No biding or validation, it was done before a background request was created to handle event.
                case BindingAndValidation:
                case CustomValidation:
                    log.trace("skipping binding and validation");
                    // Skip binding and validation.
                    return null;
                // Execute event since we are in the background request.
                case EventHandling:
                    log.trace("executing event handler");
                    // Execute event and save exception if any.
                    try {
                        return executionContext.proceed();
                    }
                    catch (Exception e) {
                        synchronized(context.actionBean)
                        {
                            log.trace("setting exception in context");
                            context.throwable = e;
                            context.status = Context.Status.COMPLETE;
                            context.completeMoment = System.currentTimeMillis();
                            context.actionBean.notifyAll();
                            context.eventFlashScope = FlashScope.getCurrent(context.actionBean.getContext().getRequest(), false);
                        }
                        throw e;
                    }
                // Save resolution to send to user when he will refresh wait page.
                case ResolutionExecution:
                    synchronized(context.actionBean)
                    {
                        log.trace("setting resolution in context");
                        context.resolution = executionContext.getResolution();
                        context.status = Context.Status.COMPLETE;
                        context.completeMoment = System.currentTimeMillis();
                        context.actionBean.notifyAll();
                        context.eventFlashScope = FlashScope.getCurrent(context.actionBean.getContext().getRequest(), false);
                    }
                    
                    // Use a default resolution to prevent processing the one event returned.
                    executionContext.setResolution(new StreamingResolution("text/plain", "thread complete"));
                    return executionContext.proceed();
                case RequestInit:
                case RequestComplete:
                    return executionContext.proceed();
            }
        }
        else {
            if (LifecycleStage.ActionBeanResolution.equals(stage)) {
                if (context != null) {
                    // We are using a wait context for this request. Go to wait page or event's resolution depending on status and skip everything else.
                    return checkStatus(executionContext, context);
                }
            }
            else if (LifecycleStage.EventHandling.equals(stage)) {
                WaitPage annotation = executionContext.getHandler().getAnnotation(WaitPage.class);
                if (annotation != null) {
                    // Event has @WaitPage annotation. Create wait context to invoke event in background and redirect user to wait page.
                    return createContextAndRedirect(executionContext, annotation);
                }
            }
        }
        
        return executionContext.proceed();
    }
171
public void run(Context context) throws IOException, InterruptedException {
    setup(context);
    while (context.nextKeyValue()) {
      map(context.getCurrentKey(), context.getCurrentValue(), context);
    }
    cleanup(context);
  }
255109
public void pause()
    {
        if (mAudioListener != null)
        {
            int sourceId = getSourceId();
            if (sourceId != GvrAudioEngine.INVALID_ID)
            {
                mAudioListener.getAudioEngine().pauseSound(sourceId);
            }
        }
    }
607534
def pause
        raise ArgumentError, 'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.' unless self.class.pause_supported?
        
        unless @resume_block
          require 'continuation' unless defined?(callcc)
          callcc do |block|
            @paused_block = block
            throw :halt, true
          end
        end
      end