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

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

    # Fetch profile for rider
    profile = client.get_rider_profile().json

    # Fetch all trips from history endpoint
    trips = []
    i = 0
    while True:
        try:
            response = client.get_rider_trips(
                limit=50,
                offset=i)
            i += 50
            if len(response.json['history']) > 0:
                trips += response.json['history']
            else:
                break
        except:
            break
            pass

    # Compute trip stats for # of rides and distance
    total_rides = 0
    total_distance_traveled = 0

    # Compute ranked list of # trips per city
    cities = list()
    for ride in trips:
        cities.append(ride['start_city']['display_name'])

        # only parse actually completed trips
        if ride['distance'] > 0:
            total_rides += 1
            total_distance_traveled += int(ride['distance'])

    total_cities = 0
    locations_counter = Counter(cities)
    locations = OrderedDict()
    cities_by_frequency = sorted(cities, key=lambda x: -locations_counter[x])
    for city in list(cities_by_frequency):
        if city not in locations:
            total_cities += 1
            locations[city] = cities.count(city)

    return render_template('rider_dashboard.html',
                           profile=profile,
                           trips=trips,
                           locations=locations,
                           total_rides=total_rides,
                           total_cities=total_cities,
                           total_distance_traveled=total_distance_traveled
                           )
739097
def process_request(self, method, data=None):
        
        # make sure requested method is valid
        self._validate_request_method(method)

        # attempt the request multiple times
        attempts = 3
        for i in range(attempts):
            response = self._send_request(method, data)

            # handle case where ubersmith is 'updating token'
            # see: https://github.com/jasonkeene/python-ubersmith/issues/1
            if self._is_token_response(response):
                if i < attempts - 1:
                    # wait 2 secs before retrying request
                    time.sleep(2)
                    continue
                else:
                    raise UpdatingTokenResponse
            break

        resp = BaseResponse(response)

        # test for error in json response
        if response.headers.get('content-type') == 'application/json':
            if not resp.json.get('status'):
                if all([
                    resp.json.get('error_code') == 1,
                    resp.json.get('error_message') == u"We are currently "
                        "undergoing maintenance, please check back shortly.",
                ]):
                    raise MaintenanceResponse(response=resp.json)
                else:
                    raise ResponseError(response=resp.json)
        return resp
711721
def query(conn_type, option, post_data=None):
    '''
    
    '''
    if ticket is None or csrf is None or url is None:
        log.debug('Not authenticated yet, doing that now..')
        _authenticate()

    full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)

    log.debug('%s: %s (%s)', conn_type, full_url, post_data)

    httpheaders = {'Accept': 'application/json',
                   'Content-Type': 'application/x-www-form-urlencoded',
                   'User-Agent': 'salt-cloud-proxmox'}

    if conn_type == 'post':
        httpheaders['CSRFPreventionToken'] = csrf
        response = requests.post(full_url, verify=verify_ssl,
                                 data=post_data,
                                 cookies=ticket,
                                 headers=httpheaders)
    elif conn_type == 'put':
        httpheaders['CSRFPreventionToken'] = csrf
        response = requests.put(full_url, verify=verify_ssl,
                                data=post_data,
                                cookies=ticket,
                                headers=httpheaders)
    elif conn_type == 'delete':
        httpheaders['CSRFPreventionToken'] = csrf
        response = requests.delete(full_url, verify=verify_ssl,
                                   data=post_data,
                                   cookies=ticket,
                                   headers=httpheaders)
    elif conn_type == 'get':
        response = requests.get(full_url, verify=verify_ssl,
                                cookies=ticket)

    response.raise_for_status()

    try:
        returned_data = response.json()
        if 'data' not in returned_data:
            raise SaltCloudExecutionFailure
        return returned_data['data']
    except Exception:
        log.error('Error in trying to process JSON')
        log.error(response)
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;
    }
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);
    }
}
1368697
def post(self, client_method, data, post_params=None, is_json=True):
        """"""
        url = self._wa.apollo_url + self.CLIENT_BASE + client_method

        if post_params is None:
            post_params = {}

        headers = {
            'Content-Type': 'application/json'
        }

        data.update({
            'username': self._wa.username,
            'password': self._wa.password,
        })

        curl_command = ['curl', url]
        for (k, v) in headers.items():
            curl_command += ['-H', quote('%s: %s' % (k, v))]
        curl_command += ['-d', quote(json.dumps(data))]
        log.info(' '.join(curl_command))

        resp = requests.post(url, data=json.dumps(data),
                             headers=headers, verify=self.__verify,
                             params=post_params, allow_redirects=False,
                             **self._request_args)

        if resp.status_code == 200 or resp.status_code == 302:
            if is_json:
                data = resp.json()
                return self._scrub_data(data)
            else:
                return resp.text

        # @see self.body for HTTP response body
        raise Exception("Unexpected response from apollo %s: %s" %
                        (resp.status_code, resp.text))
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")
595606
def connect(token, protocol=RtmProtocol, factory=WebSocketClientFactory, factory_kwargs=None, api_url=None, debug=False):
	
	if factory_kwargs is None:
		factory_kwargs = dict()

	metadata = request_session(token, api_url)
	wsfactory = factory(metadata.url, **factory_kwargs)
	if debug:
		warnings.warn('debug=True has been deprecated in autobahn 0.14.0')

	wsfactory.protocol = lambda *a,**k: protocol(*a,**k)._seedMetadata(metadata)
	connection = connectWS(wsfactory)
	return connection
