// generateLookupPaths returns a list path-prefixes for the input URL.
490568
func generateLookupPaths(urlStr string) ([]string, error) {
	const maxPathComponents = 4

	parsedURL, err := parseURL(urlStr)
	if err != nil {
		return nil, err
	}
	path := parsedURL.Path

	paths := []string{"/"}
	var pathComponents []string
	for _, p := range strings.Split(path, "/") {
		if p != "" {
			pathComponents = append(pathComponents, p)
		}
	}

	numComponents := len(pathComponents)
	if numComponents > maxPathComponents {
		numComponents = maxPathComponents
	}

	for i := 1; i < numComponents; i++ {
		paths = append(paths, "/"+strings.Join(pathComponents[:i], "/")+"/")
	}
	if path != "/" {
		paths = append(paths, path)
	}
	if len(parsedURL.RawQuery) > 0 {
		paths = append(paths, path+"?"+parsedURL.RawQuery)
	}
	return paths, nil
}
1135555
func (km *KeyManagerStandard) generateKeyMapForUsers(
	ctx context.Context, users []keybase1.UserOrTeamID,
	offline keybase1.OfflineAvailability) (
	kbfsmd.UserDevicePublicKeys, error) {
	keyMap := make(kbfsmd.UserDevicePublicKeys)

	// TODO: parallelize
	for _, w := range users {
		uid := w.AsUserOrBust() // only private TLFs should call this
		// HACK: clear cache
		km.config.KeybaseService().FlushUserFromLocalCache(ctx, uid)
		publicKeys, err := km.config.KBPKI().GetCryptPublicKeys(
			ctx, uid, offline)
		if err != nil {
			return nil, err
		}
		keyMap[uid] = make(kbfsmd.DevicePublicKeys)
		for _, key := range publicKeys {
			keyMap[uid][key] = true
		}
	}

	return keyMap, nil
}
971844
func (c *Context) URLPath(ppath string, args ...map[string]interface{}) string {
	if len(ppath) == 0 {
		if len(c.ControllerName) > 0 {
			ppath = c.ControllerName + `/`
		}
		ppath += c.ActionName
		return c.Application.URLBuilder.BuildFromPath(c.Module.Name+`/`+ppath, args...)
	}
	ppath = strings.TrimLeft(ppath, `/`)
	return c.Application.URLBuilder.BuildFromPath(c.Module.Name+`/`+ppath, args...)
}
432601
func generateMappings(appendCurrent bool) {
	hdr := "package main\n"

	initfn := `
	func init() {


	`
	t, err := bindgen.Parse(model, hdrfile)
	handleErr(err)

	var buf io.WriteCloser
	if appendCurrent {
		buf, err = os.OpenFile("mappings.go", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	} else {
		buf, err = os.OpenFile("mappings.go", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	}
	handleErr(err)
	defer buf.Close()

	if !appendCurrent {
		fmt.Fprintln(buf, hdr)
		bindgen.GenIgnored(buf, t, functions)
		fmt.Fprintln(buf, initfn)
		bindgen.GenNameMap(buf, t, "fnNameMap", processNameBasic, functions, true)
		bindgen.GenNameMap(buf, t, "enumMappings", processNameBasic, enums, true)

		generateCRUD(buf, t, "create")
		generateCRUD(buf, t, "set")
		generateCRUD(buf, t, "destroy")
		generateCRUD(buf, t, "methods")
		fmt.Fprintln(buf, "}\n")
	}
	generateAlphaBeta(buf, t)
	fmt.Fprintln(buf, initfn)
	fmt.Fprintln(buf, "}\n")
}
920708
func GenerateHashes(seed int64) (res [256]uint32) {
	random := rand.New(rand.NewSource(seed))
	used := make(map[uint32]bool)
	for i, _ := range res {
		x := uint32(random.Int63())
		for used[x] {
			x = uint32(random.Int63())
		}
		used[x] = true
		res[i] = x
	}
	return res
}
786945
func (r *ListUserSchedulesRequest) GenerateUrl() (string, url.Values, error) {
	baseUrl, params, err := r.Identifier.GenerateUrl()

	if err != nil {
		return "", nil, err
	}
	return baseUrl + "/schedules", params, err;
}
684833
func NewLookupParams(instance, service, domain string, entries chan<- *ServiceEntry) *LookupParams {
	return &LookupParams{
		*NewServiceRecord(instance, service, domain),
		entries,
	}
}
1368392
func GenerateDocs(curpath string) {
	fset := token.NewFileSet()

	f, err := parser.ParseFile(fset, filepath.Join(curpath, "routers", "router.go"), nil, parser.ParseComments)
	if err != nil {
		beeLogger.Log.Fatalf("Error while parsing router.go: %s", err)
	}

	rootapi.Infos = swagger.Information{}
	rootapi.SwaggerVersion = "2.0"

	// Analyse API comments
	if f.Comments != nil {
		for _, c := range f.Comments {
			for _, s := range strings.Split(c.Text(), "\n") {
				if strings.HasPrefix(s, "@APIVersion") {
					rootapi.Infos.Version = strings.TrimSpace(s[len("@APIVersion"):])
				} else if strings.HasPrefix(s, "@Title") {
					rootapi.Infos.Title = strings.TrimSpace(s[len("@Title"):])
				} else if strings.HasPrefix(s, "@Description") {
					rootapi.Infos.Description = strings.TrimSpace(s[len("@Description"):])
				} else if strings.HasPrefix(s, "@TermsOfServiceUrl") {
					rootapi.Infos.TermsOfService = strings.TrimSpace(s[len("@TermsOfServiceUrl"):])
				} else if strings.HasPrefix(s, "@Contact") {
					rootapi.Infos.Contact.EMail = strings.TrimSpace(s[len("@Contact"):])
				} else if strings.HasPrefix(s, "@Name") {
					rootapi.Infos.Contact.Name = strings.TrimSpace(s[len("@Name"):])
				} else if strings.HasPrefix(s, "@URL") {
					rootapi.Infos.Contact.URL = strings.TrimSpace(s[len("@URL"):])
				} else if strings.HasPrefix(s, "@LicenseUrl") {
					if rootapi.Infos.License == nil {
						rootapi.Infos.License = &swagger.License{URL: strings.TrimSpace(s[len("@LicenseUrl"):])}
					} else {
						rootapi.Infos.License.URL = strings.TrimSpace(s[len("@LicenseUrl"):])
					}
				} else if strings.HasPrefix(s, "@License") {
					if rootapi.Infos.License == nil {
						rootapi.Infos.License = &swagger.License{Name: strings.TrimSpace(s[len("@License"):])}
					} else {
						rootapi.Infos.License.Name = strings.TrimSpace(s[len("@License"):])
					}
				} else if strings.HasPrefix(s, "@Schemes") {
					rootapi.Schemes = strings.Split(strings.TrimSpace(s[len("@Schemes"):]), ",")
				} else if strings.HasPrefix(s, "@Host") {
					rootapi.Host = strings.TrimSpace(s[len("@Host"):])
				} else if strings.HasPrefix(s, "@SecurityDefinition") {
					if len(rootapi.SecurityDefinitions) == 0 {
						rootapi.SecurityDefinitions = make(map[string]swagger.Security)
					}
					var out swagger.Security
					p := getparams(strings.TrimSpace(s[len("@SecurityDefinition"):]))
					if len(p) < 2 {
						beeLogger.Log.Fatalf("Not enough params for security: %d\n", len(p))
					}
					out.Type = p[1]
					switch out.Type {
					case "oauth2":
						if len(p) < 6 {
							beeLogger.Log.Fatalf("Not enough params for oauth2: %d\n", len(p))
						}
						if !(p[3] == "implicit" || p[3] == "password" || p[3] == "application" || p[3] == "accessCode") {
							beeLogger.Log.Fatalf("Unknown flow type: %s. Possible values are `implicit`, `password`, `application` or `accessCode`.\n", p[1])
						}
						out.AuthorizationURL = p[2]
						out.Flow = p[3]
						if len(p)%2 != 0 {
							out.Description = strings.Trim(p[len(p)-1], `" `)
						}
						out.Scopes = make(map[string]string)
						for i := 4; i < len(p)-1; i += 2 {
							out.Scopes[p[i]] = strings.Trim(p[i+1], `" `)
						}
					case "apiKey":
						if len(p) < 4 {
							beeLogger.Log.Fatalf("Not enough params for apiKey: %d\n", len(p))
						}
						if !(p[3] == "header" || p[3] == "query") {
							beeLogger.Log.Fatalf("Unknown in type: %s. Possible values are `query` or `header`.\n", p[4])
						}
						out.Name = p[2]
						out.In = p[3]
						if len(p) > 4 {
							out.Description = strings.Trim(p[4], `" `)
						}
					case "basic":
						if len(p) > 2 {
							out.Description = strings.Trim(p[2], `" `)
						}
					default:
						beeLogger.Log.Fatalf("Unknown security type: %s. Possible values are `oauth2`, `apiKey` or `basic`.\n", p[1])
					}
					rootapi.SecurityDefinitions[p[0]] = out
				} else if strings.HasPrefix(s, "@Security") {
					if len(rootapi.Security) == 0 {
						rootapi.Security = make([]map[string][]string, 0)
					}
					rootapi.Security = append(rootapi.Security, getSecurity(s))
				}
			}
		}
	}
	// Analyse controller package
	for _, im := range f.Imports {
		localName := ""
		if im.Name != nil {
			localName = im.Name.Name
		}
		analyseControllerPkg(path.Join(curpath, "vendor"), localName, im.Path.Value)
	}
	for _, d := range f.Decls {
		switch specDecl := d.(type) {
		case *ast.FuncDecl:
			for _, l := range specDecl.Body.List {
				switch stmt := l.(type) {
				case *ast.AssignStmt:
					for _, l := range stmt.Rhs {
						if v, ok := l.(*ast.CallExpr); ok {
							// Analyze NewNamespace, it will return version and the subfunction
							selExpr, selOK := v.Fun.(*ast.SelectorExpr)
							if !selOK || selExpr.Sel.Name != "NewNamespace" {
								continue
							}
							version, params := analyseNewNamespace(v)
							if rootapi.BasePath == "" && version != "" {
								rootapi.BasePath = version
							}
							for _, p := range params {
								switch pp := p.(type) {
								case *ast.CallExpr:
									var controllerName string
									if selname := pp.Fun.(*ast.SelectorExpr).Sel.String(); selname == "NSNamespace" {
										s, params := analyseNewNamespace(pp)
										for _, sp := range params {
											switch pp := sp.(type) {
											case *ast.CallExpr:
												if pp.Fun.(*ast.SelectorExpr).Sel.String() == "NSInclude" {
													controllerName = analyseNSInclude(s, pp)
													if v, ok := controllerComments[controllerName]; ok {
														rootapi.Tags = append(rootapi.Tags, swagger.Tag{
															Name:        strings.Trim(s, "/"),
															Description: v,
														})
													}
												}
											}
										}
									} else if selname == "NSInclude" {
										controllerName = analyseNSInclude("", pp)
										if v, ok := controllerComments[controllerName]; ok {
											rootapi.Tags = append(rootapi.Tags, swagger.Tag{
												Name:        controllerName, // if the NSInclude has no prefix, we use the controllername as the tag
												Description: v,
											})
										}
									}
								}
							}
						}

					}
				}
			}
		}
	}
	os.Mkdir(path.Join(curpath, "swagger"), 0755)
	fd, err := os.Create(path.Join(curpath, "swagger", "swagger.json"))
	if err != nil {
		panic(err)
	}
	fdyml, err := os.Create(path.Join(curpath, "swagger", "swagger.yml"))
	if err != nil {
		panic(err)
	}
	defer fdyml.Close()
	defer fd.Close()
	dt, err := json.MarshalIndent(rootapi, "", "    ")
	dtyml, erryml := yaml.Marshal(rootapi)
	if err != nil || erryml != nil {
		panic(err)
	}
	_, err = fd.Write(dt)
	_, erryml = fdyml.Write(dtyml)
	if err != nil || erryml != nil {
		panic(err)
	}
}
71149
func (e *environ) MetadataLookupParams(region string) (*simplestreams.MetadataLookupParams, error) {
	var endpoint string
	if region == "" {
		region = e.cloud.Region
		endpoint = e.cloud.Endpoint
	} else {
		// TODO(axw) 2016-10-04 #1630089
		// MetadataLookupParams needs to be updated so that providers
		// are not expected to know how to map regions to endpoints.
		ec2Region, ok := aws.Regions[region]
		if !ok {
			return nil, errors.Errorf("unknown region %q", region)
		}
		endpoint = ec2Region.EC2Endpoint
	}
	return &simplestreams.MetadataLookupParams{
		Series:   config.PreferredSeries(e.ecfg()),
		Region:   region,
		Endpoint: endpoint,
	}, nil
}
317402
func (a *MandrillAPI) WebhookAdd(url string, events []string) (Webhook, error) {
	if url == "" {
		return Webhook{}, errors.New("url cannot be blank")
	}
	var params map[string]interface{} = make(map[string]interface{})
	params["url"] = url
	params["events"] = events
	return getWebhook(a, params, webhooks_add_endpoint)
}
1359301
func GenerateAddress(seed Trytes, index uint64, secLvl SecurityLevel, addChecksum ...bool) (Hash, error) {
	for len(seed)%81 != 0 {
		seed += "9"
	}

	if secLvl == 0 {
		secLvl = SecurityLevelMedium
	}

	subseed, err := Subseed(seed, index)
	if err != nil {
		return "", err
	}

	prvKey, err := Key(subseed, secLvl)
	if err != nil {
		return "", err
	}

	digests, err := Digests(prvKey)
	if err != nil {
		return "", err
	}

	addressTrits, err := Address(digests)
	if err != nil {
		return "", err
	}

	address := MustTritsToTrytes(addressTrits)

	if len(addChecksum) > 0 && addChecksum[0] {
		return checksum.AddChecksum(address, true, 9)
	}

	return address, nil
}
7986
func (pq *PriorityQueue) generatePrefix(level uint8) []byte {
	// priority + prefixSep = 1 + 1 = 2
	prefix := make([]byte, 2)
	prefix[0] = byte(level)
	prefix[1] = prefixSep[0]
	return prefix
}
117028
func (r *Consumer) nextLookupdEndpoint() string {
	r.mtx.RLock()
	if r.lookupdQueryIndex >= len(r.lookupdHTTPAddrs) {
		r.lookupdQueryIndex = 0
	}
	addr := r.lookupdHTTPAddrs[r.lookupdQueryIndex]
	num := len(r.lookupdHTTPAddrs)
	r.mtx.RUnlock()
	r.lookupdQueryIndex = (r.lookupdQueryIndex + 1) % num

	urlString := addr
	if !strings.Contains(urlString, "://") {
		urlString = "http://" + addr
	}

	u, err := url.Parse(urlString)
	if err != nil {
		panic(err)
	}
	if u.Path == "/" || u.Path == "" {
		u.Path = "/lookup"
	}

	v, err := url.ParseQuery(u.RawQuery)
	v.Add("topic", r.topic)
	u.RawQuery = v.Encode()
	return u.String()
}
914992
func GenerateMigration(mname, upsql, downsql, curpath string) {
	w := colors.NewColorWriter(os.Stdout)
	migrationFilePath := path.Join(curpath, DBPath, MPath)
	if _, err := os.Stat(migrationFilePath); os.IsNotExist(err) {
		// create migrations directory
		if err := os.MkdirAll(migrationFilePath, 0777); err != nil {
			beeLogger.Log.Fatalf("Could not create migration directory: %s", err)
		}
	}
	// create file
	today := time.Now().Format(MDateFormat)
	fpath := path.Join(migrationFilePath, fmt.Sprintf("%s_%s.go", today, mname))
	if f, err := os.OpenFile(fpath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err == nil {
		defer utils.CloseFile(f)
		ddlSpec := ""
		spec := ""
		up := ""
		down := ""
		if DDL != "" {
			ddlSpec = "m.ddlSpec()"
			switch strings.Title(DDL.String()) {
			case "Create":
				spec = strings.Replace(DDLSpecCreate, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
			case "Alter":
				spec = strings.Replace(DDLSpecAlter, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
			}
			spec = strings.Replace(spec, "{{tableName}}", mname, -1)
		} else {
			up = strings.Replace(MigrationUp, "{{UpSQL}}", upsql, -1)
			up = strings.Replace(up, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
			down = strings.Replace(MigrationDown, "{{DownSQL}}", downsql, -1)
			down = strings.Replace(down, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
		}

		header := strings.Replace(MigrationHeader, "{{StructName}}", utils.CamelCase(mname)+"_"+today, -1)
		header = strings.Replace(header, "{{ddlSpec}}", ddlSpec, -1)
		header = strings.Replace(header, "{{CurrTime}}", today, -1)
		f.WriteString(header + spec + up + down)
		// Run 'gofmt' on the generated source code
		utils.FormatSourceCode(fpath)
		fmt.Fprintf(w, "\t%s%screate%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", fpath, "\x1b[0m")
	} else {
		beeLogger.Log.Fatalf("Could not create migration file: %s", err)
	}
}
714371
func generateKeyPairs() ([]byte, []byte, error) {
	str := util.RandomHexString()
	public, private, err := crypto.ED25519GenerateKey(str)
	return public, private, err
}
121070
func (gce *Cloud) ListURLMaps() (*compute.UrlMapList, error) {
	// TODO: use PageToken to list all not just the first 500
	return gce.service.UrlMaps.List(gce.projectID).Do()
}
1330588
func PathHasPrefix(s, prefix string) bool {
	s = normalizePath(s)
	prefix = normalizePath(prefix)
	if s == prefix {
		return true
	}
	if !strings.HasSuffix(prefix, "/") {
		prefix += "/"
	}
	return s == prefix || strings.HasPrefix(s, prefix)
}