Helper function that creates a plnt app.
181932
def make_app():
    """"""
    from plnt import Plnt

    database_uri = os.environ.get("PLNT_DATABASE_URI")
    app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
    app.bind_to_context()
    return app
1284684
def item(ctx, appid, title):
    """"""
    ctx.obj['appid'] = appid
    ctx.obj['title'] = title
1370882
function create() {
  function app(msg) { app.handle(msg); }
  utils.merge(app, proto);
  app.init();
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }
  return app;
}
1018893
function createPiGlow(callback) {
    var myPiGlow = new PiGlowBackend();
    var myInterface = piGlowInterface(myPiGlow);

    myPiGlow
        .on('initialize', function() {
            callback(null, myInterface);
        })
        .on('error', function(error) {
            callback(error, null);
        });
}
1258388
def GeneratePipPackage(args):

    """"""

    discovery_doc = _GetDiscoveryDocFromFlags(args)
    package = discovery_doc['name']
    original_outdir = os.path.expanduser(args.outdir)
    args.outdir = os.path.join(
        args.outdir, 'apitools/clients/%s' % package)
    args.root_package = 'apitools.clients.%s' % package
    codegen = _GetCodegenFromFlags(args)
    if codegen is None:
        logging.error('Failed to create codegen, exiting.')
        return 1
    _WriteGeneratedFiles(args, codegen)
    _WriteInit(codegen)
    with util.Chdir(original_outdir):
        _WriteSetupPy(codegen)
        with util.Chdir('apitools'):
            _WriteIntermediateInit(codegen)
            with util.Chdir('clients'):
                _WriteIntermediateInit(codegen)
1302261
def decorate(self, app):
		
		from functools import wraps

		@wraps(app)
		def decorated(environ, start_response):
			# capture any start_response from the app
			app_response = {}
			app_response['status'] = "200 OK"
			app_response['headers'] = []
			app_response['written'] = BytesIO()
			def custom_start_response(status, headers, *args, **kwargs):
				app_response['status'] = status
				app_response['headers'] = headers
				app_response['args'] = args
				app_response['kwargs'] = kwargs
				return app_response['written'].write
			returned = app(environ, custom_start_response)

			# callbacks from the serialization
			def set_http_code(status):
				app_response['status'] = str(status)
			def set_header(header, value):
				app_response['headers'] = [(h,v) for (h,v) in app_response['headers'] if h.lower() != header.lower()]
				app_response['headers'].append((header, value))
			def set_content_type(content_type):
				set_header('Content-Type', content_type)

			# do the serialization
			accept = environ.get('HTTP_ACCEPT', '')
			new_return = self.output(returned, accept, set_http_code, set_content_type)

			# set the Vary header
			vary_headers = (v for (h,v) in app_response['headers'] if h.lower() == 'vary')
			vary_elements = list(itertools.chain(*[v.split(',') for v in vary_headers]))
			vary_elements = list(set([v.strip() for v in vary_elements]))
			if '*' not in vary_elements and 'accept' not in (v.lower() for v in vary_elements):
				vary_elements.append('Accept')
				set_header('Vary', ', '.join(vary_elements))

			# pass on the result to the parent WSGI server
			parent_writer = start_response(app_response['status'],
			                               app_response['headers'],
			                               *app_response.get('args', []),
			                               **app_response.get('kwargs', {}))
			written = app_response['written'].getvalue()
			if len(written) > 0:
				parent_writer(written)
			return new_return
		return decorated
1081736
def create_app(app_id, app_name, source_id, region, app_data):
    
    try:
        create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        conn = get_conn()
        c = conn.cursor()

        #check old app
        c.execute("SELECT count(*) FROM app WHERE name='{0}' ".format(app_name))
        old_app = c.fetchone()
        if old_app[0] > 0:
            print 'app name (%s) already existed, clear old app and container info ...' % app_name
            c.execute("DELETE FROM container WHERE app_id='{0}'".format(app_id))
            c.execute("DELETE FROM app WHERE name='{0}'".format(app_name))
            conn.commit()

        #insert new app
        c.execute("INSERT INTO app (id,name,source_id,region,state,create_at,change_at,app_data) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')"
            .format(app_id, app_name, source_id, region, constant.STATE_APP_RUNNING, create_at, create_at, app_data))
        conn.commit()
        conn.close()
        print 'create app %s succeed!' % app_id
    except Exception, e:
        raise RuntimeError('create app %s failed! %s' % (app_id,e))
381576
def init_app(self, app):
        """"""
        app.add_url_rule(self.request_token_url, view_func=self.request_token,
                         methods=[u'POST'])
        app.add_url_rule(self.access_token_url, view_func=self.access_token,
                         methods=[u'POST'])
        app.add_url_rule(self.register_url, view_func=self.register,
                         methods=[u'GET', u'POST'])
        app.add_url_rule(self.authorize_url, view_func=self.authorize,
                         methods=[u'GET', u'POST'])
