Hook that runs in response to a 'returned capacity' event
541056
def on_capacity(self, connection, command, query_kwargs, response,
                    capacity):
        
        now = time.time()
        args = (connection, command, query_kwargs, response, capacity)
        # Check total against the total_cap
        self._wait(args, now, self.total_cap, self._total_consumed,
                   capacity.total)

        # Increment table consumed capacity & check it
        if capacity.tablename in self.table_caps:
            table_cap = self.table_caps[capacity.tablename]
        else:
            table_cap = self.default_cap
        consumed_history = self.get_consumed(capacity.tablename)
        if capacity.table_capacity is not None:
            self._wait(args, now, table_cap, consumed_history,
                       capacity.table_capacity)
        # The local index consumed capacity also counts against the table
        if capacity.local_index_capacity is not None:
            for consumed in six.itervalues(capacity.local_index_capacity):
                self._wait(args, now, table_cap, consumed_history, consumed)

        # Increment global indexes
        # check global indexes against the table+index cap or default
        gic = capacity.global_index_capacity
        if gic is not None:
            for index_name, consumed in six.iteritems(gic):
                full_name = capacity.tablename + ':' + index_name
                if index_name in table_cap:
                    index_cap = table_cap[index_name]
                elif full_name in self.table_caps:
                    index_cap = self.table_caps[full_name]
                else:
                    # If there's no specified capacity for the index,
                    # use the cap on the table
                    index_cap = table_cap
                consumed_history = self.get_consumed(full_name)
                self._wait(args, now, index_cap, consumed_history, consumed)
827549
def ch_handler(offset=0, length=-1, **kw):
    
    global _lastSel

    offset = int(offset)
    length = int(length)
    if length < 0: length = len(_lastSel)
    return _lastSel[offset:offset+length]
