Rails controller stuff
========================
530
def setup
      set_descriptor :default 

      get_mxit_info

      @_mxit = descriptor
      @_mxit_validated = true
      @_mxit_validation_types = []
      @_mxit_validation_messages = []
      @_mxit_emulator = request.headers['X-Mxit-UserId-R'].nil?

      clean_session

      # Tidy multi-select if needed
      if params.include? :_mxit_rails_multi_select
        input = params[:_mxit_rails_multi_select].to_sym
        params.delete :_mxit_rails_multi_select

        array = mxit_form_session[input] || []
        array.map! {|item| item.to_sym}
        set = Set.new array

        if params.include? :_mxit_rails_multi_select_value
          value = params[:_mxit_rails_multi_select_value].to_sym
          params.delete :_mxit_rails_multi_select_value
          if set.include? value
            set.delete value
          else
            set.add value
          end
        end

        params[input] = set.to_a.map {|item| item.to_s}
        mxit_form_session[input] = set.to_a.map {|item| item.to_sym}
      end
    end
663495
private function createController(): void
    {
        $aFields  = $this->getArguments();
        $aCreated = [];

        try {

            $aControllers = array_filter(
                array_map(function ($sController) {
                    return implode('/', array_map('ucfirst', explode('/', ucfirst(trim($sController)))));
                }, explode(',', $aFields['CONTROLLER_NAME']))
            );
            $aMethods     = array_filter(
                array_map(function ($sMethod) {
                    return lcfirst(trim($sMethod));
                }, explode(',', $aFields['METHODS']))
            );

            sort($aControllers);

            foreach ($aControllers as $sController) {

                $aControllerBits = explode('/', $sController);
                $aControllerBits = array_map('ucfirst', $aControllerBits);

                if (count($aControllerBits) > 2) {
                    throw new ConsoleException('Controllers cannot be deeper than one directory');
                }

                $aFields['MODULE_NAME']     = getFromArray(0, $aControllerBits);
                $aFields['CONTROLLER_NAME'] = getFromArray(1, $aControllerBits, $aFields['MODULE_NAME']);
                $this->oOutput->write('Creating controller <comment>' . $sController . '</comment>... ');


                if (count($aControllerBits) == 2) {
                    //  A path has been specified, splice in the correct folder structure
                    $aLastControllerBits = array_splice($aControllerBits, -1, 1);
                    $aControllerBits     = array_merge(
                        array_map('lcfirst', $aControllerBits),
                        ['controllers'],
                        array_map('ucfirst', $aLastControllerBits)
                    );
                } else {
                    //  The controller should be in a folder called itself
                    $aControllerBits = array_merge(
                        array_map('lcfirst', $aControllerBits),
                        ['controllers'],
                        array_map('ucfirst', $aControllerBits)
                    );
                }

                $aViewBits = $aControllerBits;
                array_splice($aViewBits, -2, 1, ['views']);

                $sControllerPath     = self::CONTROLLER_PATH . implode('/', array_slice($aControllerBits, 0, -1)) . '/';
                $sViewPath           = self::CONTROLLER_PATH . implode('/', array_slice($aViewBits, 0, -1)) . '/';
                $sControllerFilename = end($aControllerBits) . '.php';
                $sClassName          = ucfirst(underscoreToCamelcase(end($aControllerBits)));

                $aFields['CONTROLLER_PATH']     = $sControllerPath;
                $aFields['CONTROLLER_FILENAME'] = $sControllerFilename;
                $aFields['CONTROLLER_CLASS']    = $sClassName;
                $aFields['VIEW_PATH']           = $sViewPath;

                //  Check if the controller already exists
                if (file_exists($sControllerPath . $sControllerFilename)) {
                    throw new ConsoleException(
                        'Controller "' . $sController . '" already exists at "' . $sControllerPath . $sControllerFilename . '"'
                    );
                }

                //  Generate methods
                if ($aFields['MODULE_NAME'] === $aFields['CONTROLLER_NAME']) {
                    $sViewPathPrefix = '';
                    $sViewPrefix     = lcfirst($aFields['CONTROLLER_NAME']) . '/';
                } else {
                    $sViewPathPrefix = $aFields['CONTROLLER_NAME'] . '/';
                    $sViewPrefix     = lcfirst($aFields['MODULE_NAME']) . '/' . $aFields['CONTROLLER_NAME'] . '/';
                }

                $aMethodStrings = [];
                $aViews         = [];
                reset($aMethods);
                foreach ($aMethods as $sMethod) {

                    $aViews[]         = $sViewPathPrefix . $sMethod;
                    $aMethodStrings[] = '';
                    $aMethodStrings[] = $this->getResource(
                        'template/controller_method.php',
                        [
                            'METHOD_NAME' => $sMethod,
                            'METHOD_VIEW' => $sViewPrefix . $sMethod,
                        ]
                    );
                    $aMethodStrings[] = '';
                    $aMethodStrings[] = '// --------------------------------------------------------------------------';
                }

                //  Remove the first item (blank string) and the last two (separators)
                $aMethodStrings = array_slice($aMethodStrings, 1, -2);

                //  Add leading tabs
                array_walk(
                    $aMethodStrings,
                    function (&$sLine) {
                        $sLine = trim($sLine);
                        if (!empty($sLine)) {
                            $aLines = explode("\n", $sLine);
                            foreach ($aLines as &$sSingleLine) {
                                $sSingleLine = $this->tabs(1) . $sSingleLine;
                            }
                            $sLine = implode("\n", $aLines);
                        }
                    }
                );

                $aFields['METHODS'] = implode("\n", $aMethodStrings);

                //  Ensure the path exists
                $this->createPath($aFields['CONTROLLER_PATH']);

                //  Create the controller and write to it
                $this->createFile(
                    $aFields['CONTROLLER_PATH'] . $aFields['CONTROLLER_FILENAME'],
                    $this->getResource('template/controller.php', $aFields)
                );
                $aCreated[] = $aFields['CONTROLLER_PATH'] . $aFields['CONTROLLER_FILENAME'];
                $this->oOutput->writeln('<info>done!</info>');

                //  Create the views
                $this->oOutput->write('Creating views for controller <comment>' . $sController . '</comment>... ');
                $this->createPath($aFields['VIEW_PATH']);

                foreach ($aViews as $sView) {
                    $sViewPath    = $aFields['VIEW_PATH'] . $sView . '.php';
                    $sViewSubPath = dirname($sView);
                    if ($sViewSubPath !== '.') {
                        $this->createPath($aFields['VIEW_PATH'] . $sViewSubPath);
                    }
                    $this->createFile(
                        $sViewPath,
                        $this->getResource(
                            'template/view.php',
                            [
                                'VIEW' => preg_replace('#^' . NAILS_APP_PATH . '#', '', $sViewPath),
                            ]
                        )
                    );
                    $aCreated[] = $sView;

                }
                $this->oOutput->writeln('<info>done!</info>');
            }

        } catch (ConsoleException $e) {
            $this->oOutput->writeln('<error>failed!</error>');
            //  Clean up created models
            if (!empty($aCreated)) {
                $this->oOutput->writeln('<error>Cleaning up - removing newly created files</error>');
                foreach ($aCreated as $sPath) {
                    @unlink($sPath);
                }
            }
            throw new ConsoleException($e->getMessage());
        }
    }
