Engine options discover HTTP entry point
513431
def options(self):
        
        #configure engine with an empty dict to ensure default selection/options
        self.engine.configure({})
        conf = self.engine.as_dict()
        conf["returns"] = [oname for oname in six.iterkeys(self._outputs)]
        # Note: we overide args to only list the ones that are declared in this view
        conf["args"] = [iname for iname in six.iterkeys(self._inputs)]
        return jsonify(conf)
905604
def start():
    
    pool = gevent.threadpool.ThreadPool(len(ENTRYPOINTS))
    for entrypoint, callback, args, kwargs in ENTRYPOINTS:
        cname = callback.__name__
        #1. Retrieve the class which owns the callback
        for name, klass in inspect.getmembers(sys.modules[callback.__module__], inspect.isclass):
            if hasattr(klass, cname):
                service_name = name.lower()
                break
        #2.Start the entrypoint
        callback = getattr(klass(), cname)
        kwargs.update({'service':service_name, 'callback':callback, 'callback_name': cname})
        LOGGER.info('Start service %s[%s].', service_name.capitalize(), cname)
        obj = entrypoint(*args, **kwargs)
        pool.spawn(obj.start, *args, **kwargs)
    pool.join()
    return True
615690
def main():
    # config file
    conf = Config()
    actions = []

    debuglevel = logging.ERROR
    for it in sys.argv[1:]:
        if it == ("-v"):
            debuglevel = logging.WARNING
        elif it == ("-vv"):
            debuglevel = logging.INFO
        elif it == ("-vvv"):
            debuglevel = logging.DEBUG
        if it == ("--valid"):
            actions.append("valid")

    conf.debuglevel = debuglevel

    srv = ServerApp(conf)
    status = srv.login(conf.token)

    if not status:
        sys.exit(100)

    # pick up and run events
    
    srv.do_all_actions(conf)

    """ send data for monitoring """
    if conf.monitoring:
        srv.monitoring()

    """ create repo for web project - apache2/uwsgi"""
    if conf.webproject:
        #data =  srv.get_all_projects()
        #content = aray2xml(data)

        """ Check all repository on this system. """
        srv.check_repo_all()

        """ Recount size of full disk in all project on this system. """
        srv.check_size_all()

        """ reset owners for projects """
        srv.check_rights()

        """ check running services """
        srv.check_services()

        mng = manager(conf)
        for it in actions:
            fc = getattr(mng, it)
            fc()
396033
def launch_browser(attempt_launch_browser=True):
    """"""
    _DISPLAY_VARIABLES = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET']
    _WEBBROWSER_NAMES_BLACKLIST = [
        'www-browser', 'lynx', 'links', 'elinks', 'w3m']

    import webbrowser

    launch_browser = attempt_launch_browser
    if launch_browser:
        if ('linux' in sys.platform and
                not any(os.getenv(var) for var in _DISPLAY_VARIABLES)):
            launch_browser = False
        try:
            browser = webbrowser.get()
            if (hasattr(browser, 'name')
                    and browser.name in _WEBBROWSER_NAMES_BLACKLIST):
                launch_browser = False
        except webbrowser.Error:
            launch_browser = False

    return launch_browser
128382
def start_pipeline(conf, args):
    """"""
    host = conf.config['instances'][args.host_instance]
    url = api.build_pipeline_url(build_instance_url(host))
    auth = tuple([conf.creds['instances'][args.host_instance]['user'], conf.creds['instances'][args.host_instance]['pass']])
    runtime_parameters = {}
    verify_ssl = host.get('verify_ssl', True)
    if args.runtime_parameters:
        runtime_parameters = json.loads(args.runtime_parameters)
    start_result = api.start_pipeline(url, args.pipeline_id, auth, verify_ssl, runtime_parameters)

    return start_result
992233
public static void main(String[] args) {
    ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);
    Props props = entryPoint.getProps();
    new WebServerProcessLogging().configure(props);
    WebServer server = new WebServer(props);
    entryPoint.launch(server);
  }
1300875
def http_context(self, worker_ctx):
        
        http = {}
        if isinstance(worker_ctx.entrypoint, HttpRequestHandler):
            try:
                request = worker_ctx.args[0]
                try:
                    if request.mimetype == 'application/json':
                        data = request.data
                    else:
                        data = request.form
                except ClientDisconnected:
                    data = {}

                urlparts = urlsplit(request.url)
                http.update({
                    'url': '{}://{}{}'.format(
                        urlparts.scheme, urlparts.netloc, urlparts.path
                    ),
                    'query_string': urlparts.query,
                    'method': request.method,
                    'data': data,
                    'headers': dict(get_headers(request.environ)),
                    'env': dict(get_environ(request.environ)),
                })
            except:
                pass  # probably not a compatible entrypoint

        self.client.http_context(http)
609592
def url_for(options = nil, engine_name = current_engine_name)
      options ||= {}
      return super(options) unless options.is_a?(Hash) || options.is_a?(ActionController::Parameters)

      url = EnginePathBuilder.handle(
        engine_name: engine_name, parameters: options, default_url_options: default_url_options
      )
      url ||= main_app.root_path default_url_options.merge(options) if options[:action] == 'home'
      url || super(HashUtils.slice!(options, *options.keys))
    end