1127344
function Atok (options) {
  if (!(this instanceof Atok))
    return new Atok(options)

  // Possible events are defined at instanciation for better performance
  EV.call(this, Atok.events)
  this.writable = true
  this.readable = true

  // Options
  options = options || {}
  this._encoding = null
  if (options.encoding) this.setEncoding( options.encoding )

  // Initializations
  // Debug flag
  this.debugMode = false

  // Status flags
  this.ended = false        // Flag indicating stream has ended
  this.ending = false       // Set when end() invokes write()
  this.paused = false       // Flag indicating stream is paused
  this.needDrain = false    // Flag indicating stream needs drain

//var keepRules = false
//include("Atok_properties.js")

//include("Atok_rule_properties.js")


  this._defaultProps = Object.keys(this)
    .filter(function (prop) {
      return /^_p_/.test(prop) && !/(continueOnFail|nextIndex)$/.test(prop)
    })
    .map(function (prop) {
      return prop.substr(3)
    })
}
869177
function(options,done) {

    request(options, function (err, response, payload) {
        if (err) {
            console.log('api call error');
            console.log(err);
        }

        done(err, payload, parseRateLimits(response.headers));
    });
}
486793
function handleResource( $tpl, &$resourceData, $method, &$extraParameters )
    {
        $path = $resourceData['template-name'];

        $matchKeys = $this->Keys;
        if ( isset( $GLOBALS['eZDesignKeys'] ) )
        {
            $matchKeys = array_merge( $matchKeys, $GLOBALS['eZDesignKeys'] );
            unset( $GLOBALS['eZDesignKeys'] );
            $this->Keys = $matchKeys;
        }
        if ( is_array( $extraParameters ) and
             isset( $extraParameters['ezdesign:keys'] ) )
        {
            $this->mergeKeys( $matchKeys, $extraParameters['ezdesign:keys'] );
        }
        $this->KeyStack[] = $this->Keys;
        $this->Keys = $matchKeys;

        eZDebug::accumulatorStart( 'override_cache', 'Override', 'Cache load' );

        if( !isset( $GLOBALS['eZOverrideTemplateCacheMap'] ) )
        {
            $overrideCacheFile = $this->createOverrideCache();

            if ( $overrideCacheFile )
            {
                include_once( $overrideCacheFile );
            }
        }

        if ( isset( $GLOBALS['eZOverrideTemplateCacheMap'] ) )
        {
            if( isset( $GLOBALS['eZOverrideTemplateCacheMap'][md5( '/' . $path )] ) )
            {
                $cacheMap = $GLOBALS['eZOverrideTemplateCacheMap'][md5( '/' . $path )];
                if ( !is_string( $cacheMap ) and trim( $cacheMap['code'] ) )
                {
                    eval( "\$matchFile = " . $cacheMap['code'] . ";" );
                }
                else
                {
                    $matchFile = $cacheMap;
                }
                $match['file'] = $matchFile;
            }
        }
        else
        {
            $template = "/" . $path;
            $matchFileArray = eZTemplateDesignResource::overrideArray( $this->OverrideSiteAccess );

            $matchFile = $matchFileArray[$template];

            if ( isset( $matchFile['custom_match'] ) )
            {
                $matchFound = false;
                foreach ( $matchFile['custom_match'] as $customMatch )
                {
                    $matchOverride = true;
                    if ( count( $customMatch['conditions'] ) > 0 )
                    {
                        foreach ( array_keys( $customMatch['conditions'] ) as $conditionKey )
                        {
                            // Create special substring match for subtree override
                            if ( $conditionKey == 'url_alias' )
                            {
                                if ( strpos( $matchKeys['url_alias'], $customMatch['conditions'][$conditionKey] ) === 0 )
                                {
                                }
                                else
                                {
                                    $matchOverride = false;
                                }
                            }
                            else if ( isset( $matchKeys[$conditionKey] ) and
                                      isset( $customMatch['conditions'][$conditionKey] ) )
                            {
                                if ( is_array( $matchKeys[$conditionKey] ) )
                                {
                                    if ( !in_array( $customMatch['conditions'][$conditionKey], $matchKeys[$conditionKey] ) )
                                    {
                                        $matchOverride = false;
                                    }
                                }
                                else if ( $matchKeys[$conditionKey] != $customMatch['conditions'][$conditionKey] )
                                {
                                    $matchOverride = false;
                                }
                            }
                            else
                            {
                                $matchOverride = false;
                            }
                        }
                        if ( $matchOverride == true )
                        {
                            $match['file'] = $customMatch['match_file'];
                            $matchFound = true;
                            break;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        // Default match without conditions
                        $match['file'] = $customMatch['match_file'];
                        $matchFound = true;
                    }
                }
                if ( !$matchFound )
                    $match['file'] = $matchFile['base_dir'] . $matchFile['template'];
            }
            else
            {
                $match['file'] = $matchFile['base_dir'] . $matchFile['template'];
            }
        }
        eZDebug::accumulatorStop( 'override_cache' );
        if ( isset( $match ) )
        {
            $file = $match["file"];

            $matchedKeys = array();
            $usedKeys = array();
            foreach ( $matchKeys as $matchKeyName => $matchKeyValue )
            {
                $usedKeys[$matchKeyName] = $matchKeyValue;
            }
            $extraParameters['ezdesign:used_keys'] = $usedKeys;
            $extraParameters['ezdesign:matched_keys'] = $matchedKeys;
            $tpl->setVariable( 'used', $usedKeys, 'DesignKeys' );
            $tpl->setVariable( 'matched', $matchedKeys, 'DesignKeys' );
            $resourceData['template-filename'] = $file;
            $result = eZTemplateFileResource::handleResourceData( $tpl, $this, $resourceData, $method, $extraParameters );
        }
        else
        {
            $result = false;
        }
        $this->Keys = array_pop( $this->KeyStack );
        return $result;
    }
175845
def consult_pre_response_hook(self, item_session: ItemSession) -> Actions:
        ''''''
        try:
            return self.hook_dispatcher.call(
                PluginFunctions.handle_pre_response,
                item_session
            )
        except HookDisconnected:
            return Actions.NORMAL
751889
function returnResponse(res, Handler, data, perfInstance) {
        var content = React.renderToString(React.createElement(Handler, { data: data })),
            html = '<!DOCTYPE html>' + content;
        options.log && log(options.log, 'perf', perfInstance());
        res.end(html);
    }
1274313
function (callback) {
                var boundCallback = _gpfArrayBind(callback, arguments);
                return !_gpfArrayEveryOwnFrom0(this, function (item, index, array) {
                    return !boundCallback(item, index, array);
                });
            }
640954
def trigger_hook(self, __name, *args, **kwargs):
        '''  '''
        return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
686086
def handle(cls, value, context, **kwargs):
        
        try:
            hook_name, key = value.split("::")
        except ValueError:
            raise ValueError("Invalid value for hook_data: %s. Must be in "
                             "<hook_name>::<key> format." % value)

        return context.hook_data[hook_name][key]
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);
}
206345
def fetch(self):
        
        self.limit.set_request_args(self.kwargs)
        data = self.connection.call(*self.args, **self.kwargs)
        self.limit.post_fetch(data)
        self.last_evaluated_key = data.get('LastEvaluatedKey')
        if self.last_evaluated_key is None:
            self.kwargs.pop('ExclusiveStartKey', None)
        else:
            self.kwargs['ExclusiveStartKey'] = self.last_evaluated_key
        self._update_capacity(data)
        if 'consumed_capacity' in data:
            self.consumed_capacity += data['consumed_capacity']
        for raw_item in data['Items']:
            item = self.connection.dynamizer.decode_keys(raw_item)
            if self.limit.accept(item):
                yield item
