Setup AppEngine SDK on CircleCI
193375
def setup_ci():
    # type: () -> None
    
    gcloud_path = shell.run('which gcloud', capture=True).stdout.strip()
    sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine'))
    gcloud_cmd = gcloud_path + ' --quiet'

    if not exists(sdk_path):
        log.info("Installing AppEngine SDK")
        shell.run('sudo {} components install app-engine-python'.format(
            gcloud_cmd
        ))
    else:
        # Only initialise once. To reinitialise, just build without cache.
        log.info("AppEngine SDK already initialised")

    log.info("Using service account authentication")
    shell.run('{} auth activate-service-account --key-file {}'.format(
        gcloud_cmd,
        conf.proj_path('ops/client_secret.json')
    ))
75596
def setup_ui(self, ):
        
        plus_icon = get_icon('glyphicons_433_plus_bright.png', asicon=True)
        self.add_tb.setIcon(plus_icon)

        self.shot_browser = ListBrowser(4, parent=self, headers=["Project", "Sequence", "Shot", "Type"])
        self.asset_browser = ListBrowser(4, parent=self, headers=["Project", "Assettype", "Asset", "Type"])

        self.shotmodel = self.create_shot_model()
        self.assetmodel = self.create_asset_model()

        self.shot_browser.set_model(self.shotmodel)
        self.asset_browser.set_model(self.assetmodel)

        self.shot_vbox.addWidget(self.shot_browser)
        self.asset_vbox.addWidget(self.asset_browser)
623746
function setup(global) {
  'use strict';

  if (process.env.NODE_ENV === 'production') {
    return;
  }

  if (!process.env.__REACT_DEVTOOLS_PORT__) {
    return;
  }

  const reactDevTools = require('react-devtools-core');
  try {
    reactDevTools.connectToDevTools({
      host: process.env.__REACT_DEVTOOLS_HOST__ || 'localhost',
      port: process.env.__REACT_DEVTOOLS_PORT__,
    });
  } catch (e) {
    console.error('Cannot connect to React DevTools')
  }
}
1296552
def setup_app(self, app, add_context_processor=True):  # pragma: no cover
        '''
        
        '''
        warnings.warn('Warning setup_app is deprecated. Please use init_app.',
                      DeprecationWarning)
        self.init_app(app, add_context_processor)
151492
function setEngine(theEngine) {
	engine = theEngine
	store = engine.getStore()
	pubsub = engine.getPubSub()
}
1153083
def setup(app):
    

    app.add_directive('readthedocs-embed', EmbedDirective)
    app.add_config_value('readthedocs_embed_project', '', 'html')
    app.add_config_value('readthedocs_embed_version', '', 'html')
    app.add_config_value('readthedocs_embed_doc', '', 'html')

    return app
1333588
def setup(self, app):
        """"""
        super().setup(app)

        self.enabled = len(self.cfg.backends)

        self.default = self.cfg.default
        if not self.default and self.enabled:
            self.default = self.cfg.backends[0][0]

        self.backends_hash = {name: parse.urlparse(loc) for (name, loc) in self.cfg.backends}
        if self.default and self.default not in self.backends_hash:
            raise PluginException('Backend not found: %s' % self.default)
