// Generate is just like New, but generates a new X resource id for you.
// Geom is initialized to (0, 0) 1x1.
// It is possible for id generation to return an error, in which case, an
// error is returned here.
962388
func Generate(xu *xgbutil.XUtil) (*Window, error) {
	wid, err := xproto.NewWindowId(xu.Conn())
	if err != nil {
		return nil, err
	}
	return New(xu, wid), nil
}
175094
func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
	o := rpt.options

	switch o.OutputFormat {
	case Dot:
		return printDOT(w, rpt)
	case Tree:
		return printTree(w, rpt)
	case Text:
		return printText(w, rpt)
	case JSON:
		return printJSON(w, rpt)
	case Raw:
		fmt.Fprint(w, rpt.prof.String())
		return nil
	case Tags:
		return printTags(w, rpt)
	case Proto:
		return rpt.prof.Write(w)
	case Dis:
		return printAssembly(w, rpt, obj)
	case List:
		return printSource(w, rpt)
	case WebList:
		return printWebSource(w, rpt, obj)
	case Callgrind:
		return printCallgrind(w, rpt)
	}
	return fmt.Errorf("unexpected output format")
}
1099817
func (eg *exampleGenerator) Generate(seen []string) interface{} {
	// Randomize array length first, since that's from higher level
	if eg.hasLengthValidation() {
		return eg.generateValidatedLengthExample(seen)
	}
	// Enum should dominate, because the potential "examples" are fixed
	if eg.hasEnumValidation() {
		return eg.generateValidatedEnumExample()
	}
	// loop until a satisified example is generated
	hasFormat, hasPattern, hasMinMax := eg.hasFormatValidation(), eg.hasPatternValidation(), eg.hasMinMaxValidation()
	attempts := 0
	for attempts < maxAttempts {
		attempts++
		var example interface{}
		// Format comes first, since it initiates the example
		if hasFormat {
			example = eg.generateFormatExample()
		}
		// now validate with the rest of matchers; if not satisified, redo
		if hasPattern {
			if example == nil {
				example = eg.generateValidatedPatternExample()
			} else if !eg.checkPatternValidation(example) {
				continue
			}
		}
		if hasMinMax {
			if example == nil {
				example = eg.generateValidatedMinMaxValueExample()
			} else if !eg.checkMinMaxValueValidation(example) {
				continue
			}
		}
		if example == nil {
			example = eg.a.Type.GenerateExample(eg.r, seen)
		}
		return example
	}
	return eg.a.Type.GenerateExample(eg.r, seen)
}
1049049
func (o *object) generate(dir string) error {
	o.handleAdvancedType()

	// generate enums
	for _, f := range o.Fields {
		if f.Enum != nil {
			if err := f.Enum.generate(dir); err != nil {
				return err
			}
		}
	}

	if o.Enum != nil {
		return o.Enum.generate(dir)
	}
	filename := filepath.Join(dir, o.Name()+".nim")
	if err := commons.GenerateFile(o, "./templates/nim/object_nim.tmpl", "object_nim", filename, true); err != nil {
		return err
	}
	return nil
}
1313024
func (gl *goLibrary) generate() error {
	// generate all Type structs
	if err := generateStructs(gl.Types, gl.targetDir()); err != nil {
		return err
	}

	// security schemes
	if err := generateSecurity(gl.SecuritySchemes, gl.targetDir(), gl.PackageName); err != nil {
		return err
	}

	// included libraries
	for name, ramlLib := range gl.Libraries {
		childLib := newGoLibrary(name, ramlLib, gl.targetDir(), gl.rootTargetDir, globLibRootURLs)
		if err := childLib.generate(); err != nil {
			return err
		}
	}
	return nil
}
423629
func (g *GifGenerator) Generate(input string, output string) (err error) {
	// virtual terminal
	var state = terminal.State{}
	vt, err := terminal.Create(&state, ioutil.NopCloser(bytes.NewBuffer([]byte{})))
	if err != nil {
		return
	}
	defer vt.Close()
	vt.Resize(g.Col, g.Row)

	// play and capture
	var (
		images []*image.Paletted
		delays []int
	)
	err = g.TtyPlay(input, vt, func(diff int32) (err error) {
		delay := int(float64(diff)/g.Speed) / 10000
		if delay > 0 {
			var img *image.Paletted
			img, err = g.Capture(&state)
			if err != nil {
				return
			}
			images = append(images, img)
			delays = append(delays, delay)
		}
		return nil
	})
	if err != nil {
		return
	}

	// generate gif file
	outFile, err := os.Create(output)
	if err != nil {
		return
	}
	defer outFile.Close()
	opts := gif.GIF{
		Image: images,
		Delay: delays,
	}
	if g.NoLoop {
		opts.LoopCount = 1
	}
	err = gif.EncodeAll(outFile, &opts)
	if err != nil {
		return
	}
	return nil
}
281679
func Generate() (files []string, err error) {
	var outDir, ver string
	set := flag.NewFlagSet("app", flag.PanicOnError)
	set.StringVar(&outDir, "out", "", "")
	set.StringVar(&ver, "version", "", "")
	set.String("design", "", "")
	set.Parse(os.Args[1:])

	if err := codegen.CheckVersion(ver); err != nil {
		return nil, err
	}

	g := &Generator{OutDir: outDir, API: design.Design}

	return g.Generate()
}
1354648
func generate(api *raml.APIDefinition, genFile string) {

	f, err := os.Create(genFile)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	// Write the header - import statements and root handler.
	f.WriteString(handlerHead)
	// Start the route map (string to handler).
	f.WriteString(mapStart)
	// Add the route map entries.
	e := template.Must(template.New("mapEntry").Parse(mapEntry))
	for name, resource := range api.Resources {
		generateMap("", name, &resource, e, f)
	}
	// Close the route map.
	f.WriteString(mapEnd)
	// Now add the HTTP handlers.
	t := template.Must(template.New("handlerText").Parse(handlerText))
	for name, resource := range api.Resources {
		generateResource("", name, &resource, t, f)
	}
	format(f)
}
495699
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	codegen.Reserved[g.Target] = true

	os.RemoveAll(g.OutDir)

	if err := os.MkdirAll(g.OutDir, 0755); err != nil {
		return nil, err
	}
	g.genfiles = []string{g.OutDir}
	if err := g.generateContexts(); err != nil {
		return nil, err
	}
	if err := g.generateControllers(); err != nil {
		return nil, err
	}
	if err := g.generateSecurity(); err != nil {
		return nil, err
	}
	if err := g.generateHrefs(); err != nil {
		return nil, err
	}
	if err := g.generateMediaTypes(); err != nil {
		return nil, err
	}
	if err := g.generateUserTypes(); err != nil {
		return nil, err
	}
	if !g.NoTest {
		if err := g.generateResourceTest(); err != nil {
			return nil, err
		}
	}

	return g.genfiles, nil
}
540750
func (sd structDef) generate(dir string) error {
	// generate enums
	for _, f := range sd.Fields {
		if f.Enum != nil {
			if err := f.Enum.generate(dir); err != nil {
				return err
			}
		}
	}
	if sd.Enum != nil {
		return sd.Enum.generate(dir)
	}
	fileName := filepath.Join(dir, sd.Name+".go")
	return commons.GenerateFile(sd, structTemplateLocation, "struct_template", fileName, true)
}
1250609
func (s *SetupService) Generate(ctx context.Context, or *platform.OnboardingRequest) (*platform.OnboardingResults, error) {
	u, err := newURL(s.Addr, setupPath)
	if err != nil {
		return nil, err
	}
	octets, err := json.Marshal(or)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", u.String(), bytes.NewReader(octets))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	hc := newClient(u.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	// TODO(jsternberg): Should this check for a 201 explicitly?
	if err := CheckError(resp, true); err != nil {
		return nil, err
	}

	var oResp onboardingResponse
	if err := json.NewDecoder(resp.Body).Decode(&oResp); err != nil {
		return nil, err
	}

	bkt, err := oResp.Bucket.toPlatform()
	if err != nil {
		return nil, err
	}
	return &platform.OnboardingResults{
		Org:    &oResp.Organization.Organization,
		User:   &oResp.User.User,
		Auth:   oResp.Auth.toPlatform(),
		Bucket: bkt,
	}, nil
}
615706
func (c Client) Generate(dir string) error {
	globAPIDef = c.APIDef

	// generate helper
	if err := commons.GenerateFile(nil, "./templates/python/client_utils_python.tmpl", "client_utils_python", filepath.Join(dir, "client_utils.py"), true); err != nil {
		return err
	}

	// generate http client
	if err := commons.GenerateFile(nil, c.Template.httpClientFile, c.Template.httpClientName, filepath.Join(dir, "http_client.py"), true); err != nil {
		return err
	}

	if err := c.generateServices(dir); err != nil {
		return err
	}

	if err := c.generateSecurity(dir); err != nil {
		return err
	}

	// python classes
	classes, err := GenerateAllClasses(c.APIDef, dir, false)
	if err != nil {
		return err
	}

	// helper for python classes
	if err := commons.GenerateFile(nil, "./templates/python/client_support.tmpl",
		"client_support", filepath.Join(dir, "client_support.py"), true); err != nil {
		return err
	}

	if c.UnmarshallResponse {
		if err := commons.GenerateFile(nil, "./templates/python/unmarshall_error.tmpl",
			"unmarshall_error", filepath.Join(dir, "unmarshall_error.py"), true); err != nil {
			return err
		}
		if err := commons.GenerateFile(nil, "./templates/python/unhandled_api_error.tmpl",
			"unhandled_api_error", filepath.Join(dir, "unhandled_api_error.py"), true); err != nil {
			return err
		}
	}

	sort.Strings(classes)
	c.Classes = classes
	return commons.GenerateFile(c, c.Template.initFile, c.Template.initName, filepath.Join(dir, "__init__.py"), true)
}
241
func Generate(pidfile string, chDel <-chan struct{}) error {
	f, err := os.OpenFile(pidfile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer f.Close()
	fmt.Fprintln(f, os.Getpid())
	if chDel != nil {
		go func() {
			select {
			case <-chDel:
				os.Remove(pidfile)
			}
		}()
	}
	return nil
}
1267592
func (id *InsertIDGenerator) Generate() string {
	prefix := id.Prefix
	if prefix == "" {
		prefix = defaultPrefix
	}
	c := atomic.AddInt64(&id.Counter, 1)
	return fmt.Sprintf("%s:%d", prefix, c)
}
1032154
func Generate() (u UUID) {
	const (
		// ensures we backoff for less than 450ms total. Use the following to
		// select new value, in units of 10ms:
		// 	n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
		maxretries = 9
		backoff    = time.Millisecond * 10
	)

	var (
		totalBackoff time.Duration
		count        int
		retries      int
	)

	for {
		// This should never block but the read may fail. Because of this,
		// we just try to read the random number generator until we get
		// something. This is a very rare condition but may happen.
		b := time.Duration(retries) * backoff
		time.Sleep(b)
		totalBackoff += b

		n, err := io.ReadFull(rand.Reader, u[count:])
		if err != nil {
			if retryOnError(err) && retries < maxretries {
				count += n
				retries++
				Loggerf("error generating version 4 uuid, retrying: %v", err)
				continue
			}

			// Any other errors represent a system problem. What did someone
			// do to /dev/urandom?
			panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
		}

		break
	}

	u[6] = (u[6] & 0x0f) | 0x40 // set version byte
	u[8] = (u[8] & 0x3f) | 0x80 // set high order byte 0b10{8,9,a,b}

	return u
}
908439
func Generate(apiDef *raml.APIDefinition, ramlFile string, ramlBytes []byte,
	dir string, libRootURLs []string) error {
	// extract zipped files
	if err := extract(dir); err != nil {
		return err
	}
	ramlBytes = append([]byte("#%RAML 1.0\n"), ramlBytes...)

	// write the main .raml file
	if err := ioutil.WriteFile(filepath.Join(dir, "api.raml"), ramlBytes, 0777); err != nil {
		return err
	}

	// copy all libraries files
	return copyLibrariesFiles(apiDef.Uses, apiDef.Libraries, ramlFile, dir, libRootURLs)
}
771974
func (m *Generator) Generate() ([]string, error) {
	// Sanity checks
	if m.OutDir == "" {
		return nil, fmt.Errorf("missing output directory flag")
	}
	if m.DesignPkgPath == "" {
		return nil, fmt.Errorf("missing design package flag")
	}

	// Create output directory
	if err := os.MkdirAll(m.OutDir, 0755); err != nil {
		return nil, err
	}

	// Create temporary workspace used for generation
	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	tmpDir, err := ioutil.TempDir(wd, "goagen")
	if err != nil {
		if _, ok := err.(*os.PathError); ok {
			err = fmt.Errorf(`invalid output directory path "%s"`, m.OutDir)
		}
		return nil, err
	}
	defer func() {
		if !m.debug {
			os.RemoveAll(tmpDir)
		}
	}()
	if m.debug {
		fmt.Printf("** Code generator source dir: %s\n", tmpDir)
	}

	pkgSourcePath, err := codegen.PackageSourcePath(m.DesignPkgPath)
	if err != nil {
		return nil, fmt.Errorf("invalid design package import path: %s", err)
	}
	pkgName, err := codegen.PackageName(pkgSourcePath)
	if err != nil {
		return nil, err
	}

	// Generate tool source code.
	pkgPath := filepath.Join(tmpDir, pkgName)
	p, err := codegen.PackageFor(pkgPath)
	if err != nil {
		return nil, err
	}
	m.generateToolSourceCode(p)

	// Compile and run generated tool.
	if m.debug {
		fmt.Printf("** Compiling with:\n%s", strings.Join(os.Environ(), "\n"))
	}
	genbin, err := p.Compile("goagen")
	if err != nil {
		return nil, err
	}
	return m.spawn(genbin)
}