722719
function handler() {
        try {
          if (this.readyState === this.DONE) {

            var response = _buildResponse(this, options.fullResponse);

            // Resolve or reject promise given the response status.
            // HTTP status of 2xx is considered a success.
            if (this.status >= 200 && this.status < 300) {

              if (successCallback) {
                Logger.warnCallbackDeprecation();
                successCallback(response);
              }
              resolve(response);

            } else {
              errorHandler(response);
            }
          }
        } catch (exception) {
          // Do nothing, will be handled by ontimeout.
        }
      }
225031
def handle(event):
        
        def dec(func):
            if not hasattr(func, '_handle_events'):
                func._handle_events = set()
            func._handle_events.add(event)
            return func

        return dec
1237453
function(err, req, res, next) {

        function done(error) {
            log(req, util.format('middleware-end %s', name));
            next(error);
        }

        if (err && !errHandler) {
            log(req, util.format('skipped %s Hook is not for error handling', name));
            next(err);

        } else if (!err && errHandler) {
            log(req, util.format('skipped %s Hook is for error handling', name));
            next();

        } else {
            try {
                log(req, util.format('middleware-start %s', name));
                errHandler ? hook(err, req, res, done) : hook(req, res, done);
            } catch (err) {
                done(err);
            }

        }
    }
19133
protected void doLoad(int offset, int limit) {
        dataSource.load(new LoadConfig<>(offset, limit, table.getView().getSortContext(),
                table.getView().getOpenCategories()), new LoadCallback<T>() {
            @Override
            public void onSuccess(LoadResult<T> loadResult) {
                setOffset(loadResult.getOffset());
                totalRows = loadResult.getTotalLength();
                table.setVisibleRange(loadResult.getOffset(), loadResult.getData().size());
                table.loaded(loadResult.getOffset(), loadResult.getData());
                updateUi();
            }

            @Override
            public void onFailure(Throwable caught) {
                GWT.log("Load failure", caught);
                //TODO: What we need to do on failure? May be clear table?
            }
        });
    }
986262
function request(server, config, hooks, keys, request, callback) {
    const start = Date.now();

    if (typeof request === 'function' && typeof callback !== 'function') {
        callback = request;
        request = {};
    }

    // handle argument variations and get Request instance
    const args = Array.from(arguments).slice(4).filter(v => v !== undefined);
    const req = (function() {
        const length = args.length;
        if (length === 0) {
            return new Request(server, keys, config.rejectable);

        } else if (length === 1 && typeof args[0] === 'function') {
            callback = args[0];
            return new Request(server, keys, config.rejectable);

        } else {
            return new Request(server, keys, config.rejectable, request);
        }
    })();

    // event log aggregation
    const queue = config.logs ? [] : null;
    if (queue) req.on('log', event => queue.push(event));

    // if logging enabled then produce the log when the request is fulfilled or rejected
    if (queue) {
        const log = function(state) {
            const events = queue.map((event, index) => {
                const seconds = util.seconds(event.timestamp - (index > 0 ? queue[index - 1].timestamp : start));
                return '[+' + seconds + 's] ' + event.category + ':' + event.type + ' ' + event.data;
            });
            console.log(state.statusCode + ' ' + req.method + ' ' + req.url +
                (state.statusCode === 302 ? '\n  Redirect To: ' + state.headers['location']  : '') +
                '\n  ID: ' + req.id +
                '\n  Start: ' + new Date(start).toISOString() +
                '\n  Duration: ' + prettyPrint.seconds(Date.now() - start) +
                '\n  Events:\n    ' +
                events.join('\n    '));
        };
        req.then(log, () => log(req.res.state));
    }

    // copy hooks into request
    req.log('initialized');
    Object.keys(hooks).forEach(type => {
        hooks[type].forEach(d => {
            req.hook(type, d.weight, d.hook)
        });
    });
    req.log('hooks applied');

    // is using a callback paradigm then execute the callback
    if (typeof callback === 'function') req.then(state => callback(null, state), err => callback(err, req.res.state));

    return req;
}