:nocov:

 Auto-load all gRPC handlers

 :nocov:
176638
def load_controllers
      return unless File.directory?(controllers_path)

      path = File.realpath(controllers_path)
      $LOAD_PATH.unshift(path)
      Dir["#{path}/**/*.rb"].each do |f|
        next if f.include?('_pb') # exclude if people include proto generated files in app/rpc

        logger.info "- Loading gRPC service file: #{f}"
        load File.realpath(f)
      end
    end
632689
def dcc(self, *args, **kwargs):
        
        dcc = self.reactor.dcc(*args, **kwargs)
        self.dcc_connections.append(dcc)
        return dcc
1081743
def init_handler(args):
    
    try:
        initialize_repository(pathlib.Path.cwd())
    except ValueError as exc:
        print(exc, file=sys.stderr)
        return ExitCode.DATAERR

    return ExitCode.OK
389820
def run(self):
        
        _ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
        check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), None))
689406
def _container_handler(c, ctx):
    """"""
    _, self = (yield None)
    queue = ctx.queue
    child_context = None
    is_field_name = ctx.ion_type is IonType.STRUCT
    delimiter_required = False
    complete = ctx.depth == 0
    can_flush = False

    def has_pending_symbol():
        return child_context and child_context.pending_symbol is not None

    def symbol_value_event():
        return child_context.event_transition(
            IonEvent, IonEventType.SCALAR, IonType.SYMBOL, _as_symbol(child_context.pending_symbol))

    def pending_symbol_value():
        if has_pending_symbol():
            assert not child_context.value
            if ctx.ion_type is IonType.STRUCT and child_context.field_name is None:
                _illegal_character(c, ctx,
                                   'Encountered STRUCT value %s without field name.' % (child_context.pending_symbol,))
            return symbol_value_event()
        return None

    def is_value_decorated():
        return child_context is not None and (child_context.annotations or child_context.field_name is not None)

    def _can_flush():
        return child_context is not None and \
               child_context.depth == 0 and \
               (
                   (
                       child_context.ion_type is not None and
                       (
                           child_context.ion_type.is_numeric or
                           (child_context.ion_type.is_text and not ctx.quoted_text and not is_field_name)
                       )
                   ) or
                   (
                       child_context.line_comment and
                       not is_value_decorated()
                   )
               )

    while True:
        # Loop over all values in this container.
        if c in ctx.container.end or c in ctx.container.delimiter or BufferQueue.is_eof(c):
            symbol_event = pending_symbol_value()
            if symbol_event is not None:
                yield symbol_event
                child_context = None
                delimiter_required = ctx.container.is_delimited
            if c in ctx.container.end:
                if not delimiter_required and is_value_decorated():
                    _illegal_character(c, child_context,
                                       'Dangling field name (%s) and/or annotation(s) (%r) at end of container.'
                                       % (child_context.field_name, child_context.annotations))
                # Yield the close event and go to enclosing container. This coroutine instance will never resume.
                yield Transition(
                    IonEvent(IonEventType.CONTAINER_END, ctx.ion_type, depth=ctx.depth-1),
                    ctx.whence
                )
                raise ValueError('Resumed a finished container handler.')
            elif c in ctx.container.delimiter:
                if not delimiter_required:
                    _illegal_character(c, ctx.derive_child_context(None),
                                       'Encountered delimiter %s without preceding value.'
                                       % (_chr(ctx.container.delimiter[0]),))
                is_field_name = ctx.ion_type is IonType.STRUCT
                delimiter_required = False
                c = None
            else:
                assert BufferQueue.is_eof(c)
                assert len(queue) == 0
                yield ctx.read_data_event(self, complete=True)
                c = None
        if c is not None and c not in _WHITESPACE:
            can_flush = False
            if c == _SLASH:
                if child_context is None:
                    # This is the start of a new child value (or, if this is a comment, a new value will start after the
                    # comment ends).
                    child_context = ctx.derive_child_context(self)
                if ctx.ion_type is IonType.SEXP:
                    handler = _sexp_slash_handler(c, child_context, pending_event=pending_symbol_value())
                else:
                    handler = _comment_handler(c, child_context, self)
            elif delimiter_required:
                # This is not the delimiter, or whitespace, or the start of a comment. Throw.
                _illegal_character(c, ctx.derive_child_context(None), 'Delimiter %s not found after value.'
                                   % (_chr(ctx.container.delimiter[0]),))
            elif has_pending_symbol():
                # A character besides whitespace, comments, and delimiters has been found, and there is a pending
                # symbol. That pending symbol is either an annotation, a field name, or a symbol value.
                if c == _COLON:
                    if is_field_name:
                        is_field_name = False
                        child_context.set_field_name()
                        c = None
                    else:
                        assert not ctx.quoted_text
                        if len(queue) == 0:
                            yield ctx.read_data_event(self)
                        c = queue.read_byte()
                        if c == _COLON:
                            child_context.set_annotation()
                            c = None  # forces another character to be read safely
                        else:
                            # Colon that doesn't indicate a field name or annotation.
                            _illegal_character(c, child_context)
                else:
                    if is_field_name:
                        _illegal_character(c, child_context, 'Illegal character after field name %s.'
                                           % child_context.pending_symbol)
                    # It's a symbol value delimited by something other than a comma (i.e. whitespace or comment)
                    yield symbol_value_event()
                    child_context = None
                    delimiter_required = ctx.container.is_delimited
                continue
            else:
                if not is_value_decorated():
                    # This is the start of a new child value.
                    child_context = ctx.derive_child_context(self)
                if is_field_name:
                    handler = _FIELD_NAME_START_TABLE[c](c, child_context)
                else:
                    handler = _VALUE_START_TABLE[c](c, child_context)  # Initialize the new handler
                    can_flush = _IMMEDIATE_FLUSH_TABLE[c]
            container_start = c == _OPEN_BRACKET or \
                              c == _OPEN_PAREN  # _OPEN_BRACE might start a lob; that is handled elsewhere.
            quoted_start = c == _DOUBLE_QUOTE or c == _SINGLE_QUOTE
            while True:
                # Loop over all characters in the current token. A token is either a non-symbol value or a pending
                # symbol, which may end up being a field name, annotation, or symbol value.
                if container_start:
                    c = None
                    container_start = False
                else:
                    if child_context.quoted_text or quoted_start:
                        quoted_start = False
                        yield child_context.next_code_point(self)
                        c = child_context.code_point
                    else:
                        if len(queue) == 0:
                            yield ctx.read_data_event(self, can_flush=can_flush)
                        c = queue.read_byte()
                trans = handler.send((c, handler))
                if trans.event is not None:
                    is_self_delimiting = False
                    if child_context.is_composite:
                        # This is a composite transition, i.e. it is an event transition followed by an immediate
                        # transition to the handler coroutine for the next token.
                        next_transition = trans.next_transition
                        child_context = trans.next_context
                        assert next_transition is None or next_transition.event is None
                    else:
                        next_transition = None
                        is_self_delimiting = child_context.is_self_delimiting
                        child_context = None
                    # This child value is finished. c is now the first character in the next value or sequence.
                    # Hence, a new character should not be read; it should be provided to the handler for the next
                    # child context.
                    yield trans
                    event_ion_type = trans.event.ion_type  # None in the case of IVM event.
                    is_container = event_ion_type is not None and event_ion_type.is_container and \
                        trans.event.event_type is not IonEventType.SCALAR
                    if is_container:
                        assert next_transition is None
                        yield Transition(
                            None,
                            _container_handler(c, ctx.derive_container_context(trans.event.ion_type, self))
                        )
                    complete = ctx.depth == 0
                    can_flush = False
                    if is_container or is_self_delimiting:
                        # The end of the value has been reached, and c needs to be updated
                        assert not ctx.quoted_text
                        if len(queue) == 0:
                            yield ctx.read_data_event(self, complete, can_flush)
                        c = queue.read_byte()
                    delimiter_required = ctx.container.is_delimited
                    if next_transition is None:
                        break
                    else:
                        trans = next_transition
                elif self is trans.delegate:
                    child_context.set_ion_type(None)  # The next token will determine the type.
                    complete = False
                    can_flush = _can_flush()
                    if is_field_name:
                        assert not can_flush
                        if c == _COLON or not child_context.is_self_delimiting:
                            break
                    elif has_pending_symbol():
                        can_flush = ctx.depth == 0
                        if not child_context.is_self_delimiting or child_context.line_comment:
                            break
                    elif child_context.is_self_delimiting:
                        # This is the end of a comment. If this is at the top level and is un-annotated,
                        # it may end the stream.
                        complete = ctx.depth == 0 and not is_value_decorated()
                    # This happens at the end of a comment within this container, or when a symbol token has been
                    # found. In both cases, an event should not be emitted. Read the next character and continue.
                    if len(queue) == 0:
                        yield ctx.read_data_event(self, complete, can_flush)
                    c = queue.read_byte()
                    break
                # This is an immediate transition to a handler (may be the same one) for the current token.
                can_flush = _can_flush()
                handler = trans.delegate
        else:
            assert not ctx.quoted_text
            if len(queue) == 0:
                yield ctx.read_data_event(self, complete, can_flush)
            c = queue.read_byte()
