Makes a a handler class to use inside the basic python HTTP server.

    state_token is the expected state token.
    done_function is a function that is called, with the code passed to it.
338622
def _make_handler(state_token, done_function):
    '''
    
    '''

    class LocalServerHandler(BaseHTTPServer.BaseHTTPRequestHandler):

        def error_response(self, msg):
            logging.warn(
                'Error response: %(msg)s. %(path)s',
                msg=msg,
                path=self.path)
            self.send_response(400)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(msg)

        def do_GET(self):
            parsed = urlparse.urlparse(self.path)
            if len(parsed.query) == 0 or parsed.path != '/callback':
                self.error_response(
                    'We encountered a problem with your request.')
                return

            params = urlparse.parse_qs(parsed.query)
            if params['state'] != [state_token]:
                self.error_response(
                    'Attack detected: state tokens did not match!')
                return

            if len(params['code']) != 1:
                self.error_response('Wrong number of "code" query parameters.')
                return

            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(
                "courseraoauth2client: we have captured Coursera's response "
                "code. Feel free to close this browser window now and return "
                "to your terminal. Thanks!")
            done_function(params['code'][0])

    return LocalServerHandler
1374484
public ServerMethodDefinition<ReqT, RespT> withServerCallHandler(
      ServerCallHandler<ReqT, RespT> handler) {
    return new ServerMethodDefinition<>(method, handler);
  }
891461
function createReducer(defaultState, handlers) {
  let _defaultStateType = t.union(t.function(), t.object());

  let _handlersType = t.nullable(t.object());

  t.param('defaultState', _defaultStateType).assert(defaultState);
  t.param('handlers', _handlersType).assert(handlers);

  if (typeof defaultState === 'object') {
    handlers = _handlersType.assert(defaultState);
    defaultState = _defaultStateType.assert(() => null);
  }

  const handlerMap = new Map();
  Object.keys(handlers).forEach(key => {
    if (typeof key === 'function') {
      if (typeof key.type !== 'string') {
        throw new Error(`Invalid handler key: "${key.name}"`);
      }
      handlerMap.set(key.type, handlers[key]);
    } else {
      handlerMap.set(key, handlers[key]);
    }
  });
  handlers = _handlersType.assert(undefined);

  return (state = defaultState(), action) => {
    if (action && handlerMap.has(action.type)) {
      return handlerMap.get(action.type)(state, action);
    }

    return state;
  };
}
163685
public static function SetHandler ($handler_class = null, $register_shutdown = false) {
		$handler_class = $handler_class ?: static::class;
		if (is_string($handler_class)) {
			$handler_class = new $handler_class;
		}
		$ret = session_set_save_handler(new \SessionHandler, $register_shutdown);
		return $ret;
	}
