// main() starts a simulation network which contains nodes running a simple
// ping-pong protocol
766254
func main() {
	flag.Parse()

	// set the log level to Trace
	log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))

	// register a single ping-pong service
	services := map[string]adapters.ServiceFunc{
		"ping-pong": func(ctx *adapters.ServiceContext) (node.Service, error) {
			return newPingPongService(ctx.Config.ID), nil
		},
	}
	adapters.RegisterServices(services)

	// create the NodeAdapter
	var adapter adapters.NodeAdapter

	switch *adapterType {

	case "sim":
		log.Info("using sim adapter")
		adapter = adapters.NewSimAdapter(services)

	case "exec":
		tmpdir, err := ioutil.TempDir("", "p2p-example")
		if err != nil {
			log.Crit("error creating temp dir", "err", err)
		}
		defer os.RemoveAll(tmpdir)
		log.Info("using exec adapter", "tmpdir", tmpdir)
		adapter = adapters.NewExecAdapter(tmpdir)

	default:
		log.Crit(fmt.Sprintf("unknown node adapter %q", *adapterType))
	}

	// start the HTTP API
	log.Info("starting simulation server on 0.0.0.0:8888...")
	network := simulations.NewNetwork(adapter, &simulations.NetworkConfig{
		DefaultService: "ping-pong",
	})
	if err := http.ListenAndServe(":8888", simulations.NewServer(network)); err != nil {
		log.Crit("error starting simulation server", "err", err)
	}
}
1183519
func main() {
	var l server.ListenConst

	if useDomainSocket {
		l = server.UnixListener(sockPath)
	} else {
		l = server.TCPListener(port)
	}

	protocols := []protocol.Components{binprot.Components, textprot.Components}

	var o orcas.OrcaConst
	var h2 handlers.HandlerConst
	var h1 handlers.HandlerConst

	// Choose the proper L1 handler
	if l1inmem {
		h1 = inmem.New
	} else if chunked {
		h1 = memcached.Chunked(l1sock)
	} else if l1batched {
		h1 = memcached.Batched(l1sock, batchOpts)
	} else {
		h1 = memcached.Regular(l1sock)
	}

	if l2enabled {
		o = orcas.L1L2
		h2 = memcached.Regular(l2sock)
	} else {
		o = orcas.L1Only
		h2 = handlers.NilHandler
	}

	// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers
	// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If
	// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent
	// sets into L1 with chunking can collide and cause data corruption.
	var lockset uint32
	if locked {
		if chunked || !multiReader {
			o, lockset = orcas.Locked(o, false, uint8(concurrency))
		} else {
			o, lockset = orcas.Locked(o, true, uint8(concurrency))
		}
	}

	go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)

	if l2enabled {
		// If L2 is enabled, start the batch L1 / L2 orchestrator
		l = server.TCPListener(batchPort)
		o := orcas.L1L2Batch

		if locked {
			o = orcas.LockedWithExisting(o, lockset)
		}

		go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
	}

	// Block forever
	wg := sync.WaitGroup{}
	wg.Add(1)
	wg.Wait()
}
223799
func main() {
	pwd, _ := os.Getwd()
	env.ReadEnv(path.Join(pwd, ".env"))
	for _, v := range os.Environ() {
		fmt.Println(v)
	}
}
283128
func main() {
	hosts := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
	}
	for name, ip := range hosts {
		fmt.Printf("%v: %v\n", name, ip)
	}
}
898681
func Main() int {
	return ParseAndRun(os.Stdout, os.Stderr, os.Stdin, os.Args[1:])
}
76497
func main() {
	// os.Setenv("IS_ENABLED", "asdf")
	c := &Config{}
	if err := env.Process(c); err != nil {
		fmt.Println("error:", err)
		return
		// panic(err)
	}
	fmt.Printf("name: %s, port: %d, adapter: %s, enabled: %v\n", c.Name, c.Port, c.Adapter, c.Enabled)
}
958080
func main() {
	snapshot, _ := zmq.NewSocket(zmq.ROUTER)
	snapshot.Bind("tcp://*:5556")
	publisher, _ := zmq.NewSocket(zmq.PUB)
	publisher.Bind("tcp://*:5557")
	collector, _ := zmq.NewSocket(zmq.PULL)
	collector.Bind("tcp://*:5558")

	//  The body of the main task collects updates from clients and
	//  publishes them back out to clients:

	sequence := int64(0)
	kvmap := make(map[string]*kvsimple.Kvmsg)

	poller := zmq.NewPoller()
	poller.Add(collector, zmq.POLLIN)
	poller.Add(snapshot, zmq.POLLIN)
LOOP:
	for {
		polled, err := poller.Poll(1000 * time.Millisecond)
		if err != nil {
			break
		}
		for _, item := range polled {
			switch socket := item.Socket; socket {
			case collector:
				//  Apply state update sent from client
				kvmsg, err := kvsimple.RecvKvmsg(collector)
				if err != nil {
					break LOOP //  Interrupted
				}
				sequence++
				kvmsg.SetSequence(sequence)
				kvmsg.Send(publisher)
				kvmsg.Store(kvmap)
				fmt.Println("I: publishing update", sequence)
			case snapshot:
				//  Execute state snapshot request
				msg, err := snapshot.RecvMessage(0)
				if err != nil {
					break LOOP
				}
				identity := msg[0]

				//  Request is in second frame of message
				request := msg[1]
				if request != "ICANHAZ?" {
					fmt.Println("E: bad request, aborting")
					break LOOP
				}
				subtree := msg[2]
				//  Send state snapshot to client

				//  For each entry in kvmap, send kvmsg to client
				for _, kvmsg := range kvmap {
					if key, _ := kvmsg.GetKey(); strings.HasPrefix(key, subtree) {
						snapshot.Send(identity, zmq.SNDMORE)
						kvmsg.Send(snapshot)
					}
				}

				//  Now send END message with sequence number
				fmt.Println("I: sending shapshot =", sequence)
				snapshot.Send(identity, zmq.SNDMORE)
				kvmsg := kvsimple.NewKvmsg(sequence)
				kvmsg.SetKey("KTHXBAI")
				kvmsg.SetBody(subtree)
				kvmsg.Send(snapshot)
			}
		}
	}
	fmt.Printf("Interrupted\n%d messages handled\n", sequence)
}
123687
func (s *Server) Run() {
	var err error

	addr := s.config.Get("server.host") + ":" + s.config.Get("server.port")
	log.Printf("Listening on address: %q", addr)

	s.net, err = net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	defer s.net.Close()

	// Start server ticker
	go s.doTick()

	for !s.working {
		// Wait for a connection.
		conn, err := s.net.Accept()
		if err != nil {
			log.Println(err)
		}

		// Handle the connection in a new goroutine.
		// Multiple connections may be served concurrently.
		go s.handle(conn)
	}
}
893235
func (l *NSQLookupd) Main() error {
	ctx := &Context{l}

	exitCh := make(chan error)
	var once sync.Once
	exitFunc := func(err error) {
		once.Do(func() {
			if err != nil {
				l.logf(LOG_FATAL, "%s", err)
			}
			exitCh <- err
		})
	}

	tcpServer := &tcpServer{ctx: ctx}
	l.waitGroup.Wrap(func() {
		exitFunc(protocol.TCPServer(l.tcpListener, tcpServer, l.logf))
	})
	httpServer := newHTTPServer(ctx)
	l.waitGroup.Wrap(func() {
		exitFunc(http_api.Serve(l.httpListener, httpServer, "HTTP", l.logf))
	})

	err := <-exitCh
	return err
}
246822
func main() {
    // Get Udp data, you can use GOnetstat.Tcp() to get TCP data
     d := GOnetstat.Udp()

     // format header
     fmt.Printf("Proto %16s %20s %14s %24s\n", "Local Adress", "Foregin Adress",
                "State", "Pid/Program")

     for _, p := range(d) {
        // format data like netstat output
        ip_port := fmt.Sprintf("%v:%v", p.Ip, p.Port)
        fip_port := fmt.Sprintf("%v:%v", p.ForeignIp, p.ForeignPort)
        pid_program := fmt.Sprintf("%v/%v", p.Pid, p.Name)

        fmt.Printf("udp %16v %20v %16v %20v\n", ip_port, fip_port,
                            p.State, pid_program)
     }
}
651247
func main() {
	key := os.Getenv("BFX_API_KEY")
	secret := os.Getenv("BFX_API_SECRET")
	client := bitfinex.NewClient().Auth(key, secret)

	dataChan := make(chan bitfinex.TermData)
	go client.WebSocket.ConnectPrivate(dataChan)

	for {
		select {
		case data := <-dataChan:
			if data.HasError() {
				// Data has error - websocket channel will be closed.
				fmt.Println("Error:", data.Error)
				return
			} else {
				fmt.Println("Data:", data)
			}
		}
	}
}
519390
func main() {
	if len(os.Args) < 2 {
		processes()
		return
	}

	cmd := os.Args[1]

	// See if it is a PID.
	pid, err := strconv.Atoi(cmd)
	if err == nil {
		processInfo(pid)
		return
	}

	if cmd == "help" {
		usage("")
	}

	if cmd == "tree" {
		displayProcessTree()
		return
	}

	fn, ok := cmds[cmd]
	if !ok {
		usage("unknown subcommand")
	}
	if len(os.Args) < 3 {
		usage("Missing PID or address.")
		os.Exit(1)
	}
	addr, err := targetToAddr(os.Args[2])
	if err != nil {
		fmt.Fprintf(os.Stderr, "Couldn't resolve addr or pid %v to TCPAddress: %v\n", os.Args[2], err)
		os.Exit(1)
	}
	var params []string
	if len(os.Args) > 3 {
		params = append(params, os.Args[3:]...)
	}
	if err := fn(*addr, params); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}
