Connect controller to handle token exchange and query Uber API.
969087
def connect():
    """"""

    # Exchange authorization code for acceess token and create session
    session = auth_flow.get_session(request.url)
    client = UberRidesClient(session)

    # Fetch profile for driver
    profile = client.get_driver_profile().json

    # Fetch last 50 trips and payments for driver
    trips = client.get_driver_trips(0, 50).json
    payments = client.get_driver_payments(0, 50).json

    return render_template('driver_dashboard.html',
                           profile=profile,
                           trips=trips['trips'],
                           payments=payments['payments']
                           )
698669
async def api(self, endpoint, params=None, test=False):
        """"""
        data = {}
        url = "{}/{}".format(self._api, endpoint)
        try:
            async with async_timeout.timeout(8, loop=self._loop):
                response = await self._session.get(
                    url, auth=self._auth, headers=HEADERS, params=params
                )

            if response.status == 200:
                self._authenticated = True
                self._connected = True
                if not test:
                    data = await response.json()
            elif response.status == 401:
                self._authenticated = False
                self._connected = True

        except asyncio.TimeoutError as error:
            self._authenticated, self._connected = False, False
            if not test:
                _LOGGER.warning("Timeouterror connecting to Traccar, %s", error)
        except aiohttp.ClientError as error:
            self._authenticated, self._connected = False, False
            if not test:
                _LOGGER.warning("Error connecting to Traccar, %s", error)
        except socket.gaierror as error:
            self._authenticated, self._connected = False, False
            if not test:
                _LOGGER.warning("Error connecting to Traccar, %s", error)
        except TypeError as error:
            self._authenticated, self._connected = False, False
            if not test:
                _LOGGER.warning("Error connecting to Traccar, %s", error)
        except Exception as error:  # pylint: disable=broad-except
            self._authenticated, self._connected = False, False
            if not test:
                _LOGGER.warning("Error connecting to Traccar, %s", error)

        return data
1344090
def setup_client(token)
      client = Octokit::Client.new(access_token: token)
      client.auto_paginate = true
      client
    end
599488
function executeController(server, controller, req, res) {
    try {
        const promise = controller.call(server, req, res);
        if (promise && typeof promise.catch === 'function') {
            promise.catch(function(err) {
                res.status(500).send(err);
            });
        }
    } catch (err) {
        res.send(err);
    }
}
1261663
def get_request(self, request):
        """"""
        request.transport_user = self.username
        request.transport_password = self.api_key
        return request
728741
public function connect(Application $app)
    {
        $controllers = $app['controllers_factory'];

        $handler = function ($resource) use ($app) {
            if ($app['logger']) {
                $app['logger']->debug(sprintf('Appending a trailing slash for the request to `/%s`.', $resource));
            }

            $currentRequest = $app['request_stack']->getCurrentRequest();
            $request = Request::create(
                '/' . $resource . '/',
                $currentRequest->getMethod(),
                [],
                $currentRequest->cookies->all(),
                $currentRequest->files->all(),
                $currentRequest->server->all(),
                $currentRequest->getContent()
            );
            $request = $request->duplicate(
                $currentRequest->query->all(),
                $currentRequest->request->all()
            );
            $request->headers->replace($currentRequest->headers->all());

            // Make an internal sub-request based off the request that would have 404'd.
            // http://silex.sensiolabs.org/doc/usage.html#forwards
            return $app->handle($request, HttpKernelInterface::SUB_REQUEST);
        };

        /**
         * Register the catch-all route.
         *
         * Use a look behind assertion to ensure we only match routes
         * with no trailing slash.
         *
         * @link https://stackoverflow.com/questions/16398471/regex-not-ending-with
         */
        $controllers->match('/{resource}', $handler)
                    ->assert('resource', '.*(?<!\/)$')
                    ->bind('no_trailing_slash_handler');

        return $controllers;
    }
1283738
def request(self, action, data={}, headers={}, method='GET'):
        
        data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId})
        return Transport.request(self, action, data, headers, method)
