//  This is the thread that handles our real clone class
//  Constructor for the clone class. Note that we create
//  the pipe that connects our frontend to the
//  backend agent:
11830
func New() (clone *Clone) {
	clone = &Clone{}
	clone.pipe, _ = zmq.NewSocket(zmq.PAIR)
	pipename := fmt.Sprint("inproc://pipe", pipe_nmb)
	pipe_nmb++
	clone.pipe.Bind(pipename)
	go clone_agent(pipename)
	return
}
1027081
func init() {
	graphdriver.Register("lcow", InitDriver)
	// DOCKER_LCOW_NOREEXEC allows for inline processing which makes
	// debugging issues in the re-exec codepath significantly easier.
	if os.Getenv("DOCKER_LCOW_NOREEXEC") != "" {
		logrus.Warnf("LCOW Graphdriver is set to not re-exec. This is intended for debugging purposes only.")
		noreexec = true
	} else {
		reexec.Register("docker-lcow-tar2ext4", tar2ext4Reexec)
	}
}
525719
func pipe() (io.ReadCloser, io.WriteCloser) {
	w := &pipeWriter{
		consumed: make(chan struct{}),
		provided: make(chan struct{}),
		closed:   make(chan struct{}),
	}
	r := &pipeReader{
		w:      w,
		closed: make(chan struct{}),
	}
	w.r = r
	return r, w
}
680827
func (s *SidecarApi) watchHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
	defer req.Body.Close()

	response.Header().Set("Content-Type", "application/json")

	listener := NewHttpListener()

	// Find out when the http connection closed so we can stop
	notify := response.(http.CloseNotifier).CloseNotify()

	// Let's subscribe to state change events
	// AddListener and RemoveListener are thread safe
	s.state.AddListener(listener)
	defer s.state.RemoveListener(listener.Name())

	byService := true
	if req.URL.Query().Get("by_service") == "false" {
		byService = false
	}

	var jsonBytes []byte
	pushUpdate := func() error {
		if byService {
			s.state.RLock()
			var err error
			jsonBytes, err = json.Marshal(s.state.ByService())
			s.state.RUnlock()

			if err != nil {
				return err
			}
		} else {
			s.state.RLock()
			jsonBytes = s.state.Encode()
			s.state.RUnlock()
		}

		// In order to flush immediately, we have to cast to a Flusher.
		// The normal HTTP library supports this but not all do, so we
		// check just in case.
		response.Write(jsonBytes)
		if f, ok := response.(http.Flusher); ok {
			f.Flush()
		}

		return nil
	}

	// Push the first update right away
	err := pushUpdate()
	if err != nil {
		log.Errorf("Error marshaling state in watchHandler: %s", err.Error())
		return
	}

	// Watch for further updates on the channel
	for {
		select {
		case <-notify:
			return

		case <-listener.Chan():
			err = pushUpdate()
			if err != nil {
				log.Errorf("Error marshaling state in watchHandler: %s", err.Error())
				return
			}
		}
	}
}
110177
func (c *Constant) Clone() Expression {
	if c.DeferredExpr != nil {
		con := *c
		return &con
	}
	return c
}
550708
func main() {
	g := generator.New()

	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		failWithError(err, "reading input")
	}

	if err := proto.Unmarshal(data, g.Request); err != nil {
		failWithError(err, "parsing input proto")
	}

	if len(g.Request.FileToGenerate) == 0 {
		fail("no files to generate")
	}

	g.CommandLineParameters(g.Request.GetParameter())

	if val, ok := g.Param["logtostderr"]; ok && val == "true" {
		logtostderr = true
	}

	tree := buildTree(g.Request.GetProtoFile())

	packageLocations := make(map[string]string)
	for _, file := range g.Request.GetProtoFile() {
		loc := file.GetName()[:strings.LastIndex(file.GetName(), "/")]
		packageLocations[file.GetPackage()] = loc
	}

	selectedServices := make(map[string]string)
	for k, v := range g.Param {
		switch {
		case k == "logtostderr":
			if v == "true" {
				logtostderr = true
			}
		case strings.HasPrefix(k, "."):
			selectedServices[k] = v
		}
	}

	for serviceKey := range selectedServices {
		service, ok := tree.services[serviceKey]
		if !ok {
			fail("Service", serviceKey, "unknown")
		}

		usedMessages := make(map[string]*message)
		usedEnums := make(map[string]*enum)

		content := new(bytes.Buffer)

		fmt.Fprintf(content, "# %s API Reference\n\n", service.GetName())
		if service.comment != "" {
			fmt.Fprintf(content, "%s\n\n", service.comment)
		}

		if len(service.methods) > 0 {
			fmt.Fprint(content, "## Methods\n\n")

			for _, method := range service.methods {
				fmt.Fprintf(content, "### `%s`\n\n", method.GetName())
				if method.comment != "" {
					fmt.Fprintf(content, "%s\n\n", method.comment)
				}
				if method.inputStream {
					fmt.Fprintf(content, "- Client stream of [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Request: [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.input, usedMessages, usedEnums)
				if method.outputStream {
					fmt.Fprintf(content, "- Server stream of [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Response: [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.output, usedMessages, usedEnums)

				fmt.Fprintln(content)

				if len(method.endpoints) != 0 {
					if len(method.endpoints) == 1 {
						fmt.Fprint(content, "#### HTTP Endpoint\n\n")
					} else {
						fmt.Fprint(content, "#### HTTP Endpoints\n\n")
					}
					for _, endpoint := range method.endpoints {
						fmt.Fprintf(content, "- `%s` `%s`", endpoint.method, endpoint.url)
						var params []string
						for _, match := range regexp.MustCompile(`\{([a-z_]+)\}`).FindAllStringSubmatch(endpoint.url, -1) {
							if match != nil && len(match) == 2 && match[1] != "" {
								params = append(params, fmt.Sprintf("`%s`", match[1]))
							}
						}
						if len(params) > 0 {
							fmt.Fprintf(content, "(%s can be left out of the request body)", strings.Join(params, ", "))
						}
						fmt.Fprintln(content)
					}
					fmt.Fprintln(content)

					fmt.Fprint(content, "#### JSON Request Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.input.JSONExample(tree))

					fmt.Fprint(content, "#### JSON Response Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.output.JSONExample(tree))
				}
			}
		}

		if len(usedMessages) > 0 {
			fmt.Fprint(content, "## Messages\n\n")

			var messageKeys []string
			for key := range usedMessages {
				messageKeys = append(messageKeys, key)
			}
			sort.Strings(messageKeys)

			for _, messageKey := range messageKeys {
				message := usedMessages[messageKey]
				fmt.Fprintf(content, "### `%s`\n\n", message.key)
				if strings.HasPrefix(messageKey, ".google") {
					fmt.Fprintf(content, "%s\n\n", strings.SplitAfter(message.comment, ".")[0])
				} else if message.comment != "" {
					fmt.Fprintf(content, "%s\n\n", message.comment)
				}
				if len(message.fields) > 0 {
					fmt.Fprintln(content, "| Field Name | Type | Description |")
					fmt.Fprintln(content, "| ---------- | ---- | ----------- |")
					for idx, field := range message.fields {
						if field.isOneOf {
							if idx == 0 || !message.fields[idx-1].isOneOf || message.fields[idx-1].GetOneofIndex() != field.GetOneofIndex() {
								oneof := message.GetOneof(field.GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **oneof %d** | one of the following %d |\n", oneof.GetName(), len(oneof.fields), len(oneof.fields))
								}
							}
						} else {
							if idx > 0 && message.fields[idx-1].isOneOf {
								oneof := message.GetOneof(message.fields[idx-1].GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **end oneof %d** |  |\n", oneof.GetName(), len(oneof.fields))
								}
							}
						}

						var fieldType string
						if field.repeated {
							fieldType += "_repeated_ "
						}
						typ := strings.ToLower(strings.TrimPrefix(field.GetType().String(), "TYPE_"))
						switch typ {
						case "message":
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						case "enum":
							// TODO(htdvisser): test this
							if enum, ok := tree.enums[field.GetTypeName()]; ok {
								usedEnums[field.GetTypeName()] = enum
							}
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						default:
							fieldType += fmt.Sprintf("`%s`", typ)
						}
						fmt.Fprintf(content, "| `%s` | %s | %s |\n", field.GetName(), fieldType, strings.Replace(field.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		if len(usedEnums) > 0 {
			fmt.Fprint(content, "## Used Enums\n\n")

			var enumKeys []string
			for key := range usedEnums {
				enumKeys = append(enumKeys, key)
			}
			sort.Strings(enumKeys)

			for _, enumKey := range enumKeys {
				enum := usedEnums[enumKey]

				fmt.Fprintf(content, "### `%s`\n\n", enum.key)
				if enum.comment != "" {
					fmt.Fprintf(content, "%s\n\n", enum.comment)
				}

				if len(enum.values) > 0 {
					fmt.Fprintln(content, "| Value | Description |")
					fmt.Fprintln(content, "| ----- | ----------- |")
					for _, value := range enum.values {
						fmt.Fprintf(content, "| `%s` | %s |\n", value.GetName(), strings.Replace(value.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		packageService := strings.TrimPrefix(service.key, ".")
		packageName := packageService[:strings.Index(packageService, ".")]
		location, ok := packageLocations[packageName]
		if !ok {
			fail("Could not find location of package", packageName)
		}
		fileName := path.Join(location, service.GetName()+".md")
		contentString := content.String()
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    &fileName,
			Content: &contentString,
		})
	}

	// Send back the results.
	data, err = proto.Marshal(g.Response)
	if err != nil {
		failWithError(err, "failed to marshal output proto")
	}
	_, err = os.Stdout.Write(data)
	if err != nil {
		failWithError(err, "failed to write output proto")
	}
}
119649
func main() {
	// Init DB and plan to close it at the end of the programme
	dbconn.Connect()
	defer dbconn.DB.Close()

	// Set GIN in production mode if run in production
	if !config.GDevEnv {
		gin.SetMode(gin.ReleaseMode)
	}

	// Init router
	router := gin.Default()
	router.Use(cors.New(apitool.DefaultCORSConfig()))

	// User component
	userComponent := user.New(rest.New(service.New(repo.New())))
	userComponent.AttachPublicAPI(router.Group("/api/v1"))
	userComponent.AttachPrivateAPI(router.Group("/api/private-v1"))

	// Start router
	go log.Println("Service user started: Navigate to " + config.GAppUrl)
	router.Run(":" + config.GPort)
}
1158206
func InitializeThreads() {
	//c, err := net.Dial(proto, address)
	//conn = c

	in = In{
		Commands:         make(chan *commands.Command),
		CommandResponses: make(chan *commands.CommandResponse),
		Quit:             make(chan int),
	}

	out = Out{
		CommandResponses: make(chan commands.CommandResponse),
		Errors:           make(chan error),
	}

	go Reader(&out, &in)
	go Writer(&out, &in)

	go func() {
		fmt.Println("Registering signals")
		p := []os.Signal{syscall.SIGINT}
		c := make(chan os.Signal, len(p))
		signal.Notify(c, p...)

		for s := range c {
			fmt.Println("Getting signal ", s)
			if s == os.Interrupt || s == os.Kill {
				fmt.Println("Finishing clean up quiting")
				CleanExit()
				return
			}
		}
	}()
	return
}
977535
func makeConstructor(
	tpt interface{},
	tptType reflect.Type,
	argTypes map[reflect.Type]constructor,
) (func(host.Host, *tptu.Upgrader) (interface{}, error), error) {
	v := reflect.ValueOf(tpt)
	// avoid panicing on nil/zero value.
	if v == (reflect.Value{}) {
		return nil, fmt.Errorf("expected a transport or transport constructor, got a %T", tpt)
	}
	t := v.Type()
	if t.Kind() != reflect.Func {
		return nil, fmt.Errorf("expected a transport or transport constructor, got a %T", tpt)
	}

	if err := checkReturnType(t, tptType); err != nil {
		return nil, err
	}

	argConstructors, err := makeArgumentConstructors(t, argTypes)
	if err != nil {
		return nil, err
	}

	return func(h host.Host, u *tptu.Upgrader) (interface{}, error) {
		arguments := make([]reflect.Value, len(argConstructors))
		for i, makeArg := range argConstructors {
			arguments[i] = reflect.ValueOf(makeArg(h, u))
		}
		return callConstructor(v, arguments)
	}, nil
}
108861
func (this *Response) Clone() *Response {
	r := createResponse(this.Response, this.next, this.app)
	r.SetRequest(this.req)
	return r
}
794248
func main() {
	// Clones the given repository, creating the remote, the local branches
	// and fetching the objects, everything in memory:
	Info("git clone https://github.com/src-d/go-siva")
	r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
		URL: "https://github.com/src-d/go-siva",
	})
	CheckIfError(err)

	// Gets the HEAD history from HEAD, just like this command:
	Info("git log")

	// ... retrieves the branch pointed by HEAD
	ref, err := r.Head()
	CheckIfError(err)

	// ... retrieves the commit history
	cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
	CheckIfError(err)

	// ... just iterates over the commits, printing it
	err = cIter.ForEach(func(c *object.Commit) error {
		fmt.Println(c)

		return nil
	})
	CheckIfError(err)
}
625092
func (h *TermsHashPerFieldImpl) _constructor(spi TermsHashPerFieldSPI,
	streamCount int, fieldState *FieldInvertState,
	termsHash TermsHash, nextPerField TermsHashPerField,
	fieldInfo *FieldInfo) {

	termsHashImpl := termsHash.fields()

	h.spi = spi
	h.intPool = termsHashImpl.intPool
	h.bytePool = termsHashImpl.bytePool
	h.termBytePool = termsHashImpl.termBytePool
	h.docState = termsHashImpl.docState
	h.termsHash = termsHash
	h.bytesUsed = termsHashImpl.bytesUsed
	h.fieldState = fieldState
	h.streamCount = streamCount
	h.numPostingInt = 2 * streamCount
	h.fieldInfo = fieldInfo
	h.nextPerField = nextPerField
	byteStarts := newPostingsBytesStartArray(h, h.bytesUsed)
	h.bytesHash = util.NewBytesRefHash(termsHashImpl.termBytePool, HASH_INIT_SIZE, byteStarts)
}
1284372
func main() {
	// Set up a connection to the server.
	cr, err := credentials.NewClientTLSFromFile("./testdata/out/GearTest.crt", "127.0.0.1")
	if err != nil {
		log.Fatalf("credentials error: %v", err)
	}
	conn, err := grpc.Dial("127.0.0.1:3000", grpc.WithTransportCredentials(cr))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	for i := 0; i < 10; i++ {
		r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: strconv.Itoa(i)})
		if err != nil {
			log.Fatalf("could not greet: %v", err)
		}
		log.Printf("Greeting: %s", r.Message)
	}

	// bench(c)
}
1288039
func cloneHeader(h http.Header) http.Header {
	h2 := make(http.Header, len(h))
	for k, vv := range h {
		vv2 := make([]string, len(vv))
		copy(vv2, vv)
		h2[k] = vv2
	}
	return h2
}
569647
func (b *Backend) Clone() *Backend {
	var c Backend
	c.Copy(b)
	return &c
}
195923
func server_thread() {
	file, err := os.Open("testdata")
	if err != nil {
		panic(err)
	}

	router, _ := zmq.NewSocket(zmq.ROUTER)
	//  Default HWM is 1000, which will drop messages here
	//  since we send more than 1,000 chunks of test data,
	//  so set an infinite HWM as a simple, stupid solution:
	router.SetRcvhwm(0)
	router.SetSndhwm(0)
	router.Bind("tcp://*:6000")
	for {
		//  First frame in each message is the sender identity
		identity, err := router.Recv(0)
		if err != nil {
			break //  Shutting down, quit
		}

		//  Second frame is "fetch" command
		command, _ := router.Recv(0)
		if command != "fetch" {
			panic("command != \"fetch\"")
		}

		chunk := make([]byte, CHUNK_SIZE)
		for {
			n, _ := io.ReadFull(file, chunk)
			router.SendMessage(identity, chunk[:n])
			if n == 0 {
				break //  Always end with a zero-size frame
			}
		}
	}
	file.Close()
}
58790
func main() {
	//  Prepare our sockets
	frontend, _ := zmq.NewSocket(zmq.ROUTER)
	backend, _ := zmq.NewSocket(zmq.ROUTER)
	defer frontend.Close()
	defer backend.Close()
	frontend.Bind("ipc://frontend.ipc")
	backend.Bind("ipc://backend.ipc")

	for client_nbr := 0; client_nbr < NBR_CLIENTS; client_nbr++ {
		go client_task()
	}
	for worker_nbr := 0; worker_nbr < NBR_WORKERS; worker_nbr++ {
		go worker_task()
	}

	//  Queue of available workers
	workers := make([]string, 0, 10)

	poller1 := zmq.NewPoller()
	poller1.Add(backend, zmq.POLLIN)
	poller2 := zmq.NewPoller()
	poller2.Add(backend, zmq.POLLIN)
	poller2.Add(frontend, zmq.POLLIN)

LOOP:
	for {
		//  Poll frontend only if we have available workers
		var sockets []zmq.Polled
		var err error
		if len(workers) > 0 {
			sockets, err = poller2.Poll(-1)
		} else {
			sockets, err = poller1.Poll(-1)
		}
		if err != nil {
			break //  Interrupted
		}
		for _, socket := range sockets {
			switch socket.Socket {
			case backend:
				//  Handle worker activity on backend

				//  Use worker identity for load-balancing
				msg, err := backend.RecvMessage(0)
				if err != nil {
					break LOOP //  Interrupted
				}
				identity, msg := unwrap(msg)
				workers = append(workers, identity)

				//  Forward message to client if it's not a READY
				if msg[0] != WORKER_READY {
					frontend.SendMessage(msg)
				}

			case frontend:
				//  Get client request, route to first available worker
				msg, err := frontend.RecvMessage(0)
				if err == nil {
					backend.SendMessage(workers[0], "", msg)
					workers = workers[1:]
				}
			}
		}
	}

	time.Sleep(100 * time.Millisecond)
}