313076
func main() {

	// initialize celery client
	cli, _ := gocelery.NewCeleryClient(
		gocelery.NewRedisCeleryBroker("redis://"),
		gocelery.NewRedisCeleryBackend("redis://"),
		1,
	)

	// prepare arguments
	taskName := "worker.add"
	argA := rand.Intn(10)
	argB := rand.Intn(10)

	// run task
	asyncResult, err := cli.Delay(taskName, argA, argB)
	if err != nil {
		panic(err)
	}

	// get results from backend with timeout
	res, err := asyncResult.Get(10 * time.Second)
	if err != nil {
		panic(err)
	}

	log.Printf("result: %+v of type %+v", res, reflect.TypeOf(res))

}
868977
func main() {
	//  Start child threads
	go publisher_thread()
	go subscriber_thread()
	go listener_thread()

	time.Sleep(100 * time.Millisecond)

	subscriber, _ := zmq.NewSocket(zmq.XSUB)
	subscriber.Connect("tcp://localhost:6000")
	publisher, _ := zmq.NewSocket(zmq.XPUB)
	publisher.Bind("tcp://*:6001")
	listener, _ := zmq.NewSocket(zmq.PAIR)
	listener.Connect("inproc://pipe")
	zmq.Proxy(subscriber, publisher, listener)

	fmt.Println("interrupted")
}
1067647
func main() {
	os.Setenv("NAME", "foo")
	os.Setenv("PORT", "9001")
	os.Setenv("ADAPTER", "shell")
	// os.Setenv("IS_ENABLED", "asdf")
	c := &Config{}
	if err := env.Process(c); err != nil {
		panic(err)
	}
	fmt.Printf("name: %s, port: %d, adapter: %s, enabled: %v\n", c.Name, c.Port, c.Adapter, c.Enabled)
}
552358
func main() {

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Basic setup and validation
	//////////////////////////////////////////////////////////////////////////

	// If only one argument provided assume it's a filename.
	if len(os.Args) == 2 {
		InFile = os.Args[1]
	}

	// If reading from a file, verify it exists.
	if InFile != "pipe:0" {
		if _, err := os.Stat(InFile); os.IsNotExist(err) {
			fmt.Fprintln(os.Stderr, "warning: infile does not exist as a file on this system, will still continue on incase this is something else that ffmpeg accepts")
		}
	}

	// If reading from pipe, make sure pipe is open
	if InFile == "pipe:0" {
		fi, err := os.Stdin.Stat()
		if err != nil {
			fmt.Println(err)
			return
		}

		if (fi.Mode() & os.ModeCharDevice) == 0 {
		} else {
			fmt.Fprintln(os.Stderr, "error: stdin is not a pipe.")
			flag.Usage()
			return
		}
	}

	if Bitrate < 1 || Bitrate > 512 {
		Bitrate = 64 // Set to Discord default
	}

	//////////////////////////////////////////////////////////////////////////
	// BLOCK : Start reader and writer workers
	//////////////////////////////////////////////////////////////////////////

	options := &dca.EncodeOptions{
		Volume:        Volume,
		Channels:      Channels,
		FrameRate:     FrameRate,
		FrameDuration: FrameDuration,
		Bitrate:       Bitrate,
		RawOutput:     RawOutput,
		Application:   dca.AudioApplication(Application),
		CoverFormat:   CoverFormat,
		VBR:           VBR,
		Comment:       Comment,
		Threads:       Threads,
	}

	var session *dca.EncodeSession
	var output = os.Stdout

	if InFile == "pipe:0" {
		session, err = dca.EncodeMem(os.Stdin, options)
	} else {
		session, err = dca.EncodeFile(InFile, options)
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed creating an encoding session: ", err)
		os.Exit(1)
	}

	if !Quiet {
		go statusPrinter(session)
	}

	_, err := io.Copy(output, session)
	if err != nil {
		fmt.Fprintln(os.Stderr, "\nError writing:", err)
		os.Exit(1)
	} else if !Quiet {
		fmt.Fprintf(os.Stderr, "\nFinished encoding\n")
		fmt.Fprint(os.Stderr, "ffmpeg output\n\n", session.FFMPEGMessages())
	}
}
773241
func (cfg *Config) Main(c context.Context, argv []string, env environ.Env) int {
	if len(argv) == 0 {
		panic("zero-length argument slice")
	}

	// Implementation of "checkWrapper": if CheckWrapperENV is set, we immediately
	// exit with a non-zero value.
	if wrapperCheck(env) {
		return 1
	}

	defaultLogLevel := logging.Error
	if env.GetEmpty(LogTraceENV) != "" {
		defaultLogLevel = logging.Debug
	}

	c = gologger.StdConfig.Use(c)
	c = logging.SetLevel(c, defaultLogLevel)

	a := application{
		Config: cfg,
		opts: vpython.Options{
			EnvConfig: venv.Config{
				BaseDir:           "", // (Determined below).
				MaxHashLen:        6,
				SetupEnv:          env,
				Package:           cfg.VENVPackage,
				PruneThreshold:    cfg.PruneThreshold,
				MaxPrunesPerSweep: cfg.MaxPrunesPerSweep,
				Loader:            cfg.PackageLoader,
			},
			BaseWheels: cfg.BaseWheels,
			WaitForEnv: true,
			SpecLoader: cfg.SpecLoader,
			Environ:    env,
		},
		logConfig: logging.Config{
			Level: defaultLogLevel,
		},
	}

	return run(c, func(c context.Context) error {
		return a.mainImpl(c, argv[0], argv[1:])
	})
}