51528
def get_handler(self, *args, **options):
        
        handler = super(Command, self).get_handler(*args, **options)
        insecure_serving = options.get('insecure_serving', False)
        if self.should_use_static_handler(options):
            return StaticFilesHandler(handler)
        return handler
483764
function AppLoader(appLoaderOpts, errEmitter) {
	this.load = load

	function load(cb) { // load data from parent process and all app Files
		var isError
		var cbCounter = 3
		var parentApps = {}
		var appFileApps = {}
		var launchBrowser

		parentloader.load(parentDataReceiver)
		appfileloader.loadAppFiles(appLoaderOpts.appFiles, fileDataReceiver)
		doneLoading()

		function parentDataReceiver(err, result) {
			if (result) {
				if (result.appMap) parentApps = result.appMap
				if (result.time) appLoaderOpts.launchTime = result.time
			}
			doneLoading(err)
		}

		function fileDataReceiver(err, appConfigs) {
			if (!err) appFileApps = appConfigs
			doneLoading(err)
		}

		function doneLoading(err) {
			if (!err) {
				if (!--cbCounter) updateAppEntity()
			} else if (!isError) {
				isError = true
				cb(err)
			}
		}

		/*
		appFileApps: the apps we should have
		parentApps: the apps that are currently running
		appLoaderOpts.apps: the apps frontend has configured

		app structure in config file json:
		key: app Name
		.id: optional string default derived from App name: app id
		.state: optional string default run: state on Node God launch, any of 'run', 'debug', 'stop'
		.folder: optional string folder: app launch folder default app id, absolute path or relative to Node God's parent folder
		.start: optional array of string: launch command and arguments for app, default ['node', .folder + '/app']
		.debug: optional array of string: debug launch command and arguments for app, default ['node', '--debug-brk', .folder + '/app']
		.watchFiles: optional string or regexp or array of those, default none: file to watch for app restart
		.watchCopy: optional object default none: key: destination path, value: source path
		- paths to file or folder, relative to .folder
		.signal boolean default from Node God settings: whether process accepts SIGUSR2 signal
		*/
		function updateAppEntity() {

			var feApps = {} // key: app id configured in frontend
			for (var appId in appLoaderOpts.apps) feApps[appId] = true

			var pApps = {} // key: app id that parent process has running
			for (var appId in parentApps) pApps[appId] = true
			for (var appId in appFileApps) { // create or update front end AppEntity instances
				var o = getAppConfig(appFileApps[appId], appId)
				if (!feApps[o.id]) appLoaderOpts.apps[o.id] = new appentity.AppEntity(o, parentApps[o.id]) // app is new to frontend
					.on('data', appLoaderOpts.appListener)
					.on('error', getErrorListener(o.id))
				else appLoaderOpts.apps[o.id].update(o)
				delete feApps[o.id]
				delete pApps[o.id]
			}

			for (var appId in feApps) { // close front end apps
				var appEntity = appLoaderOpts[o.id]
				delete appLoaderOpts[o.id]
				appEntity.close()
				appEntity.removeAllListener()
				delete pApps[o.id]
			}

			for (var appId in pApps) { // kill spurious patent process apps
				// TODO
			}

			if (launchBrowser) {
				appLoaderOpts.launchedBrowser = true
				haraldutil.browseTo(launchBrowser)
			}

			cb()
		}

		function getErrorListener(appId) {
			return listener

			function listener(err) {
				errEmitter.emit('error', new Error(appId + ': ' + err.message))
			}
		}

		function getAppConfig(fileApp, appId) {
			var o = {
				id: appId,
				name: fileApp.name,
			}

			o.state = states[fileApp.state || 0] ||  states[0]

			o.folder = path.resolve(appLoaderOpts.parentFolder, String(fileApp.folder || o.id)) // absolute path

			o.start = Array.isArray(fileApp.start) ? fileApp.start.map(makeString) :
				['node', path.join(o.folder, 'app')]

			o.debug = Array.isArray(fileApp.debug) ? fileApp.debug.map(makeString) :
				['node', '--debug-brk', path.join(o.folder, 'app')]

			o.watchFiles = typeof fileApp.watchFiles === 'string' || fileApp.watchFiles instanceof RegExp ? [fileApp.watchFiles] :
				Array.isArray(fileApp.watchFiles) ? fileApp.watchFiles.map(makeStringOrRegExp) :
				[]

			o.watchFileExclude = Array.isArray(fileApp.watchFileExclude) ? fileApp.watchFileExclude.map(makeString) :
				[]

			o.watchCopy = {}
			for (var dest in fileApp.watchCopy)
				o.watchCopy[
					path.resolve(o.folder, String(dest))] =
					path.resolve(o.folder, String(fileApp.watchCopy[dest]))

			o.signal = fileApp.signal != null ? !!fileApp.signal : appLoaderOpts.signal

			if (fileApp.launchBrowser && !appLoaderOpts.launchedBrowser) launchBrowser = fileApp.launchBrowser

			return o
		}

		function makeString(v) {
			return String(v)
		}

		function makeStringOrRegExp(v) {
			return v instanceof RegExp ? v : String(v)
		}
	}
}
17250
def autodoc_event_handlers(stream=sys.stdout):
    
    lines = []
    for cls in all_subclasses(EventHandler):
        if cls in _ABC_EVHANDLER_CLASSES: continue
        event_class = cls.event_class
        lines.extend(cls.cls2str().split("\n"))

        # Here we enforce the abstract protocol of the class
        # The unit test in tests_events will detect the problem.
        if not hasattr(cls, "can_change_physics"):
            raise RuntimeError("%s: can_change_physics must be defined" % cls)

    stream.write("\n".join(lines) + "\n")