196195
def handler(self, event, context):
        
        settings = self.settings

        # If in DEBUG mode, log all raw incoming events.
        if settings.DEBUG:
            logger.debug('Zappa Event: {}'.format(event))

        # Set any API Gateway defined Stage Variables
        # as env vars
        if event.get('stageVariables'):
            for key in event['stageVariables'].keys():
                os.environ[str(key)] = event['stageVariables'][key]

        # This is the result of a keep alive, recertify
        # or scheduled event.
        if event.get('detail-type') == u'Scheduled Event':

            whole_function = event['resources'][0].split('/')[-1].split('-')[-1]

            # This is a scheduled function.
            if '.' in whole_function:
                app_function = self.import_module_and_get_function(whole_function)

                # Execute the function!
                return self.run_function(app_function, event, context)

            # Else, let this execute as it were.

        # This is a direct command invocation.
        elif event.get('command', None):

            whole_function = event['command']
            app_function = self.import_module_and_get_function(whole_function)
            result = self.run_function(app_function, event, context)
            print("Result of %s:" % whole_function)
            print(result)
            return result

        # This is a direct, raw python invocation.
        # It's _extremely_ important we don't allow this event source
        # to be overridden by unsanitized, non-admin user input.
        elif event.get('raw_command', None):

            raw_command = event['raw_command']
            exec(raw_command)
            return

        # This is a Django management command invocation.
        elif event.get('manage', None):

            from django.core import management

            try:  # Support both for tests
                from zappa.ext.django_zappa import get_django_wsgi
            except ImportError as e:  # pragma: no cover
                from django_zappa_app import get_django_wsgi

            # Get the Django WSGI app from our extension
            # We don't actually need the function,
            # but we do need to do all of the required setup for it.
            app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS)

            # Couldn't figure out how to get the value into stdout with StringIO..
            # Read the log for now. :[]
            management.call_command(*event['manage'].split(' '))
            return {}

        # This is an AWS-event triggered invocation.
        elif event.get('Records', None):

            records = event.get('Records')
            result = None
            whole_function = self.get_function_for_aws_event(records[0])
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to process the triggered event.")
            return result

        # this is an AWS-event triggered from Lex bot's intent
        elif event.get('bot'):
            result = None
            whole_function = self.get_function_from_bot_intent_trigger(event)
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to process the triggered event.")
            return result

        # This is an API Gateway authorizer event
        elif event.get('type') == u'TOKEN':
            whole_function = self.settings.AUTHORIZER_FUNCTION
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                policy = self.run_function(app_function, event, context)
                return policy
            else:
                logger.error("Cannot find a function to process the authorization request.")
                raise Exception('Unauthorized')

        # This is an AWS Cognito Trigger Event
        elif event.get('triggerSource', None):
            triggerSource = event.get('triggerSource')
            whole_function = self.get_function_for_cognito_trigger(triggerSource)
            result = event
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to handle cognito trigger {}".format(triggerSource))
            return result

        # Normal web app flow
        try:
            # Timing
            time_start = datetime.datetime.now()

            # This is a normal HTTP request
            if event.get('httpMethod', None):
                script_name = ''
                is_elb_context = False
                headers = merge_headers(event)
                if event.get('requestContext', None) and event['requestContext'].get('elb', None):
                    # Related: https://github.com/Miserlou/Zappa/issues/1715
                    # inputs/outputs for lambda loadbalancer
                    # https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
                    is_elb_context = True
                    # host is lower-case when forwarded from ELB
                    host = headers.get('host')
                    # TODO: pathParameters is a first-class citizen in apigateway but not available without
                    # some parsing work for ELB (is this parameter used for anything?)
                    event['pathParameters'] = ''
                else:
                    if headers:
                        host = headers.get('Host')
                    else:
                        host = None
                    logger.debug('host found: [{}]'.format(host))

                    if host:
                        if 'amazonaws.com' in host:
                            logger.debug('amazonaws found in host')
                            # The path provided in th event doesn't include the
                            # stage, so we must tell Flask to include the API
                            # stage in the url it calculates. See https://github.com/Miserlou/Zappa/issues/1014
                            script_name = '/' + settings.API_STAGE
                    else:
                        # This is a test request sent from the AWS console
                        if settings.DOMAIN:
                            # Assume the requests received will be on the specified
                            # domain. No special handling is required
                            pass
                        else:
                            # Assume the requests received will be to the
                            # amazonaws.com endpoint, so tell Flask to include the
                            # API stage
                            script_name = '/' + settings.API_STAGE

                base_path = getattr(settings, 'BASE_PATH', None)

                # Create the environment for WSGI and handle the request
                environ = create_wsgi_request(
                    event,
                    script_name=script_name,
                    base_path=base_path,
                    trailing_slash=self.trailing_slash,
                    binary_support=settings.BINARY_SUPPORT,
                    context_header_mappings=settings.CONTEXT_HEADER_MAPPINGS
                )

                # We are always on https on Lambda, so tell our wsgi app that.
                environ['HTTPS'] = 'on'
                environ['wsgi.url_scheme'] = 'https'
                environ['lambda.context'] = context
                environ['lambda.event'] = event

                # Execute the application
                with Response.from_app(self.wsgi_app, environ) as response:
                    # This is the object we're going to return.
                    # Pack the WSGI response into our special dictionary.
                    zappa_returndict = dict()

                    # Issue #1715: ALB support. ALB responses must always include
                    # base64 encoding and status description
                    if is_elb_context:
                        zappa_returndict.setdefault('isBase64Encoded', False)
                        zappa_returndict.setdefault('statusDescription', response.status)

                    if response.data:
                        if settings.BINARY_SUPPORT:
                            if not response.mimetype.startswith("text/") \
                                or response.mimetype != "application/json":
                                    zappa_returndict['body'] = base64.b64encode(response.data).decode('utf-8')
                                    zappa_returndict["isBase64Encoded"] = True
                            else:
                                zappa_returndict['body'] = response.data
                        else:
                            zappa_returndict['body'] = response.get_data(as_text=True)

                    zappa_returndict['statusCode'] = response.status_code
                    if 'headers' in event:
                        zappa_returndict['headers'] = {}
                        for key, value in response.headers:
                            zappa_returndict['headers'][key] = value
                    if 'multiValueHeaders' in event:
                        zappa_returndict['multiValueHeaders'] = {}
                        for key, value in response.headers:
                            zappa_returndict['multiValueHeaders'][key] = response.headers.getlist(key)

                    # Calculate the total response time,
                    # and log it in the Common Log format.
                    time_end = datetime.datetime.now()
                    delta = time_end - time_start
                    response_time_ms = delta.total_seconds() * 1000
                    response.content = response.data
                    common_log(environ, response, response_time=response_time_ms)

                    return zappa_returndict
        except Exception as e:  # pragma: no cover
            # Print statements are visible in the logs either way
            print(e)
            exc_info = sys.exc_info()
            message = ('An uncaught exception happened while servicing this request. '
                       'You can investigate this with the `zappa tail` command.')

            # If we didn't even build an app_module, just raise.
            if not settings.DJANGO_SETTINGS:
                try:
                    self.app_module
                except NameError as ne:
                    message = 'Failed to import module: {}'.format(ne.message)

            # Call exception handler for unhandled exceptions
            exception_handler = self.settings.EXCEPTION_HANDLER
            self._process_exception(exception_handler=exception_handler,
                                    event=event, context=context, exception=e)

            # Return this unspecified exception as a 500, using template that API Gateway expects.
            content = collections.OrderedDict()
            content['statusCode'] = 500
            body = {'message': message}
            if settings.DEBUG:  # only include traceback if debug is on.
                body['traceback'] = traceback.format_exception(*exc_info)  # traceback as a list for readability.
            content['body'] = json.dumps(str(body), sort_keys=True, indent=4)
            return content
