////////////////////////////////// ## RUN ## Main command router //////////////////////////////////
436212
function run (command, args, cb) {
    if (typeof cb !== 'function') {
      var cb = cbmain
    }
    my.args = args
    my.command = command
    if (my.state) {
      parseState( function (err) {
        if (err) return cb(err)
        switchboard(cb)
      })
    }
    else {
      readState(function (err, state) {
        if (err) return cb(err)
        setState(state)
        parseState( function (err) {
          if (err) return cb(err)
          switchboard(cb)
        }) //end parseState
      }) // end readState
    }

    function switchboard(cb) {
      switch (my.command) {
      case 'init':
        init(cb);
        break
      case 'add':
        add(cb)
        break
      case 'remove':
        remove(cb);
        break
      case 'bin':
        bin(cb);
        break
      case 'checkout':
        checkout(cb);
        break
      case 'status':
        status(cb);
        break
      case 'push':
        push(cb);
        break
      default:
        cb( erf( (command === undefined) ? '' :
                 'Unknown command: ' + command , usage) )
      }
    } // end SWITCHBOARD
  }
306498
func Run(apps map[string]interface{}, port string) {
	router := mux.NewRouter()
	initialize(apps, router)

	n := negroni.Classic()
	n.UseHandler(router)
	n.Run(":" + port)
}
634723
function Router () {
    EventEmitter.apply(this);   // Call EventEmitter constructor

    this.routes = [];           // Array containing all routes
    this.path = '/';            // Current path (`/` is default)
    this.otherwise(this.path);  // Set default redirect
    this.cancel = false;        // Cancel next route change
    this.redirect = null;       // Redirect next route change

    this.recentReloads = 0;     // Number of reloads called in last 500ms
    this.resetTimer = null;     // Timeout set to clear recent reloads

    this.html5(false);          // Disable HTML5 mode by default
}
519390
func main() {
	if len(os.Args) < 2 {
		processes()
		return
	}

	cmd := os.Args[1]

	// See if it is a PID.
	pid, err := strconv.Atoi(cmd)
	if err == nil {
		processInfo(pid)
		return
	}

	if cmd == "help" {
		usage("")
	}

	if cmd == "tree" {
		displayProcessTree()
		return
	}

	fn, ok := cmds[cmd]
	if !ok {
		usage("unknown subcommand")
	}
	if len(os.Args) < 3 {
		usage("Missing PID or address.")
		os.Exit(1)
	}
	addr, err := targetToAddr(os.Args[2])
	if err != nil {
		fmt.Fprintf(os.Stderr, "Couldn't resolve addr or pid %v to TCPAddress: %v\n", os.Args[2], err)
		os.Exit(1)
	}
	var params []string
	if len(os.Args) > 3 {
		params = append(params, os.Args[3:]...)
	}
	if err := fn(*addr, params); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}
519174
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="Web server Host address to bind to",
                        default="0.0.0.0", action="store", required=False)
    parser.add_argument("-p", "--port", help="Web server Port to bind to",
                        default=8080, action="store", required=False)
    args = parser.parse_args()

    logging.basicConfig()
    run(host=args.host, port=args.port, reloader=True, server=SERVER)