442238
function setupResourceServer(app, options, models) {

    function checkAccessToken(req, accessToken, done) {
        debug('Verifying access token %s', accessToken);
        models.AccessTokens.find(accessToken, function (err, token) {
            if (err || !token) {
                return done(err);
            }

            debug('Access token found: %j', token);

            if (isExpired(token)) {
                return done(new TokenError('Access token is expired',
                    'invalid_grant'));
            }

            var userId = token.userId || token.resourceOwner;
            var appId = token.appId || token.clientId;

            var user, app;
            async.parallel([
                function lookupUser(done) {
                    if (userId == null) {
                        return process.nextTick(done);
                    }
                    models.Users.find(userId, function (err, u) {
                        if (err) {
                            return done(err);
                        }
                        if (!u) {
                            return done(
                                new TokenError('Access token has invalid user id: ' +
                                    userId, 'invalid_grant'));
                        }
                        debug('User found: %s', userInfo(u));
                        user = u;
                        done();
                    });
                },
                function lookupApp(done) {
                    if (appId == null) {
                        return process.nextTick(done);
                    }
                    models.Clients.find(appId, function (err, a) {
                        if (err) {
                            return done(err);
                        }
                        if (!a) {
                            return done(
                                new TokenError('Access token has invalid app id: ' + appId,
                                    'invalid_grant'));
                        }
                        debug('Client found: %s', clientInfo(a));
                        app = a;
                        done();
                    });
                }], function (err) {
                if (err) {
                    return done(err);
                }
                if (options.addHttpHeaders) {
                    var prefix = 'X-OAUTH2-';
                    if (typeof options.addHttpHeaders === 'string') {
                        prefix = options.addHttpHeaders;
                    }
                    if (appId != null) {
                        req.headers[prefix + 'CLIENT-ID'] = appId;
                    }
                    if (userId != null) {
                        req.headers[prefix + 'USER-ID'] = userId;
                    }
                }
                var authInfo =
                {accessToken: token, user: user, app: app, client: app};
                done(null, user || {}, authInfo);
            });
        });
    }

    var verifyAccessToken = checkAccessToken;
    if (typeof options.checkAccessToken === 'function') {
        verifyAccessToken = options.checkAccessToken;
    }

    function accessTokenValidator(req, accessToken, done) {
        verifyAccessToken(req, accessToken, function (err, user, info) {
            if (!err && info) {
                req.accessToken = info.accessToken;
            }
            done(err, user, info);
        });
    }

    /**
     * BearerStrategy
     *
     * This strategy is used to authenticate users based on an access token (aka a
     * bearer token).  The user must have previously authorized a client
     * application, which is issued an access token to make requests on behalf of
     * the authorizing user.
     */
    passport.use('copress-oauth2-bearer',
        new BearerStrategy({passReqToCallback: true}, accessTokenValidator)
    );

    passport.use('copress-oauth2-mac',
        new MacStrategy({passReqToCallback: true, jwtAlgorithm: 'HS256'},
            function (req, accessToken, done) {
                accessTokenValidator(req, accessToken, function (err, user, info) {
                    if (err || !user) {
                        return done(err, user, info);
                    }
                    var client = info && info.client;
                    var secret = client.clientSecret || client.restApiKey;
                    try {
                        var token = jwt.verify(accessToken, 'HS256', secret);
                        debug('JWT token verified: %j', token);
                    } catch (err) {
                        debug('Fail to verify JWT: %j', err);
                        done(err);
                    }
                    done(null, user, info);
                });
            })
    );

    /**
     * Return the middleware chain to enforce oAuth 2.0 authentication and
     * authorization
     * @param {Object} [options] Options object
     * - scope
     * - jwt
     */
    function authenticate(options) {
        options = options || {};

        var authenticators = [
            passport.authenticate(['copress-oauth2-bearer', 'copress-oauth2-mac'],
                options)];
        if (options.scopes || options.scope) {
            authenticators.push(scopeValidator(options));
        }
        authenticators.push(oauth2Provider.errorHandler());
        return authenticators;
    }

    return authenticate;
}
1030166
def _fix_path():
  """"""
  import os
  import sys
  all_paths = os.environ.get('PYTHONPATH').split(os.pathsep)
  for path_dir in all_paths:
    dev_appserver_path = os.path.join(path_dir, 'dev_appserver.py')
    if os.path.exists(dev_appserver_path):
      logging.debug('Found appengine SDK on path!')
      google_appengine = os.path.dirname(os.path.realpath(dev_appserver_path))
      sys.path.append(google_appengine)
      # Use the next import will fix up sys.path even further to bring in
      # any dependent lib directories that the SDK needs.
      dev_appserver = __import__('dev_appserver')
      sys.path.extend(dev_appserver.EXTRA_PATHS)
      return
786163
def sandbox(verbose, app):
    """"""
    # Load psiTurk configuration.
    config = PsiturkConfig()
    config.load_config()

    # Set the mode.
    config.set("Experiment Configuration", "mode", "sandbox")
    config.set("Server Parameters", "logfile", "-")

    # Ensure that psiTurk is in sandbox mode.
    config.set("Shell Parameters", "launch_in_sandbox_mode", "true")

    # Do shared setup.
    deploy_sandbox_shared_setup(verbose=verbose, app=app)