451013
static public function load()
    {
        if (!self::$helpersLoaded) {
            if (($router = Rails::application()->dispatcher()->router()) && ($route = $router->route())) {
                $controllerHelper = Rails::services()->get('inflector')->camelize($route->controller()) . 'Helper';
                array_unshift(self::$appQueue, $controllerHelper);
            }
            $appHelper = 'ApplicationHelper';
            array_unshift(self::$appQueue, $appHelper);
            
            foreach (array_unique(self::$appQueue) as $name) {
                self::loadHelper($name);
            }
            foreach (array_unique(self::$queue) as $name) {
                self::loadHelper($name, true);
            }
            
            # Add base helper
            self::$helpers[self::BASE_HELPER_NAME] = new Helper\Base();
            
            self::$helpersLoaded = true;
        }
    }
1265127
public function addCurrentController(): void
    {
        $controllerName = Inflector::camelize($this->_frontendData['request']['controller']);
        $this->addController(
            $controllerName . '.' . Inflector::camelize($this->_frontendData['request']['action'])
        );
        $this->addController($controllerName);
    }
1305157
function(req, res, next) {
			req.controller = controllerName;
			req.action = actionName || 'index';
			next();
		}
248823
private static function checkController()
    {
        $bSetFallback = false;
        $sControllerNamespace = Configuration::read('application.namespace') . '\Controller\\' . self::getController();
        if (class_exists($sControllerNamespace) === false) {
            $bSetFallback = true;
        }
        if (method_exists($sControllerNamespace, self::getAction()) === false) {
            $bSetFallback = true;
        }
        if ($bSetFallback === true) {
            // Set controller
            $sFallbackController = RouteCollection::getFallbackController();
            self::setController($sFallbackController);
            // Set action to route action
            $sFallbackAction = RouteCollection::getFallbackAction();
            self::setAction($sFallbackAction);
            // Set action to route action
            $arsFallbackParameter = array('code' => 404);
            self::setParameter($arsFallbackParameter);
        }
    }