207028
def _query(method='GET', profile=None, url=None, path='api/v1',
           action=None, api_key=None, service=None, params=None,
           data=None, subdomain=None, verify_ssl=True):
    '''
    

    '''

    if profile:
        creds = __salt__['config.option'](profile)
    else:
        creds = {
            'pagerduty.api_key': api_key,
            'pagerduty.subdomain': subdomain,
        }

    if url is None:
        url = 'https://{0}.pagerduty.com/{1}/{2}'.format(
            creds['pagerduty.subdomain'],
            path,
            action
        )

    if params is None:
        params = {}

    if data is None:
        data = {}

    headers = {
        'Authorization': 'Token token={0}'.format(creds['pagerduty.api_key'])
    }

    if method != 'GET':
        headers['Content-type'] = 'application/json'

    result = requests.request(
        method,
        url,
        headers=headers,
        params=params,
        data=salt.utils.json.dumps(data),
        verify=verify_ssl
    )

    if result.text is None or result.text == '':
        return None
    result_json = result.json()
    # if this query supports pagination, loop and fetch all results, merge them together
    if 'total' in result_json and 'offset' in result_json and 'limit' in result_json:
        offset = result_json['offset']
        limit = result_json['limit']
        total = result_json['total']
        while offset + limit < total:
            offset = offset + limit
            limit = 100
            data['offset'] = offset
            data['limit'] = limit
            next_page_results = requests.request(method,
                                                 url,
                                                 headers=headers,
                                                 params=params,
                                                 data=data,  # Already serialized above, don't do it again
                                                 verify=verify_ssl).json()
            offset = next_page_results['offset']
            limit = next_page_results['limit']
            # merge results
            for k, v in result_json.items():
                if isinstance(v, list):
                    result_json[k] += next_page_results[k]
    return result_json
875080
def _connect(self):
        
        oauth_client = BackendApplicationClient(client_id=self.client_id)
        oauth_session = OAuth2Session(client=oauth_client)
        token = oauth_session.fetch_token(token_url=self.url + "oauth/token",
                                            client_id=self.client_id,
                                            client_secret=self.client_secret)
                                            #verify=False)
        return OAuth2Session(client_id=self.client_id,
                                    token=token)
1344090
def setup_client(token)
      client = Octokit::Client.new(access_token: token)
      client.auto_paginate = true
      client
    end
348373
function connect() {
    return new Promise(function (resolve, reject) {
        navigator.requestMIDIAccess().then(function (access) {
            resolve(new Driver(access));
        }).catch(function () {
            reject(new Error('MIDI access denied'));
        });
    });
}
1159692
function (callback) {
    var APIController = require('./controllers/api'),
      DefaultController = require('./controllers/index'),
      PackController = require('./controllers/pack'),
      CardController = require('./controllers/card'),
      WebHookController = require('./controllers/webhook'),
      ProxyController = require('./controllers/proxy'),
      JsonParser = BodyParser.json({strict: false});
    
    // Disable caching middleware.  
    var nocache = function (req, res, next) {
      res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
      res.header('Expires', '-1');
      res.header('Pragma', 'no-cache');
      next();
    };
    
    // Setup routes late to give implementers routes higher priority and allow middleware as well.
    App.get('/api/count', nocache, APIController.count);
    App.get('/api/cards', nocache, APIController.cards);
    App.get('/api/card', nocache, APIController.card);
    
    App.post('/api/card/state/save', APIController.saveState);
    App.post('/api/card/state/clear', APIController.clearState);
    App.post('/api/card/analytics', APIController.recordAnalyticEvents);

    // Proxy
    App.post('/proxy/:pack/:card', ProxyController.post);

    // Web Hooks
    App.post('/webhook/:pack/:card', WebHookController.process);

    // Card Routes
    App.post('/:pack/:card', JsonParser, CardController.post);
    App.get('/:pack/:card', CardController.get);
    
    App.get('/:pack', PackController);
    App.get('/', DefaultController);

    var exit = function () {
      HashDo.db.disconnect(function () {
        process.exit(0);
      });
    };
    
    // Gracefully disconnect from the database on expected exit.
    process.on('SIGINT', exit);
    process.on('SIGTERM', exit);
    
    // Global error handler (always exit for programmatic errors).
    process.on('uncaughtException', function (err) {
      console.error('FATAL: ', err.message);
      console.error(err.stack);
      process.exit(1);
    });
    
    // Connect to the database and start server on successful connection.
    HashDo.db.connect(function (err) {
      if (err) {
        console.error('FATAL: Could not connect to database.', err);
        process.exit(1);
      }
      else {
        console.log('WEB: Starting web server on port %d...', process.env.PORT);
        
        App.listen(process.env.PORT, function () {
          console.log();
          console.log('Let\'s #Do');
          
          callback && callback();
        });
      }
    });
  }
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
1057512
def ConnectHandler(*args, **kwargs):
    """"""
    if kwargs["device_type"] not in platforms:
        raise ValueError(
            "Unsupported device_type: "
            "currently supported platforms are: {}".format(platforms_str)
        )
    ConnectionClass = ssh_dispatcher(kwargs["device_type"])
    return ConnectionClass(*args, **kwargs)
1262862
def dispatch_action(req)
      controller = ROUTE_TO_CONTROLLER[req.path_info]
      fail Heartcheck::Errors::RoutingError if controller.nil?

      Logger.info "Start [#{controller}] from #{req.ip} at #{Time.now}"

      controller.new.index.tap do |_|
        Logger.info "End [#{controller}]\n"
      end
    end
996168
def exec_request(endpoint, func, raise_for_status=False, **kwargs):
        
        try:
            endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint)
            headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'}
            logger.debug(headers)
            logger.debug(endpoint)
            ret = getattr(requests, func)(endpoint, headers=headers, data=kwargs)
            ret.raise_for_status()
            return ret.json()
        except requests.HTTPError as e:
            if raise_for_status:
                raise e
            logger.exception("Error encountered while performing API request to SeAT with url {}".format(endpoint))
            return {}