604268
private void loadNoxItem(final int position, NoxItem noxItem, boolean useCircularTransformation) {
    imageLoader.load(noxItem.getUrl())
        .load(noxItem.getResourceId())
        .withPlaceholder(noxItem.getPlaceholderId())
        .size(noxItemSize)
        .useCircularTransformation(useCircularTransformation)
        .notify(getImageLoaderListener(position));
  }
137184
def to_grpc_params
      {
        pool_size: rpc_pool_size,
        max_waiting_requests: rpc_max_waiting_requests,
        poll_period: rpc_poll_period,
        pool_keep_alive: rpc_pool_keep_alive,
        server_args: rpc_server_args
      }
    end
1011284
def handler_all(func=None):
	
	if not func:
		return functools.partial(handler_all)

	registrations_global.append(func)

	return func
9251
def trace_grpc(tracer=None):
    """"""
    # Wrap google.cloud._helpers.make_secure_channel
    make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL)
    make_secure_channel_wrapped = wrap_make_secure_channel(
        make_secure_channel_func, tracer)
    setattr(
        _helpers,
        MAKE_SECURE_CHANNEL,
        make_secure_channel_wrapped)

    # Wrap the grpc.insecure_channel.
    insecure_channel_func = getattr(grpc, INSECURE_CHANNEL)
    insecure_channel_wrapped = wrap_insecure_channel(
        insecure_channel_func, tracer)
    setattr(
        grpc,
        INSECURE_CHANNEL,
        insecure_channel_wrapped)

    # Wrap google.api_core.grpc_helpers.create_channel
    create_channel_func = getattr(grpc_helpers, CREATE_CHANNEL)
    create_channel_wrapped = wrap_create_channel(create_channel_func, tracer)
    setattr(
        grpc_helpers,
        CREATE_CHANNEL,
        create_channel_wrapped)