391610
def create_cli(create_app=None):
    
    def create_cli_app(info):
        """Application factory for CLI app.

        Internal function for creating the CLI. When invoked via
        ``inveniomanage`` FLASK_APP must be set.
        """
        if create_app is None:
            # Fallback to normal Flask behavior
            info.create_app = None
            app = info.load_app()
        else:
            app = create_app(debug=get_debug_flag())
        return app

    @click.group(cls=FlaskGroup, create_app=create_cli_app)
    def cli(**params):
        """Command Line Interface for Invenio."""
        pass

    return cli
466099
def init():
    """"""
    global app
    if app: return app
    conf.init(), db.init(conf.DbPath, conf.DbStatements)

    bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath)
    app = bottle.default_app()
    bottle.BaseTemplate.defaults.update(get_url=app.get_url)
    return app
994651
function buildApp(src, dest, options, callback) {
  const appArgs = selectAppArgs(options);
  copy(src, dest, (error) => {
    if (error) {
      callback(`Error Copying temporary directory: ${error}`);
      return;
    }

    fs.writeFileSync(
      path.join(dest, '/nativefier.json'),
      JSON.stringify(appArgs),
    );

    maybeCopyScripts(options.inject, dest)
      .catch((err) => {
        log.warn(err);
      })
      .then(() => {
        changeAppPackageJsonName(dest, appArgs.name, appArgs.targetUrl);
        callback();
      });
  });
}
1064275
def create(plot_data, header, ploti, sample_config, out_file_base, outtype="png",
           title=None, size=None):
    
    if mpl is None or plt is None or sns is None:
        not_found = ", ".join([x for x in ['mpl', 'plt', 'sns'] if eval(x) is None])
        logger.info("No validation plot. Missing imports: %s" % not_found)
        return None
    mpl.use('Agg', force=True)

    if header:
        df = pd.DataFrame(plot_data, columns=header)
    else:
        df = plot_data
    df["aligner"] = [get_aligner(x, sample_config) for x in df["sample"]]
    df["bamprep"] = [get_bamprep(x, sample_config) for x in df["sample"]]
    floors = get_group_floors(df, cat_labels)
    df["value.floor"] = [get_floor_value(x, cat, vartype, floors)
                         for (x, cat, vartype) in zip(df["value"], df["category"], df["variant.type"])]
    out = []
    for i, prep in enumerate(df["bamprep"].unique()):
        out.append(plot_prep_methods(df, prep, i + ploti, out_file_base, outtype, title, size))
    return out
355632
def show(*args, **kwargs):
    
    """
    _, plt, _ = _import_plt()
    plt.show(*args, **kwargs)
437565
def generate(num, prompt_default=True):
    """"""
    p = Problem(num)

    problem_text = p.text

    msg = "Generate file for problem %i?" % num
    click.confirm(msg, default=prompt_default, abort=True)

    # Allow skipped problem files to be recreated
    if p.glob:
        filename = str(p.file)
        msg = '"{}" already exists. Overwrite?'.format(filename)
        click.confirm(click.style(msg, fg='red'), abort=True)
    else:
        # Try to keep prefix consistent with existing files
        previous_file = Problem(num - 1).file
        prefix = previous_file.prefix if previous_file else ''
        filename = p.filename(prefix=prefix)

    header = 'Project Euler Problem %i' % num
    divider = '=' * len(header)
    text = '\n'.join([header, divider, '', problem_text])
    content = '\n'.join(['"""', text, '"""'])

    with open(filename, 'w') as f:
        f.write(content + '\n\n\n')

    click.secho('Successfully created "{}".'.format(filename), fg='green')

    # Copy over problem resources if required
    if p.resources:
        p.copy_resources()
502039
def generate(self):
        """"""
        for root, _, files in os.walk(self.source_dir):
            for fname in files:
                source_fpath = os.path.join(root, fname)
                self.generate_api_for_source(source_fpath)
1109061
def generate_doxygen(app):
    """"""
    _run_cmd("cd %s/.. && make doxygen" % app.builder.srcdir)
    _run_cmd("cp -rf doxygen/html %s/doxygen" % app.builder.outdir)
778699
def custom_build(inputs, is_training, keep_prob):
  """"""
  outputs = snt.Conv2D(output_channels=32, kernel_shape=4, stride=2)(inputs)
  outputs = snt.BatchNorm()(outputs, is_training=is_training)
  outputs = tf.nn.relu(outputs)
  outputs = snt.Conv2D(output_channels=64, kernel_shape=4, stride=2)(outputs)
  outputs = snt.BatchNorm()(outputs, is_training=is_training)
  outputs = tf.nn.relu(outputs)
  outputs = snt.BatchFlatten()(outputs)
  outputs = tf.nn.dropout(outputs, keep_prob=keep_prob)
  outputs = snt.Linear(output_size=10)(outputs)
  return outputs