198392
function wrapHandler(fnHandler) {
						var fnWrappedHandler = function(oEvent) {
							// The ready state at the time the event is occurring needs to
							// be preserved, to restore it when the handler is called delayed
							var iCurrentState = oXHR.readyState;
							function callHandler() {
								iReadyState = iCurrentState;
								// Only if the event has not been removed in the meantime
								// the handler needs to be called after the timeout
								if (fnWrappedHandler.active) {
									return fnHandler.call(oProxy, oEvent);
								}
							}
							// If this is an asynchronous request and a sync request is ongoing,
							// the execution of all following handler calls needs to be delayed
							if (!bSync && bSyncRequestOngoing) {
								bDelay = true;
							}
							if (bDelay) {
								_timeout(callHandler, 0);
								return true;
							}
							return callHandler();
						};
						fnHandler.wrappedHandler = fnWrappedHandler;
						fnWrappedHandler.active = true;
						return fnWrappedHandler;
					}
544906
def statichttp(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(event):
            return _handler(container, event, func)
        if hasattr(func, '__self__'):
            handler.__self__ = func.__self__
        return handler
    return decorator
946682
def thread(function):
    
    @wraps(function)
    def wrapper(*args, **kwargs):
        future = Future()

        launch_thread(_function_handler, function, args, kwargs, future)

        return future

    return wrapper
1330229
def with_cache(function):
        
        @wraps(function)
        def wrapped(cls, _cache_key, _cache_ignore, _cache_timeout, **kwargs):
            def clear_timeouts():
                """Clear the cache of timed out results."""
                for key in list(cls.timeouts):
                    if timer() - cls.timeouts[key] > _cache_timeout:
                        del cls.timeouts[key]
                        del cls.cache[key]

            if _cache_ignore:
                return function(cls, **kwargs)
            with cls.ca_lock:
                clear_timeouts()
                if _cache_key in cls.cache:
                    if cls.cache_hit_callback:
                        cls.cache_hit_callback(_cache_key)
                    return cls.cache[_cache_key]
            # Releasing the lock before actually making the request allows for
            # the possibility of more than one thread making the same request
            # to get through. Without having domain-specific caching (under the
            # assumption only one request to a domain can be made at a
            # time), there isn't a better way to handle this.
            result = function(cls, **kwargs)
            # The handlers don't call `raise_for_status` so we need to ignore
            # status codes that will result in an exception that should not be
            # cached.
            if result.status_code not in (200, 302):
                return result
            with cls.ca_lock:
                cls.timeouts[_cache_key] = timer()
                cls.cache[_cache_key] = result
                return result
        return wrapped
112888
def createHandler(self, handler):
        
        target = handler['target']
        if handler['type'] == 'log':
            self.logger.warning("Initialising csvlogger to log data to " + target)
            return CSVLogger('recorder', handler['name'], target)
        elif handler['type'] == 'post':
            self.logger.warning("Initialising http logger to log data to " + target)
            return HttpPoster(handler['name'], target)
1107948
function _readyStateChange(state) {
            this.readyState = state;

            if (typeof this.onreadystatechange == "function") {
                this.onreadystatechange();
            }

            this.dispatchEvent(new HttpRequestEvent("readystatechange"));

            if (this.readyState == IsotropyXMLHttpRequest.DONE) {
                this.dispatchEvent(new HttpRequestEvent("load", false, false, this));
                this.dispatchEvent(new HttpRequestEvent("loadend", false, false, this));
            }
        }
831810
def make_server(
        server_class, handler_class, authorizer_class, filesystem_class,
        host_port, file_access_user=None, **handler_options):
    
    from . import compat
    if isinstance(handler_class, compat.string_type):
        handler_class = import_class(handler_class)

    if isinstance(authorizer_class, compat.string_type):
        authorizer_class = import_class(authorizer_class)

    if isinstance(filesystem_class, compat.string_type):
        filesystem_class = import_class(filesystem_class)

    authorizer = authorizer_class(file_access_user)
    handler = handler_class
    for key, value in handler_options.items():
        setattr(handler, key, value)
    handler.authorizer = authorizer
    if filesystem_class is not None:
        handler.abstracted_fs = filesystem_class
    return server_class(host_port, handler)
337647
def state_callback(before_or_after = :before)
      method_name = :"#{before_or_after}_#{@order.state}"
      send(method_name) if respond_to?(method_name, true)
    end
115393
function invokeFunctionHandler(handler, args, checkArity, req, res, done) {
  // check if number of arguments provided matches the handler function arity
  if (checkArity && args.length < handler.length) { // < due to possible optionals
    done(new ModofunError(400, 'InvalidInput',
      `This operation requires ${handler.length} parameters. Received ${args.length}.`));
    return;
  }
  // set this in function call to the remaining relevant request data
  // could consider pushing the whole request object instead?
  // for now prefer to keep it to minimum to allow maximum flexibility
  const thisArg = {
    method: req.method,
    headers: req.headers,
    body: req.body,
    query: req.query,
    user: req.user
  };
  // call handler function with
  let result = handler.apply(thisArg, args);
  // handle results that are not a trusted Promise with Promise.resolve()
  // which also supports other then-ables
  if (result instanceof Promise === false) {
    result = Promise.resolve(result);
  }
  return result
    .then(value => {
      if (value === null) {
        done(new ModofunError(404, 'NullResponse', `${req.path} resource was not found`));
        return;
      }
      if (value === undefined || value === '') {
        res.status(204).end();
      } else {
        res.status(200).json(value);
      }
      done();
    })
    .catch(done);
}
623341
def add_done_callback(self, fn):  # pylint: disable=invalid-name
        
        if self._operation.done:
            _try_callback(self, fn)
        else:
            self._queue.put(dill.dumps(fn))
            if self._process is None:
                self._process = mp.Process(target=self._execute_tasks)
                self._process.start()
333461
function Zousan(func)
		{
			//  this.state = STATE_PENDING;	// Inital state (PENDING is undefined, so no need to actually have this assignment)
			//this.c = [];			// clients added while pending.   <Since 1.0.2 this is lazy instantiation>

			// If Zousan is called without "new", throw an error
			if (!(this instanceof Zousan)) throw new TypeError("Zousan must be created with the new keyword");

			// If a function was specified, call it back with the resolve/reject functions bound to this context
			if(typeof func === "function")
			{
				var me = this;
				try
				{
					func(
						function(arg) { me.resolve(arg) },	// the resolve function bound to this context.
						function(arg) { me.reject(arg) })	// the reject function bound to this context
				}
				catch(e)
				{
					me.reject(e);
				}
			}
			else if(arguments.length > 0) // If an argument was specified and it is NOT a function, throw an error
			{
				throw new TypeError("Zousan resolver " + func + " is not a function");
			}
		}
1054094
public CountingCompletionHandler<T> setHandler(Handler<AsyncResult<T>> doneHandler) {
    this.doneHandler = doneHandler;
    checkDone();
    return this;
  }