// source: github.com/gogo/protobuf/proto
761196
func encodeVarint(x uint64) []byte {
	var buf [10]byte
	var n int
	for n = 0; x > 127; n++ {
		buf[n] = 0x80 | uint8(x&0x7F)
		x >>= 7
	}
	buf[n] = uint8(x)
	n++
	return buf[0:n]
}
1125751
func main() {
	args := map[string]string{}
	gp := geopattern.Base64String(args)
	fmt.Println(gp)
}
278133
func gt(m interface{}, value interface{}) (hpredicate, error) {
	switch mapper := m.(type) {
	case toInt:
		return intGT(mapper, value)
	case toFloat64:
		return float64GT(mapper, value)
	}
	return nil, fmt.Errorf("gt: unsupported argument: %T", m)
}
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")
	}
}
25976
func assignGoTypeToProtoPackage(p *protobufPackage, t *types.Type, local, global typeNameSet, optional map[types.Name]struct{}) {
	newT, isProto := isFundamentalProtoType(t)
	if isProto {
		t = newT
	}
	if otherP, ok := global[t.Name]; ok {
		if _, ok := local[t.Name]; !ok {
			p.Imports.AddType(&types.Type{
				Kind: types.Protobuf,
				Name: otherP.ProtoTypeName(),
			})
		}
		return
	}
	if t.Name.Package == p.PackagePath {
		// Associate types only to their own package
		global[t.Name] = p
	}
	if _, ok := local[t.Name]; ok {
		return
	}
	// don't recurse into existing proto types
	if isProto {
		p.Imports.AddType(t)
		return
	}

	local[t.Name] = p
	for _, m := range t.Members {
		if namer.IsPrivateGoName(m.Name) {
			continue
		}
		field := &protoField{}
		tag := reflect.StructTag(m.Tags).Get("protobuf")
		if tag == "-" {
			continue
		}
		if err := protobufTagToField(tag, field, m, t, p.ProtoTypeName()); err == nil && field.Type != nil {
			assignGoTypeToProtoPackage(p, field.Type, local, global, optional)
			continue
		}
		assignGoTypeToProtoPackage(p, m.Type, local, global, optional)
	}
	// TODO: should methods be walked?
	if t.Elem != nil {
		assignGoTypeToProtoPackage(p, t.Elem, local, global, optional)
	}
	if t.Key != nil {
		assignGoTypeToProtoPackage(p, t.Key, local, global, optional)
	}
	if t.Underlying != nil {
		if t.Kind == types.Alias && isOptionalAlias(t) {
			optional[t.Name] = struct{}{}
		}
		assignGoTypeToProtoPackage(p, t.Underlying, local, global, optional)
	}
}
1019468
func NewProtobufEvent(e *com_signalfx_metrics_protobuf.Event) (*event.Event, error) {
	dims := make(map[string]string, len(e.GetDimensions())+1)
	edims := e.GetDimensions()
	for _, dpdim := range edims {
		dims[dpdim.GetKey()] = dpdim.GetValue()
	}

	// sure wish protobuf has something eqiv of interface{} instead of only union structs...
	// <sigh>
	props := make(map[string]interface{}, len(e.GetDimensions())+1)
	for _, dpdim := range e.GetProperties() {
		pval := dpdim.GetValue()
		pkey := dpdim.GetKey()
		if pval.StrValue != nil {
			props[pkey] = pval.GetStrValue()
		} else if pval.BoolValue != nil {
			props[pkey] = pval.GetBoolValue()
		} else if pval.DoubleValue != nil {
			props[pkey] = pval.GetDoubleValue()
		} else if pval.IntValue != nil {
			props[pkey] = pval.GetIntValue()
		} else {
			return nil, errPropertyValueNotSet
		}
	}

	cat := event.ToProtoEC(e.GetCategory())
	return event.NewWithProperties(e.GetEventType(), cat, dims, props, fromTs(e.GetTimestamp())), nil
}
772357
func protoc(goOut string, includes, fnames []string) ([]byte, error) {
	args := []string{"--go_out=plugins=grpc:" + goOut}
	for _, inc := range includes {
		args = append(args, "-I", inc)
	}
	args = append(args, fnames...)
	return exec.Command("protoc", args...).CombinedOutput()
}
1219931
func (s *Status) Proto() *spb.Status {
	if s == nil {
		return nil
	}
	return proto.Clone(s.s).(*spb.Status)
}
468015
func main() {

	app := iris.New()

	app.Get("/users", func(ctx iris.Context) {
		ctx.Gzip(true)
		ctx.ContentType("text/html")

		var userList = []string{
			"Alice",
			"Bob",
			"Tom",
		}

		// Had better use buffer sync.Pool.
		// Hero(github.com/shiyanhui/hero/hero) exports GetBuffer and PutBuffer for this.
		//
		// buffer := hero.GetBuffer()
		// defer hero.PutBuffer(buffer)
		// buffer := new(bytes.Buffer)
		// template.UserList(userList, buffer)
		// ctx.Write(buffer.Bytes())

		// using an io.Writer for automatic buffer management (i.e. hero built-in buffer pool),
		// iris context implements the io.Writer by its ResponseWriter
		// which is an enhanced version of the standard http.ResponseWriter
		// but still 100% compatible, GzipResponseWriter too:
		// _, err := template.UserListToWriter(userList, ctx.GzipResponseWriter())
		buffer := new(bytes.Buffer)
		template.UserList(userList, buffer)

		_, err := ctx.Write(buffer.Bytes())
		if err != nil {
			ctx.StatusCode(iris.StatusInternalServerError)
			ctx.WriteString(err.Error())
		}
	})

	app.Run(iris.Addr(":8080"))
}
762669
func (p Port) Proto() string {
	parts := strings.Split(string(p), "/")
	if len(parts) == 1 {
		return "tcp"
	}
	return parts[1]
}
1180572
func protobufTagToField(tag string, field *protoField, m types.Member, t *types.Type, localPackage types.Name) error {
	if len(tag) == 0 || tag == "-" {
		return nil
	}

	// protobuf:"bytes,3,opt,name=Id,customtype=github.com/gogo/protobuf/test.Uuid"
	parts := strings.Split(tag, ",")
	if len(parts) < 3 {
		return fmt.Errorf("member %q of %q malformed 'protobuf' tag, not enough segments\n", m.Name, t.Name)
	}
	protoTag, err := strconv.Atoi(parts[1])
	if err != nil {
		return fmt.Errorf("member %q of %q malformed 'protobuf' tag, field ID is %q which is not an integer: %v\n", m.Name, t.Name, parts[1], err)
	}
	field.Tag = protoTag

	// In general there is doesn't make sense to parse the protobuf tags to get the type,
	// as all auto-generated once will have wire type "bytes", "varint" or "fixed64".
	// However, sometimes we explicitly set them to have a custom serialization, e.g.:
	//   type Time struct {
	//     time.Time `protobuf:"Timestamp,1,req,name=time"`
	//   }
	// to force the generator to use a given type (that we manually wrote serialization &
	// deserialization methods for).
	switch parts[0] {
	case "varint", "fixed32", "fixed64", "bytes", "group":
	default:
		name := types.Name{}
		if last := strings.LastIndex(parts[0], "."); last != -1 {
			prefix := parts[0][:last]
			name = types.Name{
				Name:    parts[0][last+1:],
				Package: prefix,
				Path:    strings.Replace(prefix, ".", "/", -1),
			}
		} else {
			name = types.Name{
				Name:    parts[0],
				Package: localPackage.Package,
				Path:    localPackage.Path,
			}
		}
		field.Type = &types.Type{
			Name: name,
			Kind: types.Protobuf,
		}
	}

	protoExtra := make(map[string]string)
	for i, extra := range parts[3:] {
		parts := strings.SplitN(extra, "=", 2)
		if len(parts) != 2 {
			return fmt.Errorf("member %q of %q malformed 'protobuf' tag, tag %d should be key=value, got %q\n", m.Name, t.Name, i+4, extra)
		}
		switch parts[0] {
		case "name":
			protoExtra[parts[0]] = parts[1]
		case "casttype", "castkey", "castvalue":
			parts[0] = fmt.Sprintf("(gogoproto.%s)", parts[0])
			protoExtra[parts[0]] = strconv.Quote(parts[1])
		}
	}

	field.Extras = protoExtra
	if name, ok := protoExtra["name"]; ok {
		field.Name = name
		delete(protoExtra, "name")
	}

	return nil
}
1320095
func init() {
	validation.Rules.Add(
		"regex:projects/.*",
		"${appid}.cfg",
		func(ctx *validation.Context, configSet, path string, content []byte) error {
			cfg := &notifypb.ProjectConfig{}
			if err := proto.UnmarshalText(string(content), cfg); err != nil {
				ctx.Errorf("invalid ProjectConfig proto message: %s", err)
			} else {
				validateProjectConfig(ctx, cfg)
			}
			return nil
		})

	validation.Rules.Add(
		"regex:projects/.*",
		`regex:${appid}/email-templates/[^/]+\.template`,
		validateEmailTemplateFile)
}
1288481
func (dec *Decoder) Decode(pb proto.Message) error {
	buf, err := ioutil.ReadAll(dec.r)
	if err != nil {
		return err
	}

	return proto.Unmarshal(buf, pb)
}
574394
func (r ProtoBuf) Render(w http.ResponseWriter) error {
	r.WriteContentType(w)

	bytes, err := proto.Marshal(r.Data.(proto.Message))
	if err != nil {
		return err
	}

	_, err = w.Write(bytes)
	return err
}
1214827
func MetadataFromProto(proto *pb.Metadata) Metadata {
	if euiBytes := proto.GetAppEUI(); euiBytes != nil {
		eui := new(types.AppEUI)
		if err := eui.Unmarshal(euiBytes); err != nil {
			return nil
		}
		return AppEUIMetadata{*eui}
	}
	if appID := proto.GetAppID(); appID != "" {
		return AppIDMetadata{appID}
	}
	if prefixBytes := proto.GetDevAddrPrefix(); prefixBytes != nil {
		prefix := new(types.DevAddrPrefix)
		if err := prefix.Unmarshal(prefixBytes); err != nil {
			return nil
		}
		return PrefixMetadata{*prefix}
	}
	if gatewayID := proto.GetGatewayID(); gatewayID != "" {
		return GatewayIDMetadata{gatewayID}
	}
	return nil
}
755951
func (t *FpdfTpl) GobDecode(buf []byte) error {
	r := bytes.NewBuffer(buf)
	decoder := gob.NewDecoder(r)

	firstClassTemplates := make([]*FpdfTpl, 0)
	err := decoder.Decode(&firstClassTemplates)
	t.templates = make([]Template, len(firstClassTemplates))

	for x := 0; x < len(t.templates); x++ {
		t.templates[x] = Template(firstClassTemplates[x])
	}

	firstClassImages := t.childrenImages()

	t.templates = append(t.childrensTemplates(), t.templates...)

	t.images = make(map[string]*ImageInfoType)
	if err == nil {
		err = decoder.Decode(&t.images)
	}

	for k, v := range firstClassImages {
		t.images[k] = v
	}

	if err == nil {
		err = decoder.Decode(&t.corner)
	}
	if err == nil {
		err = decoder.Decode(&t.size)
	}
	if err == nil {
		err = decoder.Decode(&t.bytes)
	}
	if err == nil {
		err = decoder.Decode(&t.page)
	}

	return err
}
729732
func ProtoToTime(ts *logutilpb.Time) time.Time {
	if ts == nil {
		// treat nil like the empty Timestamp
		return time.Unix(0, 0).UTC()
	}
	return time.Unix(ts.Seconds, int64(ts.Nanoseconds)).UTC()
}