find a port for livereload if needed first
325055
function(callback){

        // Inject live reload snippet
        if (options.livereload !== false) {
          if (options.livereload === true) {
            options.livereload = 35729;
          }

          // TODO: Add custom ports here?
          middleware.unshift(injectLiveReload({port: options.livereload}));
          callback(null);
        } else {
          callback(null);
        }
      }
256571
def _get_conn(self, host, port):
        """"""
        host_key = (host, port)
        if host_key not in self.conns:
            self.conns[host_key] = KafkaConnection(
                host,
                port,
                timeout=self.timeout
            )

        return self.conns[host_key]
738497
def main():
    
    try:
        # Get the `src` directory's absolute path
        src_path = os.path.dirname(
            # `aoiklivereload` directory's absolute path
            os.path.dirname(
                # `demo` directory's absolute path
                os.path.dirname(
                    # This file's absolute path
                    os.path.abspath(__file__)
                )
            )
        )

        # If the `src` directory path is not in `sys.path`
        if src_path not in sys.path:
            # Add to `sys.path`.
            #
            # This aims to save user setting PYTHONPATH when running this demo.
            #
            sys.path.append(src_path)

        # Import reloader class
        from aoiklivereload import LiveReloader

        # Create reloader
        reloader = LiveReloader(
            # Reload mode.
            #
            # In windows, have to use `spawn_exit` reload mode and force the
            # current process to exit immediately, otherwise will get the
            # error:
            # ```
            # OSError: [WinError 10048] Only one usage of each socket address
            # (protocol/network address/port) is normally permitted
            # ```
            #
            # Notice in `spawn_exit` reload mode, the user will not be able
            # to kill the new process using Ctrl-c.
            #
            reload_mode=('spawn_exit' if sys.platform == 'win32' else 'exec'),
            force_exit=True,
        )

        # Start watcher thread
        reloader.start_watcher_thread()

        # Server host
        server_host = '0.0.0.0'

        # Server port
        server_port = 8000

        # Get message
        msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
            server_host, server_port
        )

        # Print message
        print(msg)

        # Create request handler
        class HelloHandler(tornado.web.RequestHandler):
            """
            Request handler class.
            """

            def get(self):
                """
                Request handler.

                :return:
                    None.
                """
                # Write response body
                self.write('hello')

        # List of tuples that maps URL pattern to handler
        handler_tuples = [
            ('/', HelloHandler),
        ]

        # Create Tornado app
        tornado_app = tornado.web.Application(
            handler_tuples,
            # Disable Tornado's reloader
            debug=False,
        )

        # Start listening
        tornado_app.listen(server_port, address=server_host)

        # Get event loop
        io_loop = tornado.ioloop.IOLoop.current()

        # Run event loop
        io_loop.start()

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
1275845
def server_and_prefix(self):
        """"""
        return(host_port_prefix(self.config.host, self.config.port, self.prefix))
1177289
def find_available_port():
    
    s = socket.socket()
    s.bind(('localhost', 0))
    _address, port = s.getsockname()
    s.close()
    return port
1230577
def get_host_port(spec, default_port):
    ""
    args = (spec.split(':', 1) + [default_port])[:2]
    args[1] = int(args[1])
    return args[0], args[1]
656984
def livereload_request(self, **options):
        
        style = color_style()
        verbosity = int(options['verbosity'])
        host = '%s:%s' % (options['livereload_host'],
                          options['livereload_port'])
        try:
            urlopen('http://%s/changed?files=.' % host)
            self.message('LiveReload request emitted.\n',
                         verbosity, style.HTTP_INFO)
        except IOError as e:
            self.stdout.write(
                self.style.WARNING('LiveReload exception: %s' % e)
            )
            pass
355725
function connect() {
    let port = null;

    try {
      port = parseInt(readFileSync(path.join(
        datadir,
        'control-port'
      )).toString().split(':')[1]);
    } catch (err) {
      /* istanbul ignore next */
      portFileReads++;

      /* istanbul ignore next */
      if (portFileReads <= 20) {
        return setTimeout(() => connect(), 1000);
      } else {
        return controller.emit('error',
                               new Error('Failed to read control port'));
      }
    }

    socket.connect(port, '127.0.0.1');
  }
260380
def livereload_request(self, **options):
        
        style = color_style()
        verbosity = int(options['verbosity'])
        host = '%s:%d' % (
            options['livereload_host'],
            options['livereload_port'],
        )
        try:
            urlopen('http://%s/forcereload' % host)
            self.message('LiveReload request emitted.\n',
                         verbosity, style.HTTP_INFO)
        except IOError:
            pass
896422
def find_free_port():
    """"""
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        sock.bind(('', 0))
        return sock.getsockname()[1]
137657
def find_port(addr, user):
    """"""
    import pwd
    home = pwd.getpwuid(os.getuid()).pw_dir
    for name in os.listdir('%s/.ssh/' % home):
        if name.startswith('unixpipe_%s@%s_' % (user, addr,)):
            return int(name.split('_')[2])
593689
def get_host_port(self, container_port, proto='tcp', index=0):
        
        port_spec = '{}/{}'.format(container_port, proto)
        return self._host_port(port_spec, index)
289064
def connectToServer(self):
    """"""
    self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
      self.rtspSocket.connect((self.serverAddr, self.serverPort))
    except:
      tkinter.messagebox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
714100
def connect(self):
        """"""
        if not getattr(self._local, 'conn', None):
            try:
                server = self._servers.get()
                logger.debug('Connecting to %s', server)
                self._local.conn = ClientTransport(server, self._framed_transport,
                    self._timeout, self._recycle)
            except (Thrift.TException, socket.timeout, socket.error):
                logger.warning('Connection to %s failed.', server)
                self._servers.mark_dead(server)
                return self.connect()
        return self._local.conn
314912
def add_port_callback(self, port, cb):
        """"""
        logger.debug('Adding callback on port [%d] to [%s]', port, cb)
        self.add_header_callback(cb, port, 0, 0xff, 0x0)
495141
function (callback) {
    checkPortStatus(port, host, opts, function (error, statusOfPort) {
      numberOfPortsChecked++
      if (statusOfPort === status) {
        foundPort = true
        callback(error)
      } else {
        port = portList ? portList[numberOfPortsChecked] : port + 1
        callback(null)
      }
    })
  }
1230271
function () {

	if (l_ip_port === undefined) {
		LOG.warn('not init (or already disposed), cannot connect to server');
		return;
	}

	if (l_connector === undefined)    
		l_connector = new SR.Connector(l_config);

    // establish connection
	LOG.warn('connecting to: ' + l_ip_port);
	l_connector.connect(l_ip_port, function (err, socket) {
		
		if (err) {
			// try-again later
			LOG.warn('attempt to re-connect in: ' + l_timeoutConnectRetry + 'ms');
			setTimeout(l_connect, l_timeoutConnectRetry);
			return;
		}
				
		LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established');
        l_connector.send('SR_REGISTER_SERVER', l_para, 'SR_REGISTER_SERVER_R', function (res) {
            console.log(res.data);
        });
	});    
}