947101
function ( options ) {
			this.protocol = options.protocol || 'http';
			this.port = options.port;
			this.server = options.server;
			this.path = options.path;
			this.proxy = options.proxy;
			this.jar = request.jar(); // create new cookie jar for each instance

			this.debug = options.debug;

			// set up logging
			const winston = require( 'winston' ),
				// file logging
				path = require( 'path' ),
				fs = require( 'fs' ),
				logDir = path.dirname( process.argv[ 1 ] ) + '/log/',
				logFile = logDir + path.basename( process.argv[ 1 ], '.js' ) + '.log',
				// how many tasks (i.e. requests) to run in parallel
				concurrency = options.concurrency || 3;

			this.logger = new ( winston.Logger )();

			// console logging
			if ( this.debug ) {
				this.logger.add( winston.transports.Console, {
					level: 'debug'
				} );
			}

			this.logger.cli();

			if ( fs.existsSync( logDir ) ) {
				this.logger.add( winston.transports.File, {
					colorize: true,
					filename: logFile,
					json: false,
					level: this.debug ? 'debug' : 'info'
				} );
			}

			// requests queue
			// @see https://github.com/caolan/async#queue
			this.queue = async.queue( function ( task, callback ) {
			// process the task (and call the provided callback once it's completed)
				task( callback );
			}, concurrency );

			// HTTP client
			this.formatUrl = require( 'url' ).format;

			this.userAgent = options.userAgent || ( `nodemw/${VERSION} (node.js ${process.version}; ${process.platform} ${process.arch})` );
			this.version = VERSION;

			// debug info
			this.info( process.argv.join( ' ' ) );
			this.info( this.userAgent );

			let port = this.port ? `:${this.port}` : '';

			this.info( `Using <${this.protocol}://${this.server}${port}${this.path}/api.php> as API entry point` );
			this.info( '----' );
		}
753298
function HttpConnection(options) {
    options = options ?
        ({
            protocol: (options.protocol || 'http:'),
            host: (options.host || 'localhost'),
            port: (options.port || '80'),
            path: httpPath,
            withCredentials: false
        }) :
        ({
            path: 'http://localhost:80' + httpPath
        });
    this.options = util._extend({
        localAddress: process.env.LOCAL_ADDRESS
    }, options);
    this._config = JSON.stringify(this.options);
    if (logger.isDebugEnabled()) {
        logger.debug('created with %s', this._config);
    }
}
1102679
def main():
    '''
    
    '''
    args = CLI.parse_args(__doc__)

    if args['--verbose']:
        requests_log = logging.getLogger("requests.packages.urllib3")
        requests_log.setLevel(logging.DEBUG)
        logging.basicConfig(level=logging.DEBUG)

    if not args['-k']:
        print("No API key given. Please create an API key on <https://octopart.com/api/dashboard>")
        return ReturnValues.NO_APIKEY

    if args['-t'] == 'octopart':
        engine = PyPartsOctopart(args['-k'], verbose=args['--verbose'])
    elif args['-t'] == 'parts.io':
        engine = PyPartsPartsIO(args['-k'], verbose=args['--verbose'])
    else:
        engine = PyPartsBase(args['-k'], verbose=args['--verbose'])

    try:
        if 'lookup' in args or 'search' in args:
            return engine.part_search(args['<part>'])
        elif 'specs' in args:
            return engine.part_specs(args['<part>'])
        elif 'datasheet' in args:
            if args['<action>'] == 'open':
                if args['--output']:
                    return engine.part_datasheet(args['<part>'], command=args['--command'], path=args['--output'])
                else:
                    return engine.part_datasheet(args['<part>'], command=args['--command'])
            elif args['<action>'] == 'save':
                return engine.part_datasheet(args['<part>'], path=args['--output'])
        elif 'show' in args:
            return engine.part_show(args['<part>'], printout=args['--print'])
    except OctopartException as err:
        print(err)
        return ReturnValues.RUNTIME_ERROR
182395
def main(port=8000, n_output=10, use_segmenter=False):
    """"""
    global n
    global use_segmenter_flag
    n = n_output
    use_segmenter_flag = use_segmenter
    logging.info("Start webserver...")
    app.run(port=port)