598875
def autodiscover():
    
    global LOADED
    if LOADED:
        return
    LOADED = True
    for app in get_app_name_list():
        try:
            module = import_module(app)
        except ImportError:
            pass
        else:
            try:
                import_module("%s.page_processors" % app)
            except:
                if module_has_submodule(module, "page_processors"):
                    raise
711924
def populate_client_cache(self, low):
        '''
        
        '''
        reaction_type = low['state']
        if reaction_type not in self.client_cache:
            log.debug('Reactor is populating %s client cache', reaction_type)
            if reaction_type in ('runner', 'wheel'):
                # Reaction types that run locally on the master want the full
                # opts passed.
                self.client_cache[reaction_type] = \
                    self.reaction_class[reaction_type](self.opts)
                # The len() function will cause the module functions to load if
                # they aren't already loaded. We want to load them so that the
                # spawned threads don't need to load them. Loading in the
                # spawned threads creates race conditions such as sometimes not
                # finding the required function because another thread is in
                # the middle of loading the functions.
                len(self.client_cache[reaction_type].functions)
            else:
                # Reactions which use remote pubs only need the conf file when
                # instantiating a client instance.
                self.client_cache[reaction_type] = \
                    self.reaction_class[reaction_type](self.opts['conf_file'])
789464
def main(argv=None):
    
    parser = argparse.ArgumentParser(
        description='Event storage and event proxy.',
        usage='%(prog)s <configfile>'
    )
    parser.add_argument('--exit-codeword', metavar="MSG", dest="exit_message",
                        default=None, help="An incoming message that makes"
                                           " Rewind quit. Used for testing.")
    parser.add_argument('configfile')

    args = argv if argv is not None else sys.argv[1:]
    args = parser.parse_args(args)

    config = configparser.SafeConfigParser()
    with open(args.configfile) as f:
        config.readfp(f)

    exitcode = run(config, args.exit_message)
    return exitcode