60957
func main() {
	app := cli.NewApp()
	app.Name = Name
	app.Version = Version
	app.Author = "kyokomi"
	app.Email = ""
	app.Usage = ""

	app.Flags = GlobalFlags
	app.Commands = Commands
	app.CommandNotFound = CommandNotFound

	app.Run(os.Args)
}
766254
func main() {
	flag.Parse()

	// set the log level to Trace
	log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))

	// register a single ping-pong service
	services := map[string]adapters.ServiceFunc{
		"ping-pong": func(ctx *adapters.ServiceContext) (node.Service, error) {
			return newPingPongService(ctx.Config.ID), nil
		},
	}
	adapters.RegisterServices(services)

	// create the NodeAdapter
	var adapter adapters.NodeAdapter

	switch *adapterType {

	case "sim":
		log.Info("using sim adapter")
		adapter = adapters.NewSimAdapter(services)

	case "exec":
		tmpdir, err := ioutil.TempDir("", "p2p-example")
		if err != nil {
			log.Crit("error creating temp dir", "err", err)
		}
		defer os.RemoveAll(tmpdir)
		log.Info("using exec adapter", "tmpdir", tmpdir)
		adapter = adapters.NewExecAdapter(tmpdir)

	default:
		log.Crit(fmt.Sprintf("unknown node adapter %q", *adapterType))
	}

	// start the HTTP API
	log.Info("starting simulation server on 0.0.0.0:8888...")
	network := simulations.NewNetwork(adapter, &simulations.NetworkConfig{
		DefaultService: "ping-pong",
	})
	if err := http.ListenAndServe(":8888", simulations.NewServer(network)); err != nil {
		log.Crit("error starting simulation server", "err", err)
	}
}
205706
function run() {
		if ($this->blacklisted($this->hive['IP']))
			// Spammer detected
			$this->error(403);
		if (!$this->hive['ROUTES'])
			// No routes defined
			user_error(self::E_Routes,E_USER_ERROR);
		// Match specific routes first
		$paths=[];
		foreach ($keys=array_keys($this->hive['ROUTES']) as $key) {
			$path=preg_replace('/@\w+/','*@',$key);
			if (substr($path,-1)!='*')
				$path.='+';
			$paths[]=$path;
		}
		$vals=array_values($this->hive['ROUTES']);
		array_multisort($paths,SORT_DESC,$keys,$vals);
		$this->hive['ROUTES']=array_combine($keys,$vals);
		// Convert to BASE-relative URL
		$req=urldecode($this->hive['PATH']);
		$preflight=FALSE;
		if ($cors=(isset($this->hive['HEADERS']['Origin']) &&
			$this->hive['CORS']['origin'])) {
			$cors=$this->hive['CORS'];
			header('Access-Control-Allow-Origin: '.$cors['origin']);
			header('Access-Control-Allow-Credentials: '.
				$this->export($cors['credentials']));
			$preflight=
				isset($this->hive['HEADERS']['Access-Control-Request-Method']);
		}
		$allowed=[];
		foreach ($this->hive['ROUTES'] as $pattern=>$routes) {
			if (!$args=$this->mask($pattern,$req))
				continue;
			ksort($args);
			$route=NULL;
			$ptr=$this->hive['CLI']?self::REQ_CLI:$this->hive['AJAX']+1;
			if (isset($routes[$ptr][$this->hive['VERB']]) ||
				isset($routes[$ptr=0]))
				$route=$routes[$ptr];
			if (!$route)
				continue;
			if (isset($route[$this->hive['VERB']]) && !$preflight) {
				if ($this->hive['VERB']=='GET' &&
					preg_match('/.+\/$/',$this->hive['PATH']))
					$this->reroute(substr($this->hive['PATH'],0,-1).
						($this->hive['QUERY']?('?'.$this->hive['QUERY']):''));
				list($handler,$ttl,$kbps,$alias)=$route[$this->hive['VERB']];
				// Capture values of route pattern tokens
				$this->hive['PARAMS']=$args;
				// Save matching route
				$this->hive['ALIAS']=$alias;
				$this->hive['PATTERN']=$pattern;
				if ($cors && $cors['expose'])
					header('Access-Control-Expose-Headers: '.
						(is_array($cors['expose'])?
							implode(',',$cors['expose']):$cors['expose']));
				if (is_string($handler)) {
					// Replace route pattern tokens in handler if any
					$handler=preg_replace_callback('/({)?@(\w+\b)(?(1)})/',
						function($id) use($args) {
							$pid=count($id)>2?2:1;
							return isset($args[$id[$pid]])?
								$args[$id[$pid]]:
								$id[0];
						},
						$handler
					);
					if (preg_match('/(.+)\h*(?:->|::)/',$handler,$match) &&
						!class_exists($match[1]))
						$this->error(404);
				}
				// Process request
				$result=NULL;
				$body='';
				$now=microtime(TRUE);
				if (preg_match('/GET|HEAD/',$this->hive['VERB']) && $ttl) {
					// Only GET and HEAD requests are cacheable
					$headers=$this->hive['HEADERS'];
					$cache=Cache::instance();
					$cached=$cache->exists(
						$hash=$this->hash($this->hive['VERB'].' '.
							$this->hive['URI']).'.url',$data);
					if ($cached) {
						if (isset($headers['If-Modified-Since']) &&
							strtotime($headers['If-Modified-Since'])+
								$ttl>$now) {
							$this->status(304);
							die;
						}
						// Retrieve from cache backend
						list($headers,$body,$result)=$data;
						if (!$this->hive['CLI'])
							array_walk($headers,'header');
						$this->expire($cached[0]+$ttl-$now);
					}
					else
						// Expire HTTP client-cached page
						$this->expire($ttl);
				}
				else
					$this->expire(0);
				if (!strlen($body)) {
					if (!$this->hive['RAW'] && !$this->hive['BODY'])
						$this->hive['BODY']=file_get_contents('php://input');
					ob_start();
					// Call route handler
					$result=$this->call($handler,[$this,$args,$handler],
						'beforeroute,afterroute');
					$body=ob_get_clean();
					if (isset($cache) && !error_get_last()) {
						// Save to cache backend
						$cache->set($hash,[
							// Remove cookies
							preg_grep('/Set-Cookie\:/',headers_list(),
								PREG_GREP_INVERT),$body,$result],$ttl);
					}
				}
				$this->hive['RESPONSE']=$body;
				if (!$this->hive['QUIET']) {
					if ($kbps) {
						$ctr=0;
						foreach (str_split($body,1024) as $part) {
							// Throttle output
							$ctr++;
							if ($ctr/$kbps>($elapsed=microtime(TRUE)-$now) &&
								!connection_aborted())
								usleep(1e6*($ctr/$kbps-$elapsed));
							echo $part;
						}
					}
					else
						echo $body;
				}
				if ($result || $this->hive['VERB']!='OPTIONS')
					return $result;
			}
			$allowed=array_merge($allowed,array_keys($route));
		}
		if (!$allowed)
			// URL doesn't match any route
			$this->error(404);
		elseif (!$this->hive['CLI']) {
			if (!preg_grep('/Allow:/',$headers_send=headers_list()))
				// Unhandled HTTP method
				header('Allow: '.implode(',',array_unique($allowed)));
			if ($cors) {
				if (!preg_grep('/Access-Control-Allow-Methods:/',$headers_send))
					header('Access-Control-Allow-Methods: OPTIONS,'.
						implode(',',$allowed));
				if ($cors['headers'] &&
					!preg_grep('/Access-Control-Allow-Headers:/',$headers_send))
					header('Access-Control-Allow-Headers: '.
						(is_array($cors['headers'])?
							implode(',',$cors['headers']):
							$cors['headers']));
				if ($cors['ttl']>0)
					header('Access-Control-Max-Age: '.$cors['ttl']);
			}
			if ($this->hive['VERB']!='OPTIONS')
				$this->error(405);
		}
		return FALSE;
	}
