Binds a Pale API implementation to a webapp2 WSGIApplication
4757
def bind_pale_to_webapp2(pale_app_module,
        webapp_wsgiapplication,
        route_prefix=None):
    """"""

    if not isinstance(webapp_wsgiapplication, webapp2.WSGIApplication):
        raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected "
                "the passed in webapp_wsgiapplication to be an instance of "
                "WSGIApplication, but it was an instance of %s instead."
                % (type(webapp_wsgiapplication), ))

    if not pale.is_pale_module(pale_app_module):
        raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected "
                "the passed in pale_app_module to be a Python module with a "
                "`_module_type` value equal to `pale.ImplementationModule`, "
                "but it found an instance of %s instead."
                % (type(pale_app_module), ))

    endpoints = pale.extract_endpoints(pale_app_module)

    for endpoint in endpoints:
        endpoint._set_response_class(RESPONSE_CLASS)
        method = endpoint._http_method
        name = endpoint._route_name

        req_handler = pale_webapp2_request_handler_generator(endpoint)

        route_uri = endpoint._uri
        if route_prefix is not None:
            route_uri = "%s%s" % (route_prefix, route_uri)

        route = webapp2.Route(
                route_uri,
                handler=req_handler,
                name=name,
                handler_method='pale_handler',
                methods=[method, "OPTIONS"])
        webapp_wsgiapplication.router.add(route)
702144
public void bindWithApplication( String externalExportPrefix, String applicationName ) {

		Set<String> bounds = this.applicationBindings.get( externalExportPrefix );
		if( bounds == null ) {
			bounds = new LinkedHashSet<> ();
			this.applicationBindings.put( externalExportPrefix, bounds );
		}

		bounds.add( applicationName );
	}
111945
def to_flasgger(self, app=None, definitions=None, paths=None):
        
        if Schema is None:
            raise RuntimeError('Please install marshmallow and apispec')

        return flasgger.utils.apispec_to_template(
            app,
            self,
            definitions=definitions,
            paths=paths
        )
1258526
def main(global_config, **settings):
    """"""
    engine = engine_from_config(settings, "sqlalchemy.")

    DBSession.configure(bind=engine)

    Base.metadata.bind = engine

    config = Configurator(settings=settings)

    config.include("pyramid_jinja2")

    config.include("pyramid_debugtoolbar")

    config.add_route("home", "/")

    config.add_route("data", "/data")

    config.add_route("data_advanced", "/data_advanced")

    config.add_route("data_yadcf", "/data_yadcf")

    config.add_route("dt_110x", "/dt_110x")

    config.add_route("dt_110x_custom_column", "/dt_110x_custom_column")

    config.add_route("dt_110x_basic_column_search",
                     "/dt_110x_basic_column_search")

    config.add_route("dt_110x_advanced_column_search",
                     "/dt_110x_advanced_column_search")

    config.add_route("dt_110x_yadcf", "/dt_110x_yadcf")

    config.scan()

    json_renderer = JSON()

    json_renderer.add_adapter(date, date_adapter)

    config.add_renderer("json_with_dates", json_renderer)

    config.add_jinja2_renderer('.html')

    return config.make_wsgi_app()
140792
public void route(HttpMethods meth, String path, API api, GwCode code) throws Exception {
		String version = "1.0";
		// Get Correct API Class from Mapper
		Class<?> respCls = facade.mapper().getClass(api); 
		if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name());
		// setup Application API HTML ContentTypes for JSON and Route
		String application = applicationJSON(respCls, version);
		//route(env,meth,path,code,application,"application/json;version="+version,"*/*");

		// setup Application API HTML ContentTypes for XML and Route
		application = applicationXML(respCls, version);
		//route(env,meth,path,code.clone(facade_1_0_XML,false),application,"text/xml;version="+version);
		
		// Add other Supported APIs here as created
	}