699953
def find_controller(self, state):
        '''
        
        '''
        # get a sorted list of hooks, by priority (no controller hooks yet)
        req = state.request
        pecan_state = req.pecan

        # store the routing path for the current application to allow hooks to
        # modify it
        pecan_state['routing_path'] = path = req.path_info

        # handle "on_route" hooks
        self.handle_hooks(self.hooks, 'on_route', state)

        # lookup the controller, respecting content-type as requested
        # by the file extension on the URI
        pecan_state['extension'] = None

        # attempt to guess the content type based on the file extension
        if self.guess_content_type_from_ext \
                and not pecan_state['content_type'] \
                and '.' in path:
            _, extension = splitext(path.rstrip('/'))

            # preface with a letter to ensure compat for 2.5
            potential_type = guess_type('x' + extension)[0]

            if extension and potential_type is not None:
                path = ''.join(path.rsplit(extension, 1))
                pecan_state['extension'] = extension
                pecan_state['content_type'] = potential_type

        controller, remainder = self.route(req, self.root, path)
        cfg = _cfg(controller)

        if cfg.get('generic_handler'):
            raise exc.HTTPNotFound

        # handle generic controllers
        im_self = None
        if cfg.get('generic'):
            im_self = six.get_method_self(controller)
            handlers = cfg['generic_handlers']
            controller = handlers.get(req.method, handlers['DEFAULT'])
            handle_security(controller, im_self)
            cfg = _cfg(controller)

        # add the controller to the state so that hooks can use it
        state.controller = controller

        # if unsure ask the controller for the default content type
        content_types = cfg.get('content_types', {})
        if not pecan_state['content_type']:
            # attempt to find a best match based on accept headers (if they
            # exist)
            accept = getattr(req.accept, 'header_value', '*/*') or '*/*'
            if accept == '*/*' or (
                    accept.startswith('text/html,') and
                    list(content_types.keys()) in self.SIMPLEST_CONTENT_TYPES):
                pecan_state['content_type'] = cfg.get(
                    'content_type',
                    'text/html'
                )
            else:
                best_default = acceptparse.MIMEAccept(
                    accept
                ).best_match(
                    content_types.keys()
                )

                if best_default is None:
                    msg = "Controller '%s' defined does not support " + \
                          "content_type '%s'. Supported type(s): %s"
                    logger.error(
                        msg % (
                            controller.__name__,
                            pecan_state['content_type'],
                            content_types.keys()
                        )
                    )
                    raise exc.HTTPNotAcceptable()

                pecan_state['content_type'] = best_default
        elif cfg.get('content_type') is not None and \
                pecan_state['content_type'] not in content_types:

            msg = "Controller '%s' defined does not support content_type " + \
                  "'%s'. Supported type(s): %s"
            logger.error(
                msg % (
                    controller.__name__,
                    pecan_state['content_type'],
                    content_types.keys()
                )
            )
            raise exc.HTTPNotFound

        # fetch any parameters
        if req.method == 'GET':
            params = req.GET
        elif req.content_type in ('application/json',
                                  'application/javascript'):
            try:
                if not isinstance(req.json, dict):
                    raise TypeError('%s is not a dict' % req.json)
                params = NestedMultiDict(req.GET, req.json)
            except (TypeError, ValueError):
                params = req.params
        else:
            params = req.params

        # fetch the arguments for the controller
        args, varargs, kwargs = self.get_args(
            state,
            params.mixed(),
            remainder,
            cfg['argspec'],
            im_self
        )
        state.arguments = Arguments(args, varargs, kwargs)

        # handle "before" hooks
        self.handle_hooks(self.determine_hooks(controller), 'before', state)

        return controller, args + varargs, kwargs