1120543
def _struct_or_lob_handler(c, ctx):
    """"""
    assert c == _OPEN_BRACE
    c, self = yield
    yield ctx.immediate_transition(_STRUCT_OR_LOB_TABLE[c](c, ctx))
185564
def prepare_handler(cfg):
    
    positions, velocities, box = None, None, None
    _path = cfg.get('_path', './')
    forcefield = cfg.pop('forcefield', None)
    topology_args = sanitize_args_for_file(cfg.pop('topology'), _path)

    if 'checkpoint' in cfg:
        restart_args = sanitize_args_for_file(cfg.pop('checkpoint'), _path)
        restart = Restart.load(*restart_args)
        positions = restart.positions
        velocities = restart.velocities
        box = restart.box

    if 'positions' in cfg:
        positions_args = sanitize_args_for_file(cfg.pop('positions'), _path)
        positions = Positions.load(*positions_args)
        box = BoxVectors.load(*positions_args)

    if 'velocities' in cfg:
        velocities_args = sanitize_args_for_file(cfg.pop('velocities'), _path)
        velocities = Velocities.load(*velocities_args)

    if 'box' in cfg:
        box_args = sanitize_args_for_file(cfg.pop('box'), _path)
        box = BoxVectors.load(*box_args)

    options = {}
    for key in 'positions velocities box forcefield'.split():
        value = locals()[key]
        if value is not None:
            options[key] = value

    return SystemHandler.load(*topology_args, **options)