// NOTE: OS X provides GAP and GATT services, and they can't be customized.
// For Linux/Embedded, however, this is something we want to fully control.
358898
func NewGattService() *gatt.Service {
	s := gatt.NewService(attrGATTUUID)
	s.AddCharacteristic(attrServiceChangedUUID).HandleNotifyFunc(
		func(r gatt.Request, n gatt.Notifier) {
			go func() {
				log.Printf("TODO: indicate client when the services are changed")
			}()
		})
	return s
}
1062242
func (x *genRunner) xtraSM(varname string, t reflect.Type, encode, isptr bool) {
	var ptrPfx, addrPfx string
	if isptr {
		ptrPfx = "*"
	} else {
		addrPfx = "&"
	}
	if encode {
		x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname)
	} else {
		x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname)
	}
	x.registerXtraT(t)
}
656513
func init() {
	GPort = os.Getenv("PORT")
	if GPort == "" {
		GPort = devPort
		GAppUrl = devAppUrl + ":" + GPort
		log.Println("Dev Environnement detected")
	} else {
		GAppUrl = prodAppUrl
		log.Println("Heroku Environement detected")
	}
}
470229
func PortToHostIPMAC(port, subnet int) (string, string) {
	b0 := subnet >> 24
	b1 := (subnet >> 16) & 0xff
	b2 := (port >> 8) & 0xff
	b3 := port & 0xff
	ipStr := fmt.Sprintf("%d.%d.%d.%d/16", b0, b1, b2, b3)
	macStr := fmt.Sprintf("02:02:%02x:%02x:%02x:%02x", b0, b1, b2, b3)

	return ipStr, macStr
}
1171529
func (s *HostService) GetHostTagID(keyword string, opts ...OptionFunc) (string, int, error) {
	p := &ListHostTagsParams{}
	p.p = make(map[string]interface{})

	p.p["keyword"] = keyword

	for _, fn := range append(s.cs.options, opts...) {
		if err := fn(s.cs, p); err != nil {
			return "", -1, err
		}
	}

	l, err := s.ListHostTags(p)
	if err != nil {
		return "", -1, err
	}

	if l.Count == 0 {
		return "", l.Count, fmt.Errorf("No match found for %s: %+v", keyword, l)
	}

	if l.Count == 1 {
		return l.HostTags[0].Id, l.Count, nil
	}

	if l.Count > 1 {
		for _, v := range l.HostTags {
			if v.Name == keyword {
				return v.Id, l.Count, nil
			}
		}
	}
	return "", l.Count, fmt.Errorf("Could not find an exact match for %s: %+v", keyword, l)
}
409766
func PgTriggersByTgconstraint(db XODB, tgconstraint pgtypes.Oid) ([]*PgTrigger, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, oid, ctid, tgrelid, tgname, tgfoid, tgtype, tgenabled, tgisinternal, tgconstrrelid, tgconstrindid, tgconstraint, tgdeferrable, tginitdeferred, tgnargs, tgattr, tgargs, tgqual ` +
		`FROM pg_catalog.pg_trigger ` +
		`WHERE tgconstraint = $1`

	// run query
	XOLog(sqlstr, tgconstraint)
	q, err := db.Query(sqlstr, tgconstraint)
	if err != nil {
		return nil, err
	}
	defer q.Close()

	// load results
	res := []*PgTrigger{}
	for q.Next() {
		pt := PgTrigger{}

		// scan
		err = q.Scan(&pt.Tableoid, &pt.Cmax, &pt.Xmax, &pt.Cmin, &pt.Xmin, &pt.Oid, &pt.Ctid, &pt.Tgrelid, &pt.Tgname, &pt.Tgfoid, &pt.Tgtype, &pt.Tgenabled, &pt.Tgisinternal, &pt.Tgconstrrelid, &pt.Tgconstrindid, &pt.Tgconstraint, &pt.Tgdeferrable, &pt.Tginitdeferred, &pt.Tgnargs, &pt.Tgattr, &pt.Tgargs, &pt.Tgqual)
		if err != nil {
			return nil, err
		}

		res = append(res, &pt)
	}

	return res, nil
}
807671
func XGoogHeader(keyval ...string) string {
	if len(keyval) == 0 {
		return ""
	}
	if len(keyval)%2 != 0 {
		panic("gax.Header: odd argument count")
	}
	var buf bytes.Buffer
	for i := 0; i < len(keyval); i += 2 {
		buf.WriteByte(' ')
		buf.WriteString(keyval[i])
		buf.WriteByte('/')
		buf.WriteString(keyval[i+1])
	}
	return buf.String()[1:]
}
1076764
func GoCrossCompile(opts *CompileOpts) error {
	env := append(os.Environ(),
		"GOOS="+opts.Platform.OS,
		"GOARCH="+opts.Platform.Arch)

	// If we're building for our own platform, then enable cgo always. We
	// respect the CGO_ENABLED flag if that is explicitly set on the platform.
	if !opts.Cgo && os.Getenv("CGO_ENABLED") != "0" {
		opts.Cgo = runtime.GOOS == opts.Platform.OS &&
			runtime.GOARCH == opts.Platform.Arch
	}

	// If cgo is enabled then set that env var
	if opts.Cgo {
		env = append(env, "CGO_ENABLED=1")
	} else {
		env = append(env, "CGO_ENABLED=0")
	}

	var outputPath bytes.Buffer
	tpl, err := template.New("output").Parse(opts.OutputTpl)
	if err != nil {
		return err
	}
	tplData := OutputTemplateData{
		Dir:  filepath.Base(opts.PackagePath),
		OS:   opts.Platform.OS,
		Arch: opts.Platform.Arch,
	}
	if err := tpl.Execute(&outputPath, &tplData); err != nil {
		return err
	}

	if opts.Platform.OS == "windows" {
		outputPath.WriteString(".exe")
	}

	// Determine the full path to the output so that we can change our
	// working directory when executing go build.
	outputPathReal := outputPath.String()
	outputPathReal, err = filepath.Abs(outputPathReal)
	if err != nil {
		return err
	}

	// Go prefixes the import directory with '_' when it is outside
	// the GOPATH.For this, we just drop it since we move to that
	// directory to build.
	chdir := ""
	if opts.PackagePath[0] == '_' {
		if runtime.GOOS == "windows" {
			// We have to replace weird paths like this:
			//
			//   _/c_/Users
			//
			// With:
			//
			//   c:\Users
			//
			re := regexp.MustCompile("^/([a-zA-Z])_/")
			chdir = re.ReplaceAllString(opts.PackagePath[1:], "$1:\\")
			chdir = strings.Replace(chdir, "/", "\\", -1)
		} else {
			chdir = opts.PackagePath[1:]
		}

		opts.PackagePath = ""
	}

	args := []string{"build"}
	if opts.Rebuild {
		args = append(args, "-a")
	}
	if opts.ModMode != "" {
		args = append(args, "-mod", opts.ModMode)
	}
	args = append(args,
		"-gcflags", opts.Gcflags,
		"-ldflags", opts.Ldflags,
		"-asmflags", opts.Asmflags,
		"-tags", opts.Tags,
		"-o", outputPathReal,
		opts.PackagePath)

	_, err = execGo(opts.GoCmd, env, chdir, args...)
	return err
}
837473
func main() {
	mathrand.SeedRandomly()

	// Setup process global Context.
	c := context.Background()
	c = gologger.StdConfig.Use(c) // Log to STDERR.

	// TODO(dnj): We currently instantiate global instances of several services,
	// with the current service configuration paramers (e.g., name of BigTable
	// table, etc.).
	//
	// We should monitor config and kill a Flex instance if it's been observed to
	// change. It would respawn, reload the new config, and then be good to go
	// until the next change.
	//
	// As things stand, this configuration basically never changes, so this is
	// not terribly important. However, it's worth noting that we should do this,
	// and that here is probably the right place to kick off such a goroutine.

	// Standard HTTP endpoints using flex LogDog services singleton.
	r := router.NewWithRootContext(c)
	mw := flexMW.ReadOnlyFlex
	mw.InstallHandlers(r)

	// Setup the global services, such as auth, luci-config.
	gsvc, err := flex.NewGlobalServices(flexMW.WithGlobal(c))
	if err != nil {
		logging.WithError(err).Errorf(c, "Failed to setup Flex services.")
		panic(err)
	}
	defer gsvc.Close()
	baseMW := mw.Base().Extend(gsvc.Base)

	// Set up PRPC server.
	svr := &prpc.Server{
		AccessControl: accessControl,
	}
	logsServer := logs.New()
	logsPb.RegisterLogsServer(svr, logsServer)
	discovery.Enable(svr)
	svr.InstallHandlers(r, baseMW)

	// Setup HTTP endpoints.
	// We support OpenID (cookie) auth for browsers and OAuth2 for everything else.
	httpMW := baseMW.Extend(
		auth.Authenticate(
			server.CookieAuth,
			&auth.GoogleOAuth2Method{Scopes: []string{commonAuth.OAuthScopeEmail}}))
	r.GET("/logs/*path", httpMW, logs.GetHandler)

	// Run forever.
	logging.Infof(c, "Listening on port 8080...")
	if err := http.ListenAndServe(":8080", r); err != nil {
		logging.WithError(err).Errorf(c, "Failed HTTP listen.")
		panic(err)
	}
}
1130226
func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
	var volumeDriver string
	for _, option := range options {
		key, val, err := parsers.ParseKeyValueOpt(option)
		if err != nil {
			return nil, err
		}
		switch key {
		case Layer0VolumeDriver:
			volumeDriver = val
		default:
			return nil, fmt.Errorf("Unknown option %s\n", key)
		}
	}
	logrus.Infof("Layer0 volume driver: %v", volumeDriver)
	volDriver, err := volumedrivers.Get(volumeDriver)
	if err != nil {
		return nil, err
	}
	ov, err := overlay.Init(home, options, uidMaps, gidMaps)
	if err != nil {
		volDriver.Shutdown()
		return nil, err
	}
	d := &Layer0{
		Driver:    ov,
		home:      home,
		volumes:   make(map[string]*Layer0Vol),
		volDriver: volDriver,
	}

	return d, nil
}
721786
func IsOSSupported(os string) bool {
	if runtime.GOOS == os {
		return true
	}
	if LCOWSupported() && os == "linux" {
		return true
	}
	return false
}
138641
func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
	d := &Driver{
		homes:      []string{home},
		idMappings: idtools.NewIDMappingsFromMaps(uidMaps, gidMaps),
	}
	rootIDs := d.idMappings.RootPair()
	if err := idtools.MkdirAllAndChown(home, 0700, rootIDs); err != nil {
		return nil, err
	}
	for _, option := range options {
		if strings.HasPrefix(option, "vfs.imagestore=") {
			d.homes = append(d.homes, strings.Split(option[15:], ",")...)
			continue
		}
		if strings.HasPrefix(option, ".imagestore=") {
			d.homes = append(d.homes, strings.Split(option[12:], ",")...)
			continue
		}
		if strings.HasPrefix(option, "vfs.ostree_repo=") {
			if !ostree.OstreeSupport() {
				return nil, fmt.Errorf("vfs: ostree_repo specified but support for ostree is missing")
			}
			d.ostreeRepo = option[16:]
		}
		if strings.HasPrefix(option, ".ostree_repo=") {
			if !ostree.OstreeSupport() {
				return nil, fmt.Errorf("vfs: ostree_repo specified but support for ostree is missing")
			}
			d.ostreeRepo = option[13:]
		}
		if strings.HasPrefix(option, "vfs.mountopt=") {
			return nil, fmt.Errorf("vfs driver does not support mount options")
		}
	}
	if d.ostreeRepo != "" {
		rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
		if err != nil {
			return nil, err
		}
		if err := ostree.CreateOSTreeRepository(d.ostreeRepo, rootUID, rootGID); err != nil {
			return nil, err
		}
	}
	return graphdriver.NewNaiveDiffDriver(d, graphdriver.NewNaiveLayerIDMapUpdater(d)), nil
}
12533
func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
	deviceSet, err := NewDeviceSet(home, true, options, uidMaps, gidMaps)
	if err != nil {
		return nil, err
	}

	if err := mount.MakePrivate(home); err != nil {
		return nil, err
	}

	d := &Driver{
		DeviceSet: deviceSet,
		home:      home,
		uidMaps:   uidMaps,
		gidMaps:   gidMaps,
	}

	return graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps), nil
}
1120405
func (ble *BLE) Init() {
	ble.sendCBMsg(1, xpc.Dict{"kCBMsgArgName": fmt.Sprintf("goble-%v", time.Now().Unix()),
		"kCBMsgArgOptions": xpc.Dict{"kCBInitOptionShowPowerAlert": 0}, "kCBMsgArgType": 0})
}
302077
func monitorTty(client *docker.Client, containerID string, terminalFd uintptr) {
	resizeTty(client, containerID, terminalFd)

	sigchan := make(chan os.Signal, 1)
	gosignal.Notify(sigchan, syscall.SIGWINCH)
	go func() {
		for _ = range sigchan {
			resizeTty(client, containerID, terminalFd)
		}
	}()
}
76497
func main() {
	// os.Setenv("IS_ENABLED", "asdf")
	c := &Config{}
	if err := env.Process(c); err != nil {
		fmt.Println("error:", err)
		return
		// panic(err)
	}
	fmt.Printf("name: %s, port: %d, adapter: %s, enabled: %v\n", c.Name, c.Port, c.Adapter, c.Enabled)
}
965099
func MacdExt(inReal []float64, inFastPeriod int, inFastMAType MaType, inSlowPeriod int, inSlowMAType MaType, inSignalPeriod int, inSignalMAType MaType) ([]float64, []float64, []float64) {

	lookbackLargest := 0
	if inFastPeriod < inSlowPeriod {
		lookbackLargest = inSlowPeriod
	} else {
		lookbackLargest = inFastPeriod
	}
	lookbackTotal := (inSignalPeriod - 1) + (lookbackLargest - 1)

	outMACD := make([]float64, len(inReal))
	outMACDSignal := make([]float64, len(inReal))
	outMACDHist := make([]float64, len(inReal))

	slowMABuffer := Ma(inReal, inSlowPeriod, inSlowMAType)
	fastMABuffer := Ma(inReal, inFastPeriod, inFastMAType)
	tempBuffer1 := make([]float64, len(inReal))

	for i := 0; i < len(slowMABuffer); i++ {
		tempBuffer1[i] = fastMABuffer[i] - slowMABuffer[i]
	}
	tempBuffer2 := Ma(tempBuffer1, inSignalPeriod, inSignalMAType)

	for i := lookbackTotal; i < len(outMACDHist); i++ {
		outMACD[i] = tempBuffer1[i]
		outMACDSignal[i] = tempBuffer2[i]
		outMACDHist[i] = outMACD[i] - outMACDSignal[i]
	}

	return outMACD, outMACDSignal, outMACDHist
}