// main routine to carve a file
424236
func carveFile(datafile string, offset int64, limit int) {
	chunkCnt := 0
	f, err := os.Open(datafile)
	if err != nil {
		log.LogErrorAndExit(err)
	}
	defer f.Close()
	f.Seek(offset, os.SEEK_SET)
	dup, err := os.Open(datafile)
	if err != nil {
		log.LogErrorAndExit(err)
	}
	defer dup.Close()
	dup.Seek(offset, os.SEEK_SET)

	for offset := range findChunksOffsets(f) {
		log.Infof("Parsing Chunk @ Offset: %d (0x%08[1]x)", offset)
		chunk, err := fetchChunkFromReader(dup, offset)
		if err != nil {
			log.LogError(err)
		}
		for e := range chunk.Events() {
			printEvent(e)
		}
		chunkCnt++

		if limit > 0 && chunkCnt >= limit {
			break
		}
		log.Debug("End of the loop")
	}
}
214632
func main() {
	CheckArgs("<path>")
	path := os.Args[1]

	// We instance\iate a new repository targeting the given path (the .git folder)
	r, err := git.PlainOpen(path)
	CheckIfError(err)

	// Get the working directory for the repository
	w, err := r.Worktree()
	CheckIfError(err)

	// Pull the latest changes from the origin remote and merge into the current branch
	Info("git pull origin")
	err = w.Pull(&git.PullOptions{RemoteName: "origin"})
	CheckIfError(err)

	// Print the latest commit that was just pulled
	ref, err := r.Head()
	CheckIfError(err)
	commit, err := r.CommitObject(ref.Hash())
	CheckIfError(err)

	fmt.Println(commit)
}
569881
func (cnf *Mycnf) makeMycnf(cnfFiles []string) (string, error) {
	myTemplateSource := new(bytes.Buffer)
	myTemplateSource.WriteString("[mysqld]\n")
	for _, path := range cnfFiles {
		data, dataErr := ioutil.ReadFile(path)
		if dataErr != nil {
			return "", dataErr
		}
		myTemplateSource.WriteString("## " + path + "\n")
		myTemplateSource.Write(data)
	}
	return cnf.fillMycnfTemplate(myTemplateSource.String())
}
488254
func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: demux <file.wav>\n")
		os.Exit(1)
	}

	testInfo, err := os.Stat(os.Args[1])
	checkErr(err)

	testWav, err := os.Open(os.Args[1])
	checkErr(err)

	wavReader, err := wav.NewReader(testWav, testInfo.Size())
	checkErr(err)

	fileMeta := wavReader.GetFile()
	fmt.Println(dump(fileMeta))

	if fileMeta.Channels != 2 {
		log.Fatal("Please use a 2-channel audio file")
	}

	// A slice of many 1-4 byte samples
	var left [][]byte
	left = make([][]byte, fileMeta.NumberOfSamples/2)

	var i uint32
	var buf []byte
	for i = 0; i < fileMeta.NumberOfSamples/2; i++ {

		buf, err = wavReader.ReadRawSample()
		checkErr(err)
		left[i] = buf

		// Throw the right-channel away
		_, err = wavReader.ReadRawSample()
		checkErr(err)
	}

	filename := "mono-" + testInfo.Name()
	os.Remove(filename)

	f, err := os.Create(filename)
	checkErr(err)

	// Create the headers for our new mono file
	meta := wav.File{
		Channels:        1,
		SampleRate:      fileMeta.SampleRate,
		SignificantBits: fileMeta.SignificantBits,
	}

	writer, err := meta.NewWriter(f)
	checkErr(err)

	// Write to file
	for _, sample := range left {
		err = writer.WriteSample(sample)
		checkErr(err)
	}

	err = writer.Close()
	checkErr(err)

	fmt.Println("Created Mono File", f.Name())

	f, err = os.Open(f.Name())
	checkErr(err)

	stat, err := f.Stat()
	checkErr(err)

	wavReader, err = wav.NewReader(f, stat.Size())
	checkErr(err)

	fileMeta = wavReader.GetFile()
	fmt.Println(dump(fileMeta))
}
227578
func main() {
	if reexec.Init() {
		return
	}

	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(os.Stderr, "initc: panicked: %s\n", r)
			os.Exit(4)
		}
	}()

	rootFsPath := flag.String("root", "", "Path for the root file system directory")
	configFilePath := flag.String("config", "./etc/config", "Path for the configuration file")
	title := flag.String("title", "", "")
	cflager.AddFlags(flag.CommandLine)
	flag.Parse()

	if *rootFsPath == "" {
		missing("--root")
	}

	syncReader := os.NewFile(uintptr(3), "/dev/a")
	defer syncReader.Close()
	syncWriter := os.NewFile(uintptr(4), "/dev/d")
	defer syncWriter.Close()

	sync := &containerizer.PipeSynchronizer{
		Reader: syncReader,
		Writer: syncWriter,
	}

	if err := sync.Wait(2 * time.Minute); err != nil {
		fail(fmt.Sprintf("initc: wait for host: %s", err), 8)
	}

	env, err := process.EnvFromFile(*configFilePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "initc: failed to get env from config file: %s\n", err)
		os.Exit(3)
	}

	dropCapabilities := env["root_uid"] != "0"
	procMountFlags := syscall.MS_NOSUID | syscall.MS_NODEV | syscall.MS_NOEXEC
	sysMountFlags := syscall.MS_NOSUID | syscall.MS_NODEV | syscall.MS_NOEXEC | syscall.MS_RDONLY

	if dropCapabilities {
		procMountFlags = procMountFlags | syscall.MS_RDONLY
	}

	initializer := &system.Initializer{
		Steps: []system.StepRunner{
			&containerizer.FuncStep{system.Mount{
				Type:       system.Tmpfs,
				Flags:      syscall.MS_NODEV,
				TargetPath: "/dev/shm",
			}.Mount},
			&containerizer.FuncStep{system.Mount{
				Type:       system.Proc,
				Flags:      procMountFlags,
				TargetPath: "/proc",
			}.Mount},
			&containerizer.FuncStep{system.Mount{
				Type:       system.Sys,
				Flags:      sysMountFlags,
				TargetPath: "/sys",
			}.Mount},
			&containerizer.FuncStep{system.Mount{
				Type:       system.Devpts,
				TargetPath: "/dev/pts",
				Data:       "newinstance,ptmxmode=0666",
			}.Mount},
			&containerizer.FuncStep{system.Unmount{
				Dir: "/tmp/garden-host",
			}.Unmount},
			&containerizer.FuncStep{func() error {
				return setupNetwork(env)
			}},
			&containerizer.CapabilitiesStep{
				Drop:         dropCapabilities,
				Capabilities: &sys.ProcessCapabilities{Pid: os.Getpid()},
			},
		},
	}

	containerizer := containerizer.Containerizer{
		RootfsPath:           *rootFsPath,
		ContainerInitializer: initializer,
		Waiter:               sync,
		Signaller:            sync,
	}

	if err := containerizer.Init(); err != nil {
		fail(fmt.Sprintf("failed to init containerizer: %s", err), 2)
	}

	syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(4), syscall.F_SETFD, 0)
	syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(5), syscall.F_SETFD, 0)

	if err := syscall.Exec("/proc/self/exe", []string{"initd", fmt.Sprintf("-dropCapabilities=%t", dropCapabilities), fmt.Sprintf("-title=\"%s\"", *title)}, os.Environ()); err != nil {
		fail(fmt.Sprintf("failed to reexec: %s", err), 3)
	}
}
1330904
func main() {
	env, err := plugins.NewEnvironment()
	env.RespondAndExitIfError(err)

	packageName, err := resolvePackageName(env.Request.OutputPath)
	env.RespondAndExitIfError(err)

	// Use the name used to run the plugin to decide which files to generate.
	var files []string
	switch {
	case strings.Contains(env.Invocation, "gnostic-go-client"):
		files = []string{"client.go", "types.go", "constants.go"}
	case strings.Contains(env.Invocation, "gnostic-go-server"):
		files = []string{"server.go", "provider.go", "types.go", "constants.go"}
	default:
		files = []string{"client.go", "server.go", "provider.go", "types.go", "constants.go"}
	}

	for _, model := range env.Request.Models {
		switch model.TypeUrl {
		case "surface.v1.Model":
			surfaceModel := &surface.Model{}
			err = proto.Unmarshal(model.Value, surfaceModel)
			if err == nil {
				// Customize the code surface model for Go
				NewGoLanguageModel().Prepare(surfaceModel)

				modelJSON, _ := json.MarshalIndent(surfaceModel, "", "  ")
				modelFile := &plugins.File{Name: "model.json", Data: modelJSON}
				env.Response.Files = append(env.Response.Files, modelFile)

				// Create the renderer.
				renderer, err := NewServiceRenderer(surfaceModel)
				renderer.Package = packageName
				env.RespondAndExitIfError(err)

				// Run the renderer to generate files and add them to the response object.
				err = renderer.Render(env.Response, files)
				env.RespondAndExitIfError(err)

				// Return with success.
				env.RespondAndExit()
			}
		}
	}
	err = errors.New("No generated code surface model is available.")
	env.RespondAndExitIfError(err)
}
781815
func main() {
    fs, _ := ioutil.ReadDir(".")
    out, _ := os.Create("textfiles.go")
    out.Write([]byte("package nameGen \n\nvar (\n"))
    for _, f := range fs {
        if strings.HasSuffix(f.Name(), ".txt") {
            lines, _ := readFile(f.Name())
            out.Write([]byte(strings.TrimSuffix(f.Name(), ".txt") + " = [" + strconv.Itoa(len(lines)) + "]string {"))
            for _, line := range lines {
              out.Write([]byte("`" + line + "`,"))
            }
            out.Write([]byte("}\n"))
        }
    }
    out.Write([]byte(")\n"))
}
456154
func (r *patternPainter) Paint(ss []raster.Span, done bool) {
	b := r.im.Bounds()
	for _, s := range ss {
		if s.Y < b.Min.Y {
			continue
		}
		if s.Y >= b.Max.Y {
			return
		}
		if s.X0 < b.Min.X {
			s.X0 = b.Min.X
		}
		if s.X1 > b.Max.X {
			s.X1 = b.Max.X
		}
		if s.X0 >= s.X1 {
			continue
		}
		const m = 1<<16 - 1
		y := s.Y - r.im.Rect.Min.Y
		x0 := s.X0 - r.im.Rect.Min.X
		// RGBAPainter.Paint() in $GOPATH/src/github.com/golang/freetype/raster/paint.go
		i0 := (s.Y-r.im.Rect.Min.Y)*r.im.Stride + (s.X0-r.im.Rect.Min.X)*4
		i1 := i0 + (s.X1-s.X0)*4
		for i, x := i0, x0; i < i1; i, x = i+4, x+1 {
			ma := s.Alpha
			if r.mask != nil {
				ma = ma * uint32(r.mask.AlphaAt(x, y).A) / 255
				if ma == 0 {
					continue
				}
			}
			c := r.p.ColorAt(x, y)
			cr, cg, cb, ca := c.RGBA()
			dr := uint32(r.im.Pix[i+0])
			dg := uint32(r.im.Pix[i+1])
			db := uint32(r.im.Pix[i+2])
			da := uint32(r.im.Pix[i+3])
			a := (m - (ca * ma / m)) * 0x101
			r.im.Pix[i+0] = uint8((dr*a + cr*ma) / m >> 8)
			r.im.Pix[i+1] = uint8((dg*a + cg*ma) / m >> 8)
			r.im.Pix[i+2] = uint8((db*a + cb*ma) / m >> 8)
			r.im.Pix[i+3] = uint8((da*a + ca*ma) / m >> 8)
		}
	}
}
1116801
func (f Frame) file() string {
	fn := runtime.FuncForPC(f.pc())
	if fn == nil {
		return "unknown"
	}
	file, _ := fn.FileLine(f.pc())
	return file
}
228165
func main() {
	loggingConfig := &LoggingConfig{
		RootSink: Sink().
			AddSinks(
				// Log everything to Stderr
				Sink().SetOutput(StderrOutput()),
				Sink().SetTransform(FilterTransform(ExcludeWhenAllMatch,
					"module", "p2p",
					"captured_logging_source", "tendermint_log15")).
					AddSinks(
						Sink().SetOutput(StdoutOutput()),
					),
			),
	}
	fmt.Println(loggingConfig.RootTOMLString())
}
855419
func main() {
	if len(os.Args) != 4 {
		fmt.Fprintf(os.Stderr, "expected 3 arguments, got %d\n", len(os.Args)-1)
		exit.Exit(1)
	}

	// No error checking here, it's a contrived example after all.
	a, _ := strconv.Atoi(os.Args[2])
	b, _ := strconv.Atoi(os.Args[3])

	var op func(int, int) int
	switch os.Args[1] {
	case "add":
		op = add
	case "sub":
		op = sub
	default:
		fmt.Fprintf(os.Stderr, "unknown operation: %s\n", os.Args[1])
		exit.Exit(1)
	}

	fmt.Println(op(a, b))
}
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)
	}
}
11203
func main() {
	rootDir := "."
	root := tview.NewTreeNode(rootDir).
		SetColor(tcell.ColorRed)
	tree := tview.NewTreeView().
		SetRoot(root).
		SetCurrentNode(root)

	// A helper function which adds the files and directories of the given path
	// to the given target node.
	add := func(target *tview.TreeNode, path string) {
		files, err := ioutil.ReadDir(path)
		if err != nil {
			panic(err)
		}
		for _, file := range files {
			node := tview.NewTreeNode(file.Name()).
				SetReference(filepath.Join(path, file.Name())).
				SetSelectable(file.IsDir())
			if file.IsDir() {
				node.SetColor(tcell.ColorGreen)
			}
			target.AddChild(node)
		}
	}

	// Add the current directory to the root node.
	add(root, rootDir)

	// If a directory was selected, open it.
	tree.SetSelectedFunc(func(node *tview.TreeNode) {
		reference := node.GetReference()
		if reference == nil {
			return // Selecting the root node does nothing.
		}
		children := node.GetChildren()
		if len(children) == 0 {
			// Load and show files in this directory.
			path := reference.(string)
			add(node, path)
		} else {
			// Collapse if visible, expand if collapsed.
			node.SetExpanded(!node.IsExpanded())
		}
	})

	if err := tview.NewApplication().SetRoot(tree, true).Run(); err != nil {
		panic(err)
	}
}
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
}
88374
func main() {
	env, err := plugins.NewEnvironment()
	env.RespondAndExitIfError(err)
	code := &printer.Code{}
	for _, model := range env.Request.Models {
		log.Printf("model %s", model.TypeUrl)
		switch model.TypeUrl {
		case "openapi.v2.Document":
			documentv2 := &openapiv2.Document{}
			err = proto.Unmarshal(model.Value, documentv2)
			if err == nil {
				printDocumentV2(code, documentv2)
			}
		case "openapi.v3.Document":
			documentv3 := &openapiv3.Document{}
			err = proto.Unmarshal(model.Value, documentv3)
			if err == nil {
				printDocumentV3(code, documentv3)
			}
		}
	}
	file := &plugins.File{
		Name: "summary.txt",
		Data: []byte(code.String()),
	}
	env.Response.Files = append(env.Response.Files, file)
	env.RespondAndExit()
}
752619
func MakeFileFunc(baseDir string, encBase64 bool) function.Function {
	return function.New(&function.Spec{
		Params: []function.Parameter{
			{
				Name: "path",
				Type: cty.String,
			},
		},
		Type: function.StaticReturnType(cty.String),
		Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
			path := args[0].AsString()
			src, err := readFileBytes(baseDir, path)
			if err != nil {
				return cty.UnknownVal(cty.String), err
			}

			switch {
			case encBase64:
				enc := base64.StdEncoding.EncodeToString(src)
				return cty.StringVal(enc), nil
			default:
				if !utf8.Valid(src) {
					return cty.UnknownVal(cty.String), fmt.Errorf("contents of %s are not valid UTF-8; use the filebase64 function to obtain the Base64 encoded contents or the other file functions (e.g. filemd5, filesha256) to obtain file hashing results instead", path)
				}
				return cty.StringVal(string(src)), nil
			}
		},
	})
}
807644
func main() {

	fmt.Println("--- Begin Example One ---")
	exampleOne()
	fmt.Println("--- End Example One ---")

	fmt.Println("--- Begin Example Two ---")
	exampleTwo()
	fmt.Println("--- End Example Two ---")

	fmt.Println("--- Begin Example Three ---")
	exampleThree()
	fmt.Println("--- End Example Three ---")

	fmt.Println("--- Begin Example Four ---")
	exampleFour()
	fmt.Println("--- End Example Four ---")

	fmt.Println("--- Begin Example Five ---")
	exampleFive()
	fmt.Println("--- End Example Five ---")

	fmt.Println("--- Begin Example Six ---")
	exampleSix()
	fmt.Println("--- End Example Six ---")

}