1093317
public void configureWebApp() throws Exception
    {
        Set tlds = new HashSet();
        
        // Find tld's from web.xml
        // When the XMLConfigurator (or other configurator) parsed the web.xml,
        // It should have created aliases for all TLDs.  So search resources aliases
        // for aliases ending in tld
        if (_context.getResourceAliases()!=null)
        {
            Iterator iter=_context.getResourceAliases().values().iterator();
            while(iter.hasNext())
            {
                String location = (String)iter.next();
                if (location!=null && location.toLowerCase().endsWith(".tld"))
                {
                    if (!location.startsWith("/"))
                        location="/WEB-INF/"+location;
                    Resource l=_context.getBaseResource().addPath(location);
                    tlds.add(l);
                }
            }
        }
        
        // Look for any tlds in WEB-INF directly.
        if (_context.getWebInf()!=null)
        {
            String[] contents = _context.getWebInf().list();
            for (int i=0;i<contents.length;i++)
            {
                if (contents[i]!=null && contents[i].toLowerCase().endsWith(".tld"))
                {
                    Resource l=_context.getWebInf().addPath(contents[i]);
                    tlds.add(l);
                }
                
            }

            // Look for any tlds in the META-INF of included jars
            Resource lib=_context.getWebInf().addPath("lib/");
            if (lib.exists() && lib.isDirectory())
            {
                contents = lib.list();
                for (int i=0;i<contents.length;i++)
                {
                    if (contents[i]!=null && contents[i].toLowerCase().endsWith(".jar"))
                    {
                        Resource l=lib.addPath(contents[i]);
                        Resource meta=Resource.newResource("jar:"+l+"!/META-INF/");
                        if (meta.exists())
                        {
                            String[] meta_contents=meta.list();
                            
                            for (int j=0;j<meta_contents.length;j++)
                            {
                                if (meta_contents[j]!=null && meta_contents[j].toLowerCase().endsWith(".tld"))
                                {
                                    Resource t=meta.addPath(meta_contents[j]);
                                    tlds.add(t);
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // Create a TLD parser
        XmlParser parser = new XmlParser(false);
        
        parser.redirectEntity("web-jsptaglibrary_1_1.dtd",WebApplicationContext.class.getResource("/javax/servlet/jsp/resources/web-jsptaglibrary_1_1.dtd"));
        parser.redirectEntity("web-jsptaglibrary_1_2.dtd",WebApplicationContext.class.getResource("/javax/servlet/jsp/resources/web-jsptaglibrary_1_2.dtd"));
        parser.redirectEntity("web-jsptaglibrary_2_0.xsd",WebApplicationContext.class.getResource("/javax/servlet/jsp/resources/web-jsptaglibrary_2_0.xsd"));
        parser.setXpath("/taglib/listener/listener-class");
        // Parse all the discovered TLDs
        Iterator iter = tlds.iterator();
        while (iter.hasNext())
        {
            try
            {
                Resource tld = (Resource)iter.next();
                if (log.isDebugEnabled()) log.debug("TLD="+tld);
                
                XmlParser.Node root = parser.parse(tld.getURL());
                
                for (int i=0;i<root.size();i++)
                {
                    Object o=root.get(i);
                    if (o instanceof XmlParser.Node)
                    {
                        XmlParser.Node node = (XmlParser.Node)o;
                        if ("listener".equals(node.getTag()))
                        {
                            String className=node.getString("listener-class",false,true);
                            if (log.isDebugEnabled()) log.debug("listener="+className);
                            
                            try
                            {
                                Class listenerClass=getWebApplicationContext().loadClass(className);
                                EventListener l=(EventListener)listenerClass.newInstance();
                                _context.addEventListener(l);
                            }
                            catch(Exception e)
                            {
                                log.warn("Could not instantiate listener "+className,e);
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                log.warn(e);
            }
        }
    }
332194
function bindRenderText(boundText, compileNode, view) {
    var /** @type {?} */ valueField = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__compiler_util_binding_util__["a" /* createCheckBindingField */])(view);
    var /** @type {?} */ evalResult = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__compiler_util_expression_converter__["b" /* convertPropertyBinding */])(view, view, view.componentContext, boundText.value, valueField.bindingId);
    if (!evalResult) {
        return null;
    }
    view.detectChangesRenderPropertiesMethod.resetDebugInfo(compileNode.nodeIndex, boundText);
    view.detectChangesRenderPropertiesMethod.addStmts(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__compiler_util_binding_util__["b" /* createCheckBindingStmt */])(evalResult, valueField.expression, __WEBPACK_IMPORTED_MODULE_9__constants__["g" /* DetectChangesVars */].throwOnChange, [__WEBPACK_IMPORTED_MODULE_6__output_output_ast__["e" /* THIS_EXPR */].prop('renderer')
            .callMethod('setText', [compileNode.renderNode, evalResult.currValExpr])
            .toStmt()]));
}
170787
def render_tag(self, context, caller, **kwargs):
        ''''''
        # load configuration from passed options
        self.load_configuration(**kwargs)

        # get request from context
        request = context['request']

        # get full path from request
        self.full_path = request.get_full_path()

        # render content of extension
        content = caller()

        # check content for "active" urls
        content = render_content(
            content,
            full_path=self.full_path,
            parent_tag=self.parent_tag,
            css_class=self.css_class,
            menu=self.menu,
            ignore_params=self.ignore_params,
        )

        return content
1202126
def update_body(app, pagename, templatename, context, doctree):
    

    STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL)
    online_builders = [
        'readthedocs', 'readthedocsdirhtml', 'readthedocssinglehtml'
    ]
    if app.builder.name == 'readthedocssinglehtmllocalmedia':
        if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme':
            theme_css = '_static/css/theme.css'
        else:
            theme_css = '_static/css/badge_only.css'
    elif app.builder.name in online_builders:
        if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme':
            theme_css = '%scss/sphinx_rtd_theme.css' % STATIC_URL
        else:
            theme_css = '%scss/badge_only.css' % STATIC_URL
    else:
        # Only insert on our HTML builds
        return

    inject_css = True

    # Starting at v0.4.0 of the sphinx theme, the theme CSS should not be injected
    # This decouples the theme CSS (which is versioned independently) from readthedocs.org
    if theme_css.endswith('sphinx_rtd_theme.css'):
        try:
            import sphinx_rtd_theme
            inject_css = LooseVersion(sphinx_rtd_theme.__version__) < LooseVersion('0.4.0')
        except ImportError:
            pass

    if inject_css and theme_css not in app.builder.css_files:
        if sphinx.version_info < (1, 8):
            app.builder.css_files.insert(0, theme_css)
        else:
            app.add_css_file(theme_css)

    # This is monkey patched on the signal because we can't know what the user
    # has done with their `app.builder.templates` before now.

    if not hasattr(app.builder.templates.render, '_patched'):
        # Janky monkey patch of template rendering to add our content
        old_render = app.builder.templates.render

        def rtd_render(self, template, render_context):
            """
            A decorator that renders the content with the users template renderer,
            then adds the Read the Docs HTML content at the end of body.
            """
            # Render Read the Docs content
            template_context = render_context.copy()
            template_context['rtd_css_url'] = '{}css/readthedocs-doc-embed.css'.format(STATIC_URL)
            template_context['rtd_analytics_url'] = '{}javascript/readthedocs-analytics.js'.format(
                STATIC_URL,
            )
            source = os.path.join(
                os.path.abspath(os.path.dirname(__file__)),
                '_templates',
                'readthedocs-insert.html.tmpl'
            )
            templ = open(source).read()
            rtd_content = app.builder.templates.render_string(templ, template_context)

            # Handle original render function
            content = old_render(template, render_context)
            end_body = content.lower().find('</head>')

            # Insert our content at the end of the body.
            if end_body != -1:
                content = content[:end_body] + rtd_content + "\n" + content[end_body:]
            else:
                log.debug("File doesn't look like HTML. Skipping RTD content addition")

            return content

        rtd_render._patched = True
        app.builder.templates.render = types.MethodType(rtd_render,
                                                        app.builder.templates)
1017885
def _bind(self, args, kwds):
    """"""
    bindings = dict(kwds)
    for i, arg in enumerate(args):
      bindings[i + 1] = arg
    used = {}
    ancestor = self.ancestor
    if isinstance(ancestor, ParameterizedThing):
      ancestor = ancestor.resolve(bindings, used)
    filters = self.filters
    if filters is not None:
      filters = filters.resolve(bindings, used)
    unused = []
    for i in xrange(1, 1 + len(args)):
      if i not in used:
        unused.append(i)
    if unused:
      raise datastore_errors.BadArgumentError(
          'Positional arguments %s were given but not used.' %
          ', '.join(str(i) for i in unused))
    return self.__class__(kind=self.kind, ancestor=ancestor,
                          filters=filters, orders=self.orders,
                          app=self.app, namespace=self.namespace,
                          default_options=self.default_options,
                          projection=self.projection, group_by=self.group_by)
157780
def displayhtml(public_key,
                attrs,
                use_ssl=False,
                error=None):
    """"""

    error_param = ''
    if error:
        error_param = '&error=%s' % error

    if use_ssl:
        server = API_SSL_SERVER
    else:
        server = API_SERVER

    if 'lang' not in attrs:
        attrs['lang'] = get_language()[:2]

    return render_to_string(
        WIDGET_TEMPLATE,
        {'api_server': server,
         'public_key': public_key,
         'error_param': error_param,
         'lang': attrs['lang'],
         'options': mark_safe(json.dumps(attrs, indent=2))
         })
535388
function(raw_tag) {

		var view_config = Lava.parsers.Common.compileAsView(raw_tag.content),
			widget_config = Lava.parsers.Common.createDefaultWidgetConfig(),
			name;

		if (Lava.schema.DEBUG) {
			if (view_config['class'] != 'View') Lava.t("define: view in <view> must be pure View, not subclass");
			if ('argument' in view_config) Lava.t("Widgets do not support arguments");
			for (name in view_config) {
				if (this.WIDGET_DEFINITION_ALLOWED_MAIN_VIEW_MEMBERS.indexOf(name) == -1) {
					Lava.t("<view>: view has an option, which can not be copied to widget: " + name + ". Probably, it must be specified via separate tag");
				}
			}
		}

		this._importVars(widget_config, view_config, ['template', 'container']);

		return widget_config;

	}
894535
def configurate_app(config_file=''):
    
    # Load config
    app.config.from_pyfile('defaults.py')
    app.config.from_pyfile(config_file, silent=True)

    if app.config.get('MINIFY_HTML', False):
        app.jinja_env.add_extension('flask_utils.jinja2htmlcompress.HTMLCompress')

    # Setup web assets
    assets = Environment(app)

    js = Bundle('common.js', filters='jsmin', output='gen/main.%(version)s.js')
    css = Bundle('common.css', filters='cssmin', output='gen/main.%(version)s.css')

    assets.register('js_all', js)
    assets.register('css_all', css)

    # Set host and port
    port = app.config.get('PORT', 5000)
    host = app.config.get('HOST', '127.0.0.1')

    return app, host, port
510186
@Override
	public Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) {
		TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB);
		try {
			String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); 
			resp.getOutputStream().print(content);
			setContentType(resp,content.contains("<?xml")?TYPE.XML:TYPE.JSON);
			return Result.ok();
		} catch (Exception e) {
			trans.error().log(e,IN,API_EXAMPLE);
			return Result.err(Result.ERR_NotImplemented,e.getMessage());
		} finally {
			tt.done();
		}
	}
1355699
@Override
	public Response replaceApplicationBindings( String applicationName, String externalExportPrefix, List<String> boundApps ) {

		if( this.logger.isLoggable( Level.FINE )) {
			StringBuilder sb = new StringBuilder();
			sb.append( "Replacing the bindings for the " );
			sb.append( externalExportPrefix );
			sb.append( " prefix with " );
			sb.append( Arrays.toString( boundApps.toArray()));
			sb.append( " in application " );
			sb.append( applicationName );
			sb.append( "." );

			this.logger.fine( sb.toString());
		}

		String lang = lang( this.manager );
		Response response;
		try {
			ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName );
			if( ma == null ) {
				response = RestServicesUtils.handleError(
						Status.NOT_FOUND,
						new RestError( ErrorCode.REST_INEXISTING, application( applicationName )),
						lang ).build();

			} else {
				Set<String> apps = new TreeSet<> ();
				if( boundApps != null )
					apps.addAll( boundApps );

				this.manager.applicationMngr().replaceApplicationBindings( ma, externalExportPrefix, apps );
				response = Response.ok().build();
			}

		} catch( UnauthorizedActionException | IOException e ) {
			response = RestServicesUtils.handleError(
					Status.FORBIDDEN,
					new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ),
					lang ).build();
		}

		return response;
	}
693169
@SuppressWarnings("deprecation")
    private void bindEnvironment() {
        bind(Bootstrap.class).toInstance(bootstrap());
        bind(Environment.class).toInstance(environment());
        install(new ConfigBindingModule(configuration(), configurationTree(),
                context.option(BindConfigurationInterfaces)));
    }
1186739
def initialize_api(args):
  
  global api
  api = ApiResource(server_host=args.hostname, server_port=args.port,
                    username=args.username, password=args.password,
                    version=args.api_version, use_tls=args.use_tls)