// Rescan replicates the RPC client's Rescan command.
769324
func (s *NeutrinoClient) Rescan(startHash *chainhash.Hash, addrs []btcutil.Address,
	outPoints map[wire.OutPoint]btcutil.Address) error {

	s.clientMtx.Lock()
	defer s.clientMtx.Unlock()
	if !s.started {
		return fmt.Errorf("can't do a rescan when the chain client " +
			"is not started")
	}
	if s.scanning {
		// Restart the rescan by killing the existing rescan.
		close(s.rescanQuit)
		s.clientMtx.Unlock()
		s.rescan.WaitForShutdown()
		s.clientMtx.Lock()
		s.rescan = nil
		s.rescanErr = nil
	}
	s.rescanQuit = make(chan struct{})
	s.scanning = true
	s.finished = false
	s.lastProgressSent = false
	s.lastFilteredBlockHeader = nil
	s.isRescan = true

	bestBlock, err := s.CS.BestBlock()
	if err != nil {
		return fmt.Errorf("Can't get chain service's best block: %s", err)
	}
	header, err := s.CS.GetBlockHeader(&bestBlock.Hash)
	if err != nil {
		return fmt.Errorf("Can't get block header for hash %v: %s",
			bestBlock.Hash, err)
	}

	// If the wallet is already fully caught up, or the rescan has started
	// with state that indicates a "fresh" wallet, we'll send a
	// notification indicating the rescan has "finished".
	if header.BlockHash() == *startHash {
		s.finished = true
		select {
		case s.enqueueNotification <- &RescanFinished{
			Hash:   startHash,
			Height: int32(bestBlock.Height),
			Time:   header.Timestamp,
		}:
		case <-s.quit:
			return nil
		case <-s.rescanQuit:
			return nil
		}
	}

	var inputsToWatch []neutrino.InputWithScript
	for op, addr := range outPoints {
		addrScript, err := txscript.PayToAddrScript(addr)
		if err != nil {
		}

		inputsToWatch = append(inputsToWatch, neutrino.InputWithScript{
			OutPoint: op,
			PkScript: addrScript,
		})
	}

	newRescan := neutrino.NewRescan(
		&neutrino.RescanChainSource{
			ChainService: s.CS,
		},
		neutrino.NotificationHandlers(rpcclient.NotificationHandlers{
			OnBlockConnected:         s.onBlockConnected,
			OnFilteredBlockConnected: s.onFilteredBlockConnected,
			OnBlockDisconnected:      s.onBlockDisconnected,
		}),
		neutrino.StartBlock(&waddrmgr.BlockStamp{Hash: *startHash}),
		neutrino.StartTime(s.startTime),
		neutrino.QuitChan(s.rescanQuit),
		neutrino.WatchAddrs(addrs...),
		neutrino.WatchInputs(inputsToWatch...),
	)
	s.rescan = newRescan
	s.rescanErr = s.rescan.Start()

	return nil
}
400174
func (m *Map) Scan(src interface{}) error {
	b, ok := src.([]byte)
	if !ok {
		return errors.New("Scan source was not []byte")
	}
	err := json.Unmarshal(b, m)
	if err != nil {
		return errors.WithStack(err)
	}
	return nil
}
1125458
func (self *Commands) Rpc(method string, args map[string]interface{}) (interface{}, error) {
	mod, meth := stringutil.SplitPair(method, `::`)

	return self.browser.Tab().RPC(mod, meth, args)
}
250877
func Ginrescan(db XODB, v0 pgtypes.Internal, v1 pgtypes.Internal, v2 pgtypes.Internal, v3 pgtypes.Internal, v4 pgtypes.Internal) error {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.ginrescan($1, $2, $3, $4, $5)`

	// run query
	XOLog(sqlstr)
	_, err = db.Exec(sqlstr)
	return err
}
365271
func (q *Query) MapScan(m map[string]interface{}) error {
	iter := q.Iter()
	if err := iter.checkErrAndNotFound(); err != nil {
		return err
	}
	iter.MapScan(m)
	return iter.Close()
}
1023766
func (db *DB) SScan(key []byte, cursor []byte, count int, inclusive bool, match string) ([][]byte, error) {
	return db.sScanGeneric(key, cursor, count, inclusive, match, false)
}
197892
func (c *cniProcessor) Resync(ctx context.Context, e *common.EventInfo) error {
	return nil
}
794252
func (s *ServerRPC) ImageRemove(ctx context.Context, req *types.ImageRemoveRequest) (*types.ImageRemoveResponse, error) {
	resp, err := s.daemon.CmdImageDelete(req.Image, req.Force, req.Prune)
	if err != nil {
		return nil, err
	}

	return &types.ImageRemoveResponse{
		Images: resp,
	}, nil
}
364059
func (w *Wallet) rescanRPCHandler() {
	chainClient, err := w.requireChainClient()
	if err != nil {
		log.Errorf("rescanRPCHandler called without an RPC client")
		w.wg.Done()
		return
	}

	quit := w.quitChan()

out:
	for {
		select {
		case batch := <-w.rescanBatch:
			// Log the newly-started rescan.
			numAddrs := len(batch.addrs)
			noun := pickNoun(numAddrs, "address", "addresses")
			log.Infof("Started rescan from block %v (height %d) for %d %s",
				batch.bs.Hash, batch.bs.Height, numAddrs, noun)

			err := chainClient.Rescan(&batch.bs.Hash, batch.addrs,
				batch.outpoints)
			if err != nil {
				log.Errorf("Rescan for %d %s failed: %v", numAddrs,
					noun, err)
			}
			batch.done(err)
		case <-quit:
			break out
		}
	}

	w.wg.Done()
}
520212
func (r *Redis) Scan(cursor uint64, pattern string, count int) (uint64, []string, error) {
	args := packArgs("SCAN", cursor)
	if pattern != "" {
		args = append(args, "MATCH", pattern)
	}
	if count > 0 {
		args = append(args, "COUNT", count)
	}
	rp, err := r.ExecuteCommand(args...)
	if err != nil {
		return 0, nil, err
	}
	if rp.Type == ErrorReply {
		return 0, nil, errors.New(rp.Error)
	}
	if rp.Type != MultiReply {
		return 0, nil, errors.New("scan protocol error")
	}
	first, err := rp.Multi[0].StringValue()
	if err != nil {
		return 0, nil, err
	}
	next, err := strconv.ParseUint(first, 10, 64)
	if err != nil {
		return 0, nil, err
	}
	list, err := rp.Multi[1].ListValue()
	return next, list, err
}
1338510
func (p *WebPage) ClipRect() (Rect, error) {
	var resp struct {
		Value rectJSON `json:"value"`
	}
	if err := p.ref.process.doJSON("POST", "/webpage/ClipRect", map[string]interface{}{"ref": p.ref.id}, &resp); err != nil {
		return Rect{}, err
	}
	return Rect{
		Top:    resp.Value.Top,
		Left:   resp.Value.Left,
		Width:  resp.Value.Width,
		Height: resp.Value.Height,
	}, nil
}
750949
func (a *AssetBuilder) RemapImage(image string) (string, error) {
	asset := &ContainerAsset{}

	asset.DockerImage = image

	// The k8s.gcr.io prefix is an alias, but for CI builds we run from a docker load,
	// and we only double-tag from 1.10 onwards.
	// For versions prior to 1.10, remap k8s.gcr.io to the old name.
	// This also means that we won't start using the aliased names on existing clusters,
	// which could otherwise be surprising to users.
	if !util.IsKubernetesGTE("1.10", a.KubernetesVersion) && strings.HasPrefix(image, "k8s.gcr.io/") {
		image = "gcr.io/google_containers/" + strings.TrimPrefix(image, "k8s.gcr.io/")
	}

	if strings.HasPrefix(image, "kope/dns-controller:") {
		// To use user-defined DNS Controller:
		// 1. DOCKER_REGISTRY=[your docker hub repo] make dns-controller-push
		// 2. export DNSCONTROLLER_IMAGE=[your docker hub repo]
		// 3. make kops and create/apply cluster
		override := os.Getenv("DNSCONTROLLER_IMAGE")
		if override != "" {
			image = override
		}
	}

	if a.AssetsLocation != nil && a.AssetsLocation.ContainerProxy != nil {
		containerProxy := strings.TrimRight(*a.AssetsLocation.ContainerProxy, "/")
		normalized := image

		// If the image name contains only a single / we need to determine if the image is located on docker-hub or if it's using a convenient URL like k8s.gcr.io/<image-name>
		// In case of a hub image it should be sufficient to just prepend the proxy url, producing eg docker-proxy.example.com/weaveworks/weave-kube
		if strings.Count(normalized, "/") <= 1 && !strings.ContainsAny(strings.Split(normalized, "/")[0], ".:") {
			normalized = containerProxy + "/" + normalized
		} else {
			var re = regexp.MustCompile(`^[^/]+`)
			normalized = re.ReplaceAllString(normalized, containerProxy)
		}

		asset.DockerImage = normalized
		asset.CanonicalLocation = image

		// Run the new image
		image = asset.DockerImage
	}

	if a.AssetsLocation != nil && a.AssetsLocation.ContainerRegistry != nil {
		registryMirror := *a.AssetsLocation.ContainerRegistry
		normalized := image

		// Remove the 'standard' kubernetes image prefix, just for sanity
		if !util.IsKubernetesGTE("1.10", a.KubernetesVersion) && strings.HasPrefix(normalized, "gcr.io/google_containers/") {
			normalized = strings.TrimPrefix(normalized, "gcr.io/google_containers/")
		} else {
			normalized = strings.TrimPrefix(normalized, "k8s.gcr.io/")
		}

		// When assembling the cluster spec, kops may call the option more then once until the config converges
		// This means that this function may me called more than once on the same image
		// It this is pass is the second one, the image will already have been normalized with the containerRegistry settings
		// If this is the case, passing though the process again will re-prepend the container registry again
		// and again, causing the spec to never converge and the config build to fail.
		if !strings.HasPrefix(normalized, registryMirror+"/") {
			// We can't nest arbitrarily
			// Some risk of collisions, but also -- and __ in the names appear to be blocked by docker hub
			normalized = strings.Replace(normalized, "/", "-", -1)
			asset.DockerImage = registryMirror + "/" + normalized
		}

		asset.CanonicalLocation = image

		// Run the new image
		image = asset.DockerImage
	}

	a.ContainerAssets = append(a.ContainerAssets, asset)
	return image, nil
}
385623
func Rescale(input, fromMin, fromMax, toMin, toMax float64) float64 {
	return (input-fromMin)*(toMax-toMin)/(fromMax-fromMin) + toMin
}
87006
func (c *Client) R() *Request {
	r := &Request{
		QueryParam: url.Values{},
		FormData:   url.Values{},
		Header:     http.Header{},

		client:          c,
		multipartFiles:  []*File{},
		multipartFields: []*MultipartField{},
		pathParams:      map[string]string{},
		jsonEscapeHTML:  true,
	}

	return r
}
1076388
func (s *MemoryScheduler) AddScan(sc *scan.Scan) error {
	return s.UpdateScan(sc)
}
278994
func (w *Wallet) rescanWithTarget(addrs []btcutil.Address,
	unspent []wtxmgr.Credit, startStamp *waddrmgr.BlockStamp) error {

	outpoints := make(map[wire.OutPoint]btcutil.Address, len(unspent))
	for _, output := range unspent {
		_, outputAddrs, _, err := txscript.ExtractPkScriptAddrs(
			output.PkScript, w.chainParams,
		)
		if err != nil {
			return err
		}

		outpoints[output.OutPoint] = outputAddrs[0]
	}

	// If a start block stamp was provided, we will use that as the initial
	// starting point for the rescan.
	if startStamp == nil {
		startStamp = &waddrmgr.BlockStamp{}
		*startStamp = w.Manager.SyncedTo()
	}

	job := &RescanJob{
		InitialSync: true,
		Addrs:       addrs,
		OutPoints:   outpoints,
		BlockStamp:  *startStamp,
	}

	// Submit merged job and block until rescan completes.
	return <-w.SubmitRescan(job)
}
401196
func (l *linuxProcessor) Resync(ctx context.Context, e *common.EventInfo) error {

	if e != nil {
		// If its a host service then use pu from eventInfo
		// The code block below assumes that pu is already created
		if e.HostService {
			return l.resyncHostService(ctx, e)
		}
	}

	cgroups := l.netcls.ListAllCgroups("")
	for _, cgroup := range cgroups {

		if _, ok := ignoreNames[cgroup]; ok {
			continue
		}

		isSSHPU := strings.Contains(cgroup, "ssh")
		if l.ssh != isSSHPU {
			continue
		}

		// List all the cgroup processes. If its empty, we can remove it.
		procs, err := l.netcls.ListCgroupProcesses(cgroup)
		if err != nil {
			continue
		}

		// All processes in cgroup have died. Let's clean up.
		if len(procs) == 0 {
			if err := l.netcls.DeleteCgroup(cgroup); err != nil {
				zap.L().Warn("Failed to deleted cgroup",
					zap.String("cgroup", cgroup),
					zap.Error(err),
				)
			}
			continue
		}

		runtime := policy.NewPURuntimeWithDefaults()
		puType := common.LinuxProcessPU
		if l.ssh && isSSHPU {
			puType = common.SSHSessionPU
		}
		runtime.SetPUType(puType)
		runtime.SetOptions(policy.OptionsType{
			CgroupMark: strconv.FormatUint(cgnetcls.MarkVal(), 10),
			CgroupName: cgroup,
		})

		// Processes are still alive. We should enforce policy.
		if err := l.config.Policy.HandlePUEvent(ctx, cgroup, common.EventStart, runtime); err != nil {
			zap.L().Error("Failed to restart cgroup control", zap.String("cgroup ID", cgroup), zap.Error(err))
		}

		if err := l.processLinuxServiceStart(cgroup, nil, runtime); err != nil {
			return err
		}
	}
	return nil
}