223499
public function main() {
    $command = array();

    $command[] = !empty($this->bin) ? $this->bin : 'drush';

    if (!empty($this->alias)) {
      $command[] = $this->alias;
    }

    if (empty($this->color)) {
      $option = new Option();
      $option->setName('nocolor');
      $this->options[] = $option;
    }


    if (!empty($this->root)) {
      $option = new Option();
      $option->setName('root');
      $option->addText($this->root);
      $this->options[] = $option;
    }

    if (!empty($this->uri)) {
      $option = new Option();
      $option->setName('uri');
      $option->addText($this->uri);
      $this->options[] = $option;
    }

    if (!empty($this->config)) {
      $option = new Option();
      $option->setName('config');
      $option->addText($this->config);
      $this->options[] = $option;
    }

    if (!empty($this->aliasPath)) {
      $option = new Option();
      $option->setName('alias-path');
      $option->addText($this->uri);
      $this->options[] = $option;
    }

    if (is_bool($this->assume)) {
      $option = new Option();
      $option->setName(($this->assume ? 'yes' : 'no'));
      $this->options[] = $option;
    }

    if ($this->simulate) {
      $option = new Option();
      $option->setName('simulate');
      $this->options[] = $option;
    }

    if ($this->pipe) {
      $option = new Option();
      $option->setName('pipe');
      $this->options[] = $option;
    }

    if ($this->verbose) {
      $option = new Option();
      $option->setName('verbose');
      $this->options[] = $option;
    }

    foreach ($this->options as $option) {
      $command[] = $option->toString();
    }

    $command[] = $this->command;

    foreach ($this->params as $param) {
      $command[] = '"' . escapeshellcmd($param->getValue()) . '"';
    }

    $command = implode(' ', $command);

    if ($this->dir !== NULL) {
      $currdir = getcwd();
      @chdir($this->dir->getPath());
    }

    // Execute Drush.
    $this->log("Executing '$command'...");
    $output = array();
    exec($command, $output, $return);

    if (isset($currdir)) {
      @chdir($currdir);
    }

    // Collect Drush output for display through Phing's log.
    foreach ($output as $line) {
      $this->log($line);
    }
    // Set value of the 'pipe' property.
    if (!empty($this->returnProperty)) {
      $this->getProject()->setProperty($this->returnProperty, implode($this->returnGlue, $output));
    }
    // Build fail.
    if ($this->haltOnError && $return != 0) {
      throw new \BuildException("Drush exited with code $return");
    }
    return $return != 0;
  }