1013823
function sdkReady(type, callback) {
        callback = callback || function () {};
        if (!Embedo.defaults.SOURCES[type]) {
          return callback(new Error('unsupported_sdk_type'));
        }
        var counter = 0;
        (function check() {
          counter++;
          if (counter > 15) {
            return callback(new Error(type + ':sdk_not_available'));
          }
          if (window[Embedo.defaults.SOURCES[type].GLOBAL]) {
            return callback(null, window[Embedo.defaults.SOURCES[type].GLOBAL]);
          }
          setTimeout(check, 10 * counter);
        })(type);
      }
360996
function setup(context) {
  if (GLOBAL.config) {
    console.log('already configured');
    console.trace();
    return;
  }
  if (!context) {
    context = require('./config.js');
  }

  GLOBAL.config = context.config;

  var svc = { pubsub: pubsub, auth: auth, indexer: indexer, pageCache: pageCache };

  GLOBAL.svc = svc;
  auth.setupUsers(GLOBAL, context.logins);
}
115039
def run(options):
    
    from google.appengine.tools import appengine_rpc
    from google.appengine.tools import appcfg

    source = 'furious'

    # use the same user agent that GAE uses in appcfg
    user_agent = appcfg.GetUserAgent()

    # Since we're only using the dev server for now we can hard code these
    # values. This will need to change and accept these values as variables
    # when this is wired up to hit appspots.
    server = appengine_rpc.HttpRpcServer(
        'localhost:8080', lambda: ('test@example.com', 'password'), user_agent,
        source, secure=False)

    # if no url is passed in just use the top level.
    url = "/"
    if options.url:
        url += options.url[0]

    # use the dev server authentication for now.
    server._DevAppServerAuthenticate()

    # send a simple GET request to the url
    server.Send(url, content_type="text/html; charset=utf-8",
                payload=None)
280776
def setup_example():
    '''  '''
    parser = argparse.ArgumentParser(
        description='Creates a simple default project (stroop) in the current\
        directory with the necessary psiTurk files.'
    )

    # Optional flags
    parser.add_argument(
        '-v', '--version', help='Print version number.', action="store_true"
    )
    args = parser.parse_args()

    # If requested version just print and quite
    if args.version:
        print version_number
    else:
        import psiturk.setup_example as se
        se.setup_example()
345280
def setup(self, app):
        
        super().setup(app)

        if isinstance(self.cfg.template_folders, str):
            self.cfg.template_folders = [self.cfg.template_folders]

        else:
            self.cfg.template_folders = list(self.cfg.template_folders)

        self.ctx_provider(lambda: {'app': self.app})
        self.env = Environment(debug=app.cfg.DEBUG, **self.cfg)
205722
public void run(List<String> args)
      throws ProcessHandlerException, AppEngineJavaComponentsNotInstalledException,
          InvalidJavaSdkException, IOException {
    sdk.validateAppEngineJavaComponents();
    sdk.validateJdk();

    // App Engine Java Sdk requires this system property to be set.
    // TODO: perhaps we should send this in directly to the command instead of changing the global
    // state here (see DevAppServerRunner)
    System.setProperty("appengine.sdk.root", sdk.getAppEngineSdkForJavaPath().toString());

    List<String> command = new ArrayList<>();
    command.add(sdk.getJavaExecutablePath().toString());
    command.add("-cp");
    command.add(sdk.getAppEngineToolsJar().toString());
    command.add("com.google.appengine.tools.admin.AppCfg");
    command.addAll(args);

    logger.info("submitting command: " + Joiner.on(" ").join(command));

    ProcessBuilder processBuilder = processBuilderFactory.newProcessBuilder();
    processBuilder.command(command);
    Process process = processBuilder.start();
    processHandler.handleProcess(process);
  }
723952
def setup(app):
    '''  '''
    app.add_autodocumenter(ColorDocumenter)
    app.add_autodocumenter(EnumDocumenter)
    app.add_autodocumenter(PropDocumenter)
    app.add_autodocumenter(ModelDocumenter)