1322580
function connect (conf) {
  // Instantiating API client, this is the one that will be passed to other methods
  var client = new Client();

  if (conf["my-host.token"]) {
    // Authorize client
    client.setToken(conf["my-host.token"]);
    // Check token…
    return checkToken(client)
      .then(null, function () {
        // …and create a new one if it failed
        console.error("Existing token is invalid");
        return createToken(client);
      });
  } else {
    // No token found: create new one
    return createToken(client);
  }
}
48553
def request(uri, data=nil, verb=:post)
      @logger.info(uri) if @logger
      auth_check
      query = {
        path: File.join('v1.0/me/', URI.escape(uri)),
        headers: {
          'Authorization': "Bearer #{@access_token.token}"
        }
      }
      if data
        query[:body] = JSON.generate(data)
        query[:headers]['Content-Type'] = 'application/json'
        @logger.info(query[:body]) if @logger
        verb = :post unless [:post, :put, :patch, :delete].include?(verb)
        response = @conn.send(verb, query)
      else
        response = @conn.get(query)
      end
      JSON.parse(response.body)
    end
183104
def connect(self):
        """"""
        if not self._SID:
            self._SID = self._auth.service.authenticate()
            print('Authenticated (SID: %s)' % self._SID)

        self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID})
        self._auth.options.headers.update({'Cookie': 'SID="%s"' % self._SID})
        return self._SID
1238903
def api_get(controller, action = nil, id = nil, params = {})
      uri = String.new

      if action && id
        uri = "/#{controller}/#{action}/#{id}"
      elsif action
        uri = "/#{controller}/#{action}/"
      else
        uri = "/#{controller}/"
      end

      response = self.connection.get(uri, params) do |request|
        request.headers['Content-Type'] = 'application/json'
        request.headers['Accept']       = 'application/json'
        request.headers['User-Agent']  = UserAgents[DefaultUserAgent]
      end

      case code = response.status.to_i
      when 400..499
        raise(Newegg::NeweggClientError, "error, #{code}: #{response.inspect}")
      when 500..599
        raise(Newegg::NeweggServerError, "error, #{code}: #{response.inspect}")
      else
        response
      end
    end
407545
def get(self, req, driver):
        
        response = driver.get_network(req.params, id)
        data = {
            'action': "get",
            'controller': "network",
            'id': id,
            'cloud': req.environ['calplus.cloud'],
            'response': response
        }
        return data
510511
def connect(self, ctx):

        

        if hasattr(ctx,"conn") or "host" not in ctx.params:
            return

        ctx.conn = conn = connect(ctx.params["host"])
        lnk = link.Link()
        lnk.wire("main", receive=conn, send=conn)
        ctx.client = api.Client(link=lnk)
        ctx.widget = ClientWidget(ctx.client, "engineer")
355725
function connect() {
    let port = null;

    try {
      port = parseInt(readFileSync(path.join(
        datadir,
        'control-port'
      )).toString().split(':')[1]);
    } catch (err) {
      /* istanbul ignore next */
      portFileReads++;

      /* istanbul ignore next */
      if (portFileReads <= 20) {
        return setTimeout(() => connect(), 1000);
      } else {
        return controller.emit('error',
                               new Error('Failed to read control port'));
      }
    }

    socket.connect(port, '127.0.0.1');
  }
834697
public void connect(String controller, String username, char[] password,
            String clientBindAddress) {
        doConnect(() -> {
            return CommandContextFactory.getInstance().
                    newCommandContext(new CommandContextConfiguration.Builder()
                            .setController(controller)
                    .setUsername(username)
                    .setPassword(password)
                    .setErrorOnInteract(false)
                    .setClientBindAddress(clientBindAddress)
                    .build());
        });
    }
452573
protected function exchangeToken() {
        $result = $this->requestAccessToken();
        if ($result && !empty($result['access_token'])) {
            $this->accessToken = $result['access_token'];
            $this->sessionStorage->write('access_token', $result['access_token']);
            if (!empty($result['refresh_token'])) {
                $this->refreshToken = $result['refresh_token'];
                $this->sessionStorage->write('refresh_token', $result['refresh_token']);
            }
            if (!empty($result['id_token'])) {
                $this->validateIdToken($result['id_token']);

                $this->user = $this->requestUserInfo();
                if ($this->user) {
                    $this->sessionStorage->write('user', $this->user);
                }
            }
        }
    }
647195
function (next) {

      var app = connect();

      // application/json
      app.use(bodyParser.json());

      // application/x-www-form-urlencoded
      app.use(bodyParser.urlencoded({ extended: false }));

      // url parameters
      app.use(function (req, res, next) {
        if (!req.query) {
          req.query = ~req.url.indexOf('?')
            ? qs.parse(parseUrl(req).query)
            : {};
        }

        req.params = _.merge({}, req.query, req.body);

        next();
      });

      next(null, app);
    }