441025
function Router() {
    var resources = {};

    // Public methods
    this.addRoute = function(resource) {
        var mPoint = resource.getMountPoint();

        if (typeof(resources[mPoint]) === 'undefined') {
            resources[mPoint] = resource;
        } else {
            resources[mPoint].update(resource);
        }
    };

    this.dispatch = function(locals) {
        var accept = locals.getAcceptedTypes();
        var request = locals.getRequest();
        var dispatched = false;
        var header;
        var mountPoint;
        var resource;

        locals.updateResponse(404);
        // Iterate over the resources
        for (mountPoint in resources) {
            // Did anybody flush already?
            resource = resources[mountPoint];
            // Does your URL definition matches this path?
            if (resource.matchesURL(request.path)) {
                locals.updateResponse(405);
                // Do you handle this method?
                if (resource.allowsMethod(request.method)) {
                    locals.updateResponse(406);
                    // Do you understand this format?
                    if (resource.acceptsType(accept, request.method)) {
                        locals.updateResponse(200);
                        // It's all yours
                        resource.takeOver(locals);
                        // And we set a flag announcing it was dispatched
                        dispatched = true;
                    }
                } else {
                    header = resource.getMethods().join(', ');
                    locals.getResponse().setHeader('Allow', header);
                }
            }
        }

        // Each resource emits a 'Resource:postRequest' event that flushes
        // the response. If no resource was found, that event was not emitted
        // and we need to do it manually.
        if (!dispatched) {
            locals.emit('Resource:completed');
            locals.emit('Resource:preRequest');
            locals.emit('Resource:postRequest');
        }
    };
}
508752
func main() {
	buildInfo := &BuildInfo{}
	OptionsParser := flags.NewParser(&options, flags.PassAfterNonOption|flags.HelpFlag)
	OptionsParser.ShortDescription = "DOSA CLI - The command-line tool for your DOSA client"
	OptionsParser.LongDescription = `
dosa manages your schema both in production and development scopes`

	c, _ := OptionsParser.AddCommand("version", "display build info", "display build info", &BuildInfo{})

	c, _ = OptionsParser.AddCommand("scope", "commands to manage scope", "create, drop, or truncate development scopes", &ScopeOptions{})
	_, _ = c.AddCommand("create", "Create scope", "creates a new scope", newScopeCreate(provideAdminClient))
	_, _ = c.AddCommand("drop", "Drop scope", "drops a scope", newScopeDrop(provideAdminClient))
	_, _ = c.AddCommand("truncate", "Truncate scope", "truncates a scope", newScopeTruncate(provideAdminClient))

	_, _ = c.AddCommand("list", "List scopes", "lists scopes", newScopeList(provideMDClient))
	_, _ = c.AddCommand("show", "Show scope MD", "show scope metadata", newScopeShow(provideMDClient))

	c, _ = OptionsParser.AddCommand("schema", "commands to manage schemas", "check or update schemas", &SchemaOptions{})
	_, _ = c.AddCommand("check", "Check schema", "check the schema", newSchemaCheck(provideAdminClient))
	_, _ = c.AddCommand("upsert", "Upsert schema", "insert or update the schema", newSchemaUpsert(provideAdminClient))
	_, _ = c.AddCommand("dump", "Dump schema", "display the schema in a given format", &SchemaDump{})
	_, _ = c.AddCommand("status", "Check schema status", "Check application status of schema", newSchemaStatus(provideAdminClient))

	c, _ = OptionsParser.AddCommand("query", "commands to do query", "fetch one or multiple rows", &QueryOptions{})
	_, _ = c.AddCommand("read", "Read query", "read a row by primary keys", newQueryRead(provideShellQueryClient))
	_, _ = c.AddCommand("range", "Range query", "read rows with range of primary keys and indexes", newQueryRange(provideShellQueryClient))

	// TODO: implement admin subcommand
	// c, _ = OptionsParser.AddCommand("admin", "commands to administrate", "", &AdminOptions{})

	_, err := OptionsParser.Parse()

	if options.Version {
		_, _ = fmt.Fprintf(os.Stdout, "%s\n", buildInfo.String())
		options.Version = false // for tests, we leak state between runs
		exit(0)
	}

	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Error: %s\n", err)
		exit(1)
		return
	}

	exit(0)
}
1332127
func Run() {
	if Config.Debug {
		gin.SetMode(gin.DebugMode)
		log.SetLevel(log.DebugLevel)
	} else {
		gin.SetMode(gin.ReleaseMode)
		log.SetLevel(log.InfoLevel)
	}

	if Config.MongoLogging {
		mongoURIParsed, _ := url.Parse(Config.MongoURL)

		hooker, err := mgorus.NewHooker(mongoURIParsed.Host, mongoURIParsed.Path[1:], "logs")

		if err == nil {
			log.AddHook(hooker)
		}
	}

	// This will test TG tokens and creates API
	time.Sleep(time.Second * 1)
	initBots()

	for _, s := range services {
		if Config.IsStandAloneServiceInstance() {
			// save the service info as a job to Redis. The MAIN instance will process it
			serviceURL := Config.StandAloneServiceURL
			if serviceURL == "" {
				serviceURL = fmt.Sprintf("http://%s:%s", s.Name, Config.Port)
			}
			_, err := ensureStandAloneServiceJob.Schedule(1, time.Now(), s.Name, serviceURL, s.Bot().tgToken())

			if err != nil {
				log.WithError(err).Panic("ensureStandAloneServiceJob error")
			}
		}
	}

	// Configure
	router := gin.New()

	// register some HTML templates
	templ := template.Must(template.New("webpreview").Parse(htmlTemplateWebpreview))
	template.Must(templ.New("determineTZ").Parse(htmlTemplateDetermineTZ))

	router.SetHTMLTemplate(templ)

	// Middlewares
	router.Use(cloneMiddleware)
	router.Use(ginRecovery)
	router.Use(ginLogger)

	if Config.Debug {
		router.Use(gin.Logger())
	}

	if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
		router.StaticFile("/", "index.html")
	}

	router.NoRoute(func(c *gin.Context) {
		// todo: good 404
		if len(c.Request.RequestURI) > 10 && (c.Request.RequestURI[1:2] == "c" || c.Request.RequestURI[1:2] == "u" || c.Request.RequestURI[1:2] == "h") {
			c.String(404, "Hi here!! This link isn't working in a browser. Please follow the instructions in the chat")
		}
	})

	/*
		Possible URLs

		Service webhooks:

		token resolving handled by framework:
		/service_name/token
		/token - DEPRECATED, to be removed, auto-detect the service

		token resolving handled by service
		/service_name/service
		/service_name

		OAuth:
		/oauth1/service_name/auth_temp_id – OAuth1 initial redirect

		/auth/service_name - OAuth2 redirect URL
		/auth/service_name/provider_id - adds provider_id for the custom OAuth provider (e.g. self-hosted instance)


		WebPreview resolving:
		/a/token
	*/

	router.HEAD("/:param1/:param2/:param3", serviceHookHandler)
	router.GET("/:param1/:param2/:param3", serviceHookHandler)
	router.POST("/:param1/:param2/:param3", serviceHookHandler)

	router.HEAD("/:param1/:param2", serviceHookHandler)
	router.GET("/:param1/:param2", serviceHookHandler)
	router.POST("/:param1/:param2", serviceHookHandler)

	router.HEAD("/:param1", serviceHookHandler)
	router.GET("/:param1", serviceHookHandler)
	router.POST("/:param1", serviceHookHandler)

	// Start listening

	var err error

	go gracefulShutdownJobPools()

	if Config.Port == "443" || Config.Port == "1443" {
		if _, err := os.Stat(Config.ConfigDir + string(os.PathSeparator) + "ssl.crt"); !os.IsNotExist(err) {
			log.Infof("SSL: Using ssl.key/ssl.crt")
			err = router.RunTLS(":"+Config.Port, Config.ConfigDir+string(os.PathSeparator)+"ssl.crt", Config.ConfigDir+string(os.PathSeparator)+"ssl.key")
		} else {
			log.Fatalf("INTEGRAM_PORT set to 443, but ssl.crt and ssl.key files not found at '%s'", Config.ConfigDir)
		}

	} else {
		if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
			log.Warnf("WARNING! It is recommended to use Integram with a SSL.\n"+
				"Set the INTEGRAM_PORT to 443 and put integram.crt & integram.key files at '%s'", Config.ConfigDir)
		}
		err = router.Run(":" + Config.Port)
	}

	if err != nil {
		log.WithError(err).Fatal("Can't start the router")
	}
}
413380
public function run()
    {
        /*echo '<pre>';
        print_r($this->router->getRoutes());
        die;*/
        try {
            $this->runAddedExceptions();

            if ($this->router->dispatch()) {
                $this->router->execute($this->container);
            } else {
                if ($this->notFoundModified) {
                    $fnc = $this->notFoundModified->bindTo($this->container);
                    $fnc();
                } else {
                    $this->render->renderNotFoundPage();
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
787064
func main() {
	// Add routes to the global handler
	goji.Get("/", Root)
	// Fully backwards compatible with net/http's Handlers
	goji.Get("/greets", http.RedirectHandler("/", 301))
	// Use your favorite HTTP verbs
	goji.Post("/greets", NewGreet)
	// Use Sinatra-style patterns in your URLs
	goji.Get("/users/:name", GetUser)
	// Goji also supports regular expressions with named capture groups.
	goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet)

	// Middleware can be used to inject behavior into your app. The
	// middleware for this application are defined in middleware.go, but you
	// can put them wherever you like.
	goji.Use(PlainText)

	// If the patterns ends with "/*", the path is treated as a prefix, and
	// can be used to implement sub-routes.
	admin := web.New()
	goji.Handle("/admin/*", admin)

	// The standard SubRouter middleware helps make writing sub-routers
	// easy. Ordinarily, Goji does not manipulate the request's URL.Path,
	// meaning you'd have to repeat "/admin/" in each of the following
	// routes. This middleware allows you to cut down on the repetition by
	// eliminating the shared, already-matched prefix.
	admin.Use(middleware.SubRouter)
	// You can also easily attach extra middleware to sub-routers that are
	// not present on the parent router. This one, for instance, presents a
	// password prompt to users of the admin endpoints.
	admin.Use(SuperSecure)

	admin.Get("/", AdminRoot)
	admin.Get("/finances", AdminFinances)

	// Goji's routing, like Sinatra's, is exact: no effort is made to
	// normalize trailing slashes.
	goji.Get("/admin", http.RedirectHandler("/admin/", 301))

	// Use a custom 404 handler
	goji.NotFound(NotFound)

	// Sometimes requests take a long time.
	goji.Get("/waitforit", WaitForIt)

	// Call Serve() at the bottom of your main() function, and it'll take
	// care of everything else for you, including binding to a socket (with
	// automatic support for systemd and Einhorn) and supporting graceful
	// shutdown on SIGINT. Serve() is appropriate for both development and
	// production.
	goji.Serve()
}
742165
function Run(path, options, callback) {
    var p = Spawn(path, options.args),
        err = "",
        data = "";

    if (options.remove !== false) {
        Fs.unlink(path, () => {});
    }

    if (options.stdin) {
        options.stdin.pipe(p.stdin);
    }

    if (options.stdout) {
        p.stdout.pipe(options.stdout);
    } else {
        p.stdout.on("data", function (chunk) {
            data += chunk.toString();
        });
    }

    if (options.stderr) {
        p.stderr.pipe(options.stderr);
    } else {
        p.stderr.on("data", function (err) {
            err += err.toString();
        });
    }

    p.on("close", function () {
        callback([null, err][Number(!!err)], data.slice(0, -1));
    });
}
726233
public static void main(String args[]) {
        String deviceName = null;
        String commandName = null;
        try {
            commandName = args[0];
            deviceName = args[1];
        } catch (final Exception e) {
            if (commandName==null) {
                System.out.println("Usage :");
                System.out.println("fr.esrf.TangoApi.DeviceProxy  commandName deviceName");
                System.out.println("	- info : Display device info.");
                System.out.println("	- commandName : command name (ping, state, status, unexport...)");
                System.out.println("	- deviceName : device name to send command.");
            } else {
                System.out.println("Device name ?");
            }
            System.exit(0);
        }
        try {
            // Check if wildcard
            String[] devnames;
            DeviceProxy[] deviceProxies;
            if (!deviceName.contains("*")) {
                devnames = new String[1];
                devnames[0] = deviceName;
            } else {
                devnames = ApiUtil.get_db_obj().getDevices(deviceName);
            }

            // Create DeviceProxy Objects
            deviceProxies = new DeviceProxy[devnames.length];
            for (int i = 0 ; i<devnames.length ; i++) {
                deviceProxies[i] = new DeviceProxy(devnames[i]);
            }

//            switch (commandName) {
//                case "info":
                if (commandName.equals("info")) {
                    for (DeviceProxy deviceProxy : deviceProxies) {
                        System.out.println(deviceProxy + "\n");
                    }
//                    break;
//                case "ping":
                }
                else
                if (commandName.equals("ping")) {
                    // noinspection InfiniteLoopStatement
                    while (true) {
                        for (int i = 0; i < deviceProxies.length; i++) {
                            try {
                                final long t = deviceProxies[i].ping();
                                System.out.println(devnames[i] + " is alive  (" + t / 1000 + " ms)");
                            } catch (final DevFailed e) {
                                System.out.println(devnames[i] + "  " + e.errors[0].desc);
                            }
                        }
                        if (deviceProxies.length > 1) {
                            System.out.println();
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (final InterruptedException e) { /* */ }
                    }
//                    break;
//                case "status":
                }
                else
                if (commandName.equals("status")) {
                    for (int i = 0; i < deviceProxies.length; i++) {
                        try {
                            System.out.println(devnames[i] + " - " + deviceProxies[i].status());
                        } catch (final DevFailed e) {
                            System.out.println(devnames[i] + "  " + e.errors[0].desc);
                        }
                    }
//                    break;
//                case "state":
                }
                else
                if (commandName.equals("state")) {
                    for (int i = 0; i < deviceProxies.length; i++) {
                        try {
                            System.out
                                    .println(devnames[i] + " is " + ApiUtil.stateName(deviceProxies[i].state()));
                        /*
                        * DeviceAttribute da = dev[i].read_attribute("State");
                        * DevState st = da.extractDevStateArray()[0];
                        * System.out.println(devnames[i] + " is " +
                        * ApiUtil.stateName(st));
                        */
                        } catch (final DevFailed e) {
                            System.out.println(devnames[i] + "  " + e.errors[0].desc);
                        }
                    }
//                    break;
//                case "":
                }
                else
                if (commandName.equals("unexport")) {
                    for (int i = 0; i < deviceProxies.length; i++) {
                        try {
                            deviceProxies[i].unexport_device();
                            System.out.println(devnames[i] + " unexported !");
                        } catch (final DevFailed e) {
                            System.out.println(devnames[i] + "  " + e.errors[0].desc);
                        }
                    }
//                    break;
//                default:
                }
                else
                    System.out.println(commandName + " ?   Unknow command !");
//                    break;
//            }
        } catch (final DevFailed e) {
            Except.print_exception(e);
            // e.printStackTrace();
        }
    }
1320495
public function run()
    {
        $request = $this->request;
        $response = $this->response;
        $config = $this->configuration;

        $httpMethod = $request->getMethod();
        $pathInfo = $request->getUri()->getPath();
        if (empty($pathInfo)) {
            $pathInfo = '/';
        }

        $routeObject = $this->router->resolve($pathInfo, $httpMethod);
        if($routeObject) {
            $middlewareList = [];
            if (isset($routeObject['middleware'])) {
                $middlewareConfig = $config->get('middlewares');
                $middlewareCount = count($routeObject['middleware']);
                $middlewareNext = null;
                $middlewareFactory = $this->container->get(MiddlewareFactory::class);

                for ($i=$middlewareCount-1; $i >= 0; $i--) {
                    $middlewareName = $routeObject['middleware'][$i];
                    $middlewareClass = $middlewareConfig[$middlewareName];
                    $middlewareList[$i] = $middlewareFactory->createObject($middlewareClass, [
                        'response' => $response,
                        'next' => $middlewareNext,
                    ]);
                    $middlewareNext = $middlewareList[$i];
                }
            }

            $baseNamespace = $config->get('controllersNamespace');
            $handler = $this->convertCallbackToClosure($routeObject['handler'], $baseNamespace);
            $params = isset($routeObject['params']) ? $routeObject['params'] : [];
            $requestHandler = new ServerRequestHandler($response, $handler, $routeObject['params']);

            if (isset($middlewareList[0])) {
                $response = $middlewareList[0]->process($request, $requestHandler);
            } else {
                $response = $requestHandler->handle($request);
            }

        } else {
            throw new HttpException(404, "Route '{$pathInfo}' not found");
        }

        $this->emitResponse($response);
    }