// medianRTT returns the median RTT of the peerset, considering only the tuning
// peers if there are more peers available.
327676
func (ps *peerSet) medianRTT() time.Duration {
	// Gather all the currently measured round trip times
	ps.lock.RLock()
	defer ps.lock.RUnlock()

	rtts := make([]float64, 0, len(ps.peers))
	for _, p := range ps.peers {
		p.lock.RLock()
		rtts = append(rtts, float64(p.rtt))
		p.lock.RUnlock()
	}
	sort.Float64s(rtts)

	median := rttMaxEstimate
	if qosTuningPeers <= len(rtts) {
		median = time.Duration(rtts[qosTuningPeers/2]) // Median of our tuning peers
	} else if len(rtts) > 0 {
		median = time.Duration(rtts[len(rtts)/2]) // Median of our connected peers (maintain even like this some baseline qos)
	}
	// Restrict the RTT into some QoS defaults, irrelevant of true RTT
	if median < rttMinEstimate {
		median = rttMinEstimate
	}
	if median > rttMaxEstimate {
		median = rttMaxEstimate
	}
	return median
}
864279
func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
	// use provided storage, if provided
	storageClient := cl.defaultStorage
	if specStorage != nil {
		storageClient = storage.NewClient(specStorage)
	}

	t = &Torrent{
		cl:       cl,
		infoHash: ih,
		peers: prioritizedPeers{
			om: btree.New(32),
			getPrio: func(p Peer) peerPriority {
				return bep40PriorityIgnoreError(cl.publicAddr(p.IP), p.addr())
			},
		},
		conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent),

		halfOpen:          make(map[string]Peer),
		pieceStateChanges: pubsub.NewPubSub(),

		storageOpener:       storageClient,
		maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,

		networkingEnabled: true,
		requestStrategy:   2,
		metadataChanged: sync.Cond{
			L: cl.locker(),
		},
		duplicateRequestTimeout: 1 * time.Second,
	}
	t.logger = cl.logger.Clone().AddValue(t)
	t.setChunkSize(defaultChunkSize)
	return
}
50467
func (c *Client) TorrentAdd(payload *TorrentAddPayload) (torrent *Torrent, err error) {
	// Validate
	if payload == nil {
		err = errors.New("payload can't be nil")
		return
	}
	if payload.Filename == nil && payload.MetaInfo == nil {
		err = errors.New("Filename and MetaInfo can't be both nil")
		return
	}
	// Send payload
	var result torrentAddAnswer
	if err = c.rpcCall("torrent-add", payload, &result); err != nil {
		err = fmt.Errorf("'torrent-add' rpc method failed: %v", err)
		return
	}
	// Extract results
	if result.TorrentAdded != nil {
		torrent = result.TorrentAdded
	} else if result.TorrentDuplicate != nil {
		torrent = result.TorrentDuplicate
	} else {
		err = errors.New("RPC call went fine but neither 'torrent-added' nor 'torrent-duplicate' result payload were found")
	}
	return
}
664133
func (p *peer) SendNodeData(data [][]byte) error {
	return p2p.Send(p.rw, NodeDataMsg, data)
}
537876
func (d *Downloader) qosTuner() {
	for {
		// Retrieve the current median RTT and integrate into the previoust target RTT
		rtt := time.Duration((1-qosTuningImpact)*float64(atomic.LoadUint64(&d.rttEstimate)) + qosTuningImpact*float64(d.peers.medianRTT()))
		atomic.StoreUint64(&d.rttEstimate, uint64(rtt))

		// A new RTT cycle passed, increase our confidence in the estimated RTT
		conf := atomic.LoadUint64(&d.rttConfidence)
		conf = conf + (1000000-conf)/2
		atomic.StoreUint64(&d.rttConfidence, conf)

		// Log the new QoS values and sleep until the next RTT
		log.Debug("Recalculated downloader QoS values", "rtt", rtt, "confidence", float64(conf)/1000000.0, "ttl", d.requestTTL())
		select {
		case <-d.quitCh:
			return
		case <-time.After(rtt):
		}
	}
}
57155
func MedianAmount(s []dcrutil.Amount) dcrutil.Amount {
	if len(s) == 0 {
		return 0
	}

	sort.Sort(dcrutil.AmountSorter(s))

	middle := len(s) / 2

	if len(s) == 0 {
		return 0
	} else if (len(s) % 2) != 0 {
		return s[middle]
	}
	return (s[middle] + s[middle-1]) / 2
}
827534
func (s *Server) BandwidthAt(index int) int {
	if len(s.Interfaces) <= index {
		return -1
	}

	nic := s.Interfaces[index]

	switch nic.UpstreamType() {
	case EUpstreamNetworkNone:
		return -1
	case EUpstreamNetworkShared:
		return 100
	case EUpstreamNetworkSwitch, EUpstreamNetworkRouter:
		//
		// 上流ネットワークがスイッチだった場合の帯域制限
		// https://manual.sakura.ad.jp/cloud/support/technical/network.html#support-network-03
		//

		// 専有ホストの場合は制限なし
		if s.PrivateHost != nil {
			return 0
		}

		// メモリに応じた制限
		memory := s.GetMemoryGB()
		switch {
		case memory < 32:
			return 1000
		case 32 <= memory && memory < 128:
			return 2000
		case 128 <= memory && memory < 224:
			return 5000
		case 224 <= memory:
			return 10000
		default:
			return -1
		}
	default:
		return -1
	}
}
1273722
func (soc *Socket) SetTcpMaxrt(value time.Duration) error {
	if minor < 2 {
		return ErrorNotImplemented42
	}
	val := int(value / time.Millisecond)
	return soc.setInt(C.ZMQ_TCP_MAXRT, val)
}
702148
func (pn *peernet) Peers() []peer.ID {
	pn.RLock()
	defer pn.RUnlock()

	peers := make([]peer.ID, 0, len(pn.connsByPeer))
	for _, cs := range pn.connsByPeer {
		for c := range cs {
			peers = append(peers, c.remote)
			break
		}
	}
	return peers
}
1354569
func (wr *Wrangler) ReparentTablet(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error {
	// Get specified tablet.
	// Get current shard master tablet.
	// Sanity check they are in the same keyspace/shard.
	// Issue a SetMaster to the tablet.
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return err
	}

	shardInfo, err := wr.ts.GetShard(ctx, ti.Keyspace, ti.Shard)
	if err != nil {
		return err
	}
	if !shardInfo.HasMaster() {
		return fmt.Errorf("no master tablet for shard %v/%v", ti.Keyspace, ti.Shard)
	}

	masterTi, err := wr.ts.GetTablet(ctx, shardInfo.MasterAlias)
	if err != nil {
		return err
	}

	// Basic sanity checking.
	if masterTi.Type != topodatapb.TabletType_MASTER {
		return fmt.Errorf("TopologyServer has inconsistent state for shard master %v", topoproto.TabletAliasString(shardInfo.MasterAlias))
	}
	if masterTi.Keyspace != ti.Keyspace || masterTi.Shard != ti.Shard {
		return fmt.Errorf("master %v and potential slave not in same keyspace/shard", topoproto.TabletAliasString(shardInfo.MasterAlias))
	}

	// and do the remote command
	return wr.tmc.SetMaster(ctx, ti.Tablet, shardInfo.MasterAlias, 0, false)
}
334249
func medianOfThree(data []int, a, b, c int) {
	m0 := b
	m1 := a
	m2 := c
	// bubble sort on 3 elements
	if data[m1] < data[m0] {
		data[m1], data[m0] = data[m0], data[m1]
	}
	if data[m2] < data[m1] {
		data[m2], data[m1] = data[m1], data[m2]
	}
	if data[m1] < data[m0] {
		data[m1], data[m0] = data[m0], data[m1]
	}
	// now data[m0] <= data[m1] <= data[m2]
}
908152
func (s *JobDetail) SetStoppedAt(v int64) *JobDetail {
	s.StoppedAt = &v
	return s
}
1328984
func (t tPacketHdr) setTPStatus(status uint32) {
	hdr := unsafe.Pointer(&t[0])
	statusPtr := unsafe.Pointer(uintptr(hdr) + uintptr(tpStatusOffset))
	atomic.StoreUint32((*uint32)(statusPtr), status)
}
788550
func NewTrait(TraitName node.Node, Stmts []node.Node, PhpDocComment string) *Trait {
	return &Trait{
		FreeFloating:  nil,
		PhpDocComment: PhpDocComment,
		TraitName:     TraitName,
		Stmts:         Stmts,
	}
}
63088
func (rt *RoutingTable) NearestPeers(id ID, count int) []peer.ID {
	cpl := CommonPrefixLen(id, rt.local)

	// It's assumed that this also protects the buckets.
	rt.tabLock.RLock()

	// Get bucket at cpl index or last bucket
	var bucket *Bucket
	if cpl >= len(rt.Buckets) {
		cpl = len(rt.Buckets) - 1
	}
	bucket = rt.Buckets[cpl]

	pds := peerDistanceSorter{
		peers:  make([]peerDistance, 0, 3*rt.bucketsize),
		target: id,
	}
	pds.appendPeersFromList(bucket.list)
	if pds.Len() < count {
		// In the case of an unusual split, one bucket may be short or empty.
		// if this happens, search both surrounding buckets for nearby peers
		if cpl > 0 {
			pds.appendPeersFromList(rt.Buckets[cpl-1].list)
		}
		if cpl < len(rt.Buckets)-1 {
			pds.appendPeersFromList(rt.Buckets[cpl+1].list)
		}
	}
	rt.tabLock.RUnlock()

	// Sort by distance to local peer
	pds.sort()

	if count < pds.Len() {
		pds.peers = pds.peers[:count]
	}

	out := make([]peer.ID, 0, pds.Len())
	for _, p := range pds.peers {
		out = append(out, p.p)
	}

	return out
}
992050
func (ps *peerSet) Peer(id string) *peerConnection {
	ps.lock.RLock()
	defer ps.lock.RUnlock()

	return ps.peers[id]
}
932157
func medianAdjustedTime(chainState *blockchain.BestState, timeSource blockchain.MedianTimeSource) time.Time {
	// The timestamp for the block must not be before the median timestamp
	// of the last several blocks.  Thus, choose the maximum between the
	// current time and one second after the past median time.  The current
	// timestamp is truncated to a second boundary before comparison since a
	// block timestamp does not supported a precision greater than one
	// second.
	newTimestamp := timeSource.AdjustedTime()
	minTimestamp := MinimumMedianTime(chainState)
	if newTimestamp.Before(minTimestamp) {
		newTimestamp = minTimestamp
	}

	return newTimestamp
}