990684
function onLauncherConnect(slaveURL) {
    var browsers = attester.config["run-browser"];
    if (browsers) {
        if (!Array.isArray(browsers)) {
            browsers = [browsers];
        }
        var args = [slaveURL];
        for (var i = 0, l = browsers.length; i < l; i++) {
            var curProcess = spawn(browsers[i], args, {
                stdio: "pipe"
            });
            curProcess.stdout.pipe(process.stdout);
            curProcess.stderr.pipe(process.stderr);
        }
    }
}
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
984370
def find_egg_entry_point(self, object_type, name=None):
        
        if name is None:
            name = 'main'
        possible = []
        for protocol_options in object_type.egg_protocols:
            for protocol in protocol_options:
                pkg_resources.require(self.spec)
                entry = pkg_resources.get_entry_info(
                    self.spec,
                    protocol,
                    name)
                if entry is not None:
                    possible.append((entry.load(), protocol, entry.name))
                    break
        if not possible:
            # Better exception
            dist = pkg_resources.get_distribution(self.spec)
            raise LookupError(
                "Entry point %r not found in egg %r (dir: %s; protocols: %s; "
                "entry_points: %s)"
                % (name, self.spec,
                   dist.location,
                   ', '.join(_flatten(object_type.egg_protocols)),
                   ', '.join(_flatten([
                dictkeys(pkg_resources.get_entry_info(self.spec, prot, name) or {})
                for prot in protocol_options] or '(no entry points)'))))
        if len(possible) > 1:
            raise LookupError(
                "Ambiguous entry points for %r in egg %r (protocols: %s)"
                % (name, self.spec, ', '.join(_flatten(protocol_options))))
        return possible[0]
651031
function main(onStart) {
    const conf = config.read();

    initLogging(conf);
    initFsStorage(conf);

    logger.debug('Default configuration file: %s', conf.path);
    logger.debug('Configuration parameters: %s', JSON.stringify(conf));

    runWebServer(conf, onStart);
}
473093
private static void configureEngine(SSLEngine engine, FlowType type, SSLLinkConfig config, SSLConnectionLink connLink) {
        // Update the engine with the latest config parameters.
        engine.setEnabledCipherSuites(config.getEnabledCipherSuites(engine));

        //Set the configured protocol on the SSLEngine
        String protocol = config.getSSLProtocol();
        if (protocol != null) {
            engine.setEnabledProtocols(new String[] { protocol });
        }

        if (type == FlowType.INBOUND) {
            engine.setUseClientMode(false);
            boolean flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION);
            // When on z/OS, need to check the MutualAuthCBINDCheck property
            // to force client authentication
            //TODO: z/os
            //            if (PlatformHelperFactory.getPlatformHelper().isZOS() &&
            //            	 UserRegistryConfig.TYPE_LOCAL_OS.equals(SecurityObjectLocator.getSecurityConfig().getActiveUserRegistry().getType()))
            //            {
            //            	Boolean cbindCheckEnabled = Boolean.FALSE;
            //
            //            	//get the endpoint name off of the thread
            //                Map connectionInfo = JSSEHelper.getInstance().getInboundConnectionInfo();
            //                if (connectionInfo != null) {
            //                    String endpointName = (String) connectionInfo.get(Constants.CONNECTION_INFO_ENDPOINT_NAME);
            //                    //only enforce cbind check on web requests
            //                    if (endpointName != null && endpointName.startsWith("HTTP")) {
            //                    	if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //                            Tr.debug(tc, "The endpoint, " + endpointName + ", is web and we are on z/OS. Proceeding to get the mutualAuthCbindCheck property.");
            //                        }
            //		                try {
            //		                    // Get cbind check flag using reflection
            //		                    final String className = "com.ibm.ws.security.zOS.NativeConfiguration";
            //		                    final Class<?> zNativeConfigClass = Class.forName(className);
            //		                    final Method getConfigMethod = zNativeConfigClass.getMethod("getConfig", (java.lang.Class[]) null);
            //		                    final Object configInstance = getConfigMethod.invoke((java.lang.Class[]) null, (java.lang.Object[]) null);
            //		                    final Method cbindCheckMethod = zNativeConfigClass.getMethod("isMutualAuthCBINDCheckEnabled", (java.lang.Class[]) null);
            //		                    cbindCheckEnabled = (Boolean) cbindCheckMethod.invoke(configInstance, (java.lang.Object[]) null);
            //		                } catch (Exception e) {
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            //		                        Tr.debug(tc, "No class, object, or method found for CBIND check", new Object[] {e});
            //		                    FFDCFilter.processException(e, CLASS_NAME, "1237");
            //		                }
            //		                if (cbindCheckEnabled.booleanValue()) {
            //		                    flag = cbindCheckEnabled.booleanValue();
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //		                        Tr.debug(tc, "The mutualAuthCBINDCheck is true, so hard-coded setNeedClientAuth to true.");}
            //		                }
            //		            }
            //                }
            //            }

            engine.setNeedClientAuth(flag);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Client auth needed is " + engine.getNeedClientAuth());
            }
            if (!flag) {
                // Client auth set to false, check client auth supported
                flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION_SUPPORTED);
                engine.setWantClientAuth(flag);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Client auth supported is " + engine.getWantClientAuth());
                }
            }
            // enable ALPN support if this is for an inbound connection
            AlpnSupportUtils.registerAlpnSupport(connLink, engine);

        } else {
            // Update engine with client side specific config parameters.
            engine.setUseClientMode(true);
        }

        try {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Calling beginHandshake on engine");
            }
            engine.beginHandshake();
        } catch (SSLException se) {
            // no FFDC required
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Error while starting handshake; " + se);
            }
        }
    }