510990
def init_controller(url):
    
    # pylint: disable=global-statement
    global _VERA_CONTROLLER
    created = False
    if _VERA_CONTROLLER is None:
        _VERA_CONTROLLER = VeraController(url)
        created = True
        _VERA_CONTROLLER.start()
    return [_VERA_CONTROLLER, created]
814625
def controller_info(self):
        """"""

        return [self._device.iotile_id, _pack_version(*self.os_info), _pack_version(*self.app_info)]
208259
def update
      @route_name ||= @controller_name ||= controller_name

      if @thing.update(thing_params)
        redirect_to things_path(@route_name), notice: "#{@controller_name.titleize} successfully updated."
      else
        @model = @thing.model_name.name.constantize
        render 'admin/edit'
      end
    end
197870
protected function loadController()
    {
        $env = Environment::get();
        $r = $env->getRecord(DIRNAME_AUTHENTICATION . '/' . $this->authTypeHandle . '/' . FILENAME_CONTROLLER);
        $prefix = $r->override ? true : $this->getPackageHandle();
        $authTypeHandle = Core::make('helper/text')->camelcase($this->authTypeHandle);
        $class = core_class('Authentication\\' . $authTypeHandle . '\\Controller', $prefix);
        $this->controller = Core::make($class, [$this]);
    }
846584
public void initControllers() throws SlickException {
		if (controllersInited) {
			return;
		}
		
		controllersInited = true;
		try {
			Controllers.create();
			int count = Controllers.getControllerCount();
			
			for (int i = 0; i < count; i++) {
				Controller controller = Controllers.getController(i);

				if ((controller.getButtonCount() >= 3) && (controller.getButtonCount() < MAX_BUTTONS)) {
					controllers.add(controller);
				}
			}
			
			Log.info("Found "+controllers.size()+" controllers");
			for (int i=0;i<controllers.size();i++) {
				Log.info(i+" : "+((Controller) controllers.get(i)).getName());
			}
		} catch (LWJGLException e) {
			if (e.getCause() instanceof ClassNotFoundException) {
				throw new SlickException("Unable to create controller - no jinput found - add jinput.jar to your classpath");
			}
			throw new SlickException("Unable to create controllers");
		} catch (NoClassDefFoundError e) {
			// forget it, no jinput availble
		}
	}
69139
def auto_link_paths
      paths = (controller_name / action_name).split('/')
      first = paths.shift
      paths.inject( [first] ) do |memo, val|
        memo.push [memo.last, val].join('/')
      end
    end
301526
def check_storage_controllers():
    
    if ctrl_flag:
        ctrl = walk_data(sess, oid_ctrl, helper)[0]
        for x, data in enumerate(ctrl, 1):
            ctrl_summary_output, ctrl_long_output = state_summary(data, 'Controller %d' % x, normal_state, helper)
            add_output(ctrl_summary_output, ctrl_long_output, helper)
434225
def setup(self):
        
        [c.start() for c in self.controllers]
        [c.wait_to_start() for c in self.controllers]
701840
function (input, controller, controller_property) {
	return {
		input      : input,
		value      : controller[controller_property] = input.invoke(),
		is_changed : function () {
			var value = controller[controller_property] = this.input.invoke();
			if (this.value !== value) {
				this.value = value;
				return true;
			}
		}
	};
}
1360249
def controller_callback(which, type, axis, value, button)
      # All controller events
      @events[:controller].each do |id, e|
        e.call(ControllerEvent.new(which, type, axis, value, button))
      end

      case type
      # When controller axis motion, like analog sticks
      when :axis
        @events[:controller_axis].each do |id, e|
          e.call(ControllerAxisEvent.new(which, axis, value))
        end
      # When controller button is pressed
      when :button_down
        @events[:controller_button_down].each do |id, e|
          e.call(ControllerButtonEvent.new(which, button))
        end
      # When controller button is released
      when :button_up
        @events[:controller_button_up].each do |id, e|
          e.call(ControllerButtonEvent.new(which, button))
        end
      end
    end