repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/numeric_fields.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/numeric_fields.go#L157-L175
go
train
// This returns a field descriptor for FieldType_NEWDECIMAL (i.e., // Field_newdecimal)
func NewNewDecimalFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
// This returns a field descriptor for FieldType_NEWDECIMAL (i.e., // Field_newdecimal) func NewNewDecimalFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
{ if len(metadata) < 2 { return nil, nil, errors.New("Metadata has too few bytes") } return &newDecimalFieldDescriptor{ baseFieldDescriptor: baseFieldDescriptor{ fieldType: mysql_proto.FieldType_NEWDECIMAL, isNullable: nullable, }, precision: uint8(metadata[0]), decimals: uint8(metadata[1]), }, metadata[2:], nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L137-L141
go
train
// For the round robin strategy, sets the number of servers to round-robin // between. The default is 6.
func (pool *LoadBalancedPool) SetActiveSetSize(size uint64)
// For the round robin strategy, sets the number of servers to round-robin // between. The default is 6. func (pool *LoadBalancedPool) SetActiveSetSize(size uint64)
{ pool.lock.Lock() defer pool.lock.Unlock() pool.activeSetSize = size }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L223-L225
go
train
// // Pool interface methods //
func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error)
// // Pool interface methods // func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error)
{ return pool.DoWithTimeout(req, 0) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L288-L291
go
train
// Issues an HTTP request, distributing more load to relatively unloaded instances.
func (pool *LoadBalancedPool) DoWithTimeout(req *http.Request, timeout time.Duration) (*http.Response, error)
// Issues an HTTP request, distributing more load to relatively unloaded instances. func (pool *LoadBalancedPool) DoWithTimeout(req *http.Request, timeout time.Duration) (*http.Response, error)
{ return pool.DoWithParams(req, DoParams{Timeout: timeout}) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L312-L412
go
train
// Returns instance that isn't marked down, if all instances are // marked as down it will just choose a next one.
func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) ( idx int, instance *instancePool, isDown bool, err error)
// Returns instance that isn't marked down, if all instances are // marked as down it will just choose a next one. func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) ( idx int, instance *instancePool, isDown bool, err error)
{ pool.lock.RLock() defer pool.lock.RUnlock() if len(pool.instanceList) == 0 { return 0, nil, false, errors.Newf("no available instances") } now := time.Now().Unix() numInstancesToTry := uint64(len(pool.instanceList)) start := 0 // map used to implement soft swapping to avoid picking the same instance multiple times // when we randomly pick instances for consistent-hashing. We could have used this actually // for the other strategies. // TODO(bashar): get rid of the random shuffle for the other strategies var idxMap map[int]int if pool.strategy == LBRoundRobin && pool.activeSetSize < numInstancesToTry { numInstancesToTry = pool.activeSetSize } else if pool.strategy == LBConsistentHashing { // we must have a key if len(key) == 0 { return 0, nil, false, errors.Newf("key was not specified for consistent-hashing") } else if maxInstances <= 0 { return 0, nil, false, errors.Newf( "invalid maxInstances for consistent-hashing: %v", maxInstances) } // in case we're asked to try more than the number of servers we have if maxInstances > int(numInstancesToTry) { maxInstances = int(numInstancesToTry) } // let's find the closest server to start. We don't start from 0 in that case hash := pool.hashFunction(key, pool.hashSeed) // we need to find the closest server that hashes to >= hash. start = sort.Search(len(pool.instanceList), func(i int) bool { return pool.instanceHashes[i] >= hash }) // In the case where hash > all elements, sort.Search returns len(pool.instanceList). // Hence, we mod the result start = start % len(pool.instanceHashes) idxMap = make(map[int]int) } for i := 0; uint64(i) < numInstancesToTry; i++ { switch pool.strategy { case LBRoundRobin: // In RoundRobin strategy instanceIdx keeps changing, to // achieve round robin load balancing. instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1) idx = int(instanceIdx % numInstancesToTry) case LBSortedFixed: // In SortedFixed strategy instances are always traversed in same // exact order. idx = i case LBShuffledFixed: // In ShuffledFixed strategy instances are also always traversed in // same exact order. idx = i case LBConsistentHashing: // In ConsistentHashing strategy instances are picked up randomly between // start and start + numInstancesToTry. This is to load balance between // the alive servers that are closest to the key in the hash space // consistent-hashing will prefer availability over consistency. In the case some // server is down, we will try new servers in the hash-ring. The way we do this is by // picking random instances next (excluding already picked instances). That's why we // do a 'soft-swap' between already picked instance and move the start offset by 1 // every time. We don't touch the pool.instanceList to make sure we don't // screw up any order. The swap below guarantees that start always has an idx that // has never been tried before. newStart := i + start idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList) // we need to swap idxMap[newStart] with idxMap[idx] (or fill them). var ok bool if idxMap[idx], ok = idxMap[idx]; ok { idxMap[newStart] = idxMap[idx] } else { idxMap[newStart] = idx } idxMap[idx] = newStart // we need to pick the correct idx after the swap idx = idxMap[newStart] } if pool.markDownUntil[idx] < now { break } } return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L415-L418
go
train
// Returns a Pool for an instance selected based on load balancing strategy.
func (pool *LoadBalancedPool) GetSingleInstance() (Pool, error)
// Returns a Pool for an instance selected based on load balancing strategy. func (pool *LoadBalancedPool) GetSingleInstance() (Pool, error)
{ _, instance, _, err := pool.getInstance(nil, 1) return instance, err }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L429-L438
go
train
// Returns a SimplePool for given instanceId, or an error if it does not exist. // TODO(zviad): right now this scans all instances, thus if there are a lot of // instances per partition it can become very slow. If it becomes a problem, fix it!
func (pool *LoadBalancedPool) GetInstancePool(instanceId int) (*SimplePool, error)
// Returns a SimplePool for given instanceId, or an error if it does not exist. // TODO(zviad): right now this scans all instances, thus if there are a lot of // instances per partition it can become very slow. If it becomes a problem, fix it! func (pool *LoadBalancedPool) GetInstancePool(instanceId int) (*SimplePool, error)
{ pool.lock.RLock() defer pool.lock.RUnlock() for _, instancePool := range pool.instanceList { if instancePool.instanceId == instanceId { return &instancePool.SimplePool, nil } } return nil, errors.Newf("InstanceId: %v not found in the pool", instanceId) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L441-L448
go
train
// Marks instance down till downUntil epoch in seconds.
func (pool *LoadBalancedPool) markInstanceDown( idx int, instance *instancePool, downUntil int64)
// Marks instance down till downUntil epoch in seconds. func (pool *LoadBalancedPool) markInstanceDown( idx int, instance *instancePool, downUntil int64)
{ pool.lock.Lock() defer pool.lock.Unlock() if idx < len(pool.instanceList) && pool.instanceList[idx] == instance { pool.markDownUntil[idx] = downUntil } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/http2/load_balanced_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/http2/load_balanced_pool.go#L451-L454
go
train
// Marks instance as ready to be used.
func (pool *LoadBalancedPool) markInstanceUp( idx int, instance *instancePool)
// Marks instance as ready to be used. func (pool *LoadBalancedPool) markInstanceUp( idx int, instance *instancePool)
{ pool.markInstanceDown(idx, instance, 0) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
lockstore/map.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L71-L78
go
train
// NewLockingMap returns a new instance of LockingMap
func NewLockingMap(options LockingMapOptions) LockingMap
// NewLockingMap returns a new instance of LockingMap func NewLockingMap(options LockingMapOptions) LockingMap
{ return &lockingMap{ lock: &sync.RWMutex{}, keyLocker: New(options.LockStoreOptions), data: make(map[string]interface{}), checkFunc: options.ValueCheckFunc, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
lockstore/map.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L82-L96
go
train
// Get returns the value, ok for a given key from within the map. If a ValueCheckFunc // was defined for the map, the value is only returned if that function returns true.
func (m *lockingMap) Get(key string) (interface{}, bool)
// Get returns the value, ok for a given key from within the map. If a ValueCheckFunc // was defined for the map, the value is only returned if that function returns true. func (m *lockingMap) Get(key string) (interface{}, bool)
{ m.keyLocker.RLock(key) defer m.keyLocker.RUnlock(key) m.lock.RLock() defer m.lock.RUnlock() val, ok := m.data[key] if ok && (m.checkFunc == nil || m.checkFunc(key, val)) { return val, true } else { // No value or it failed to check return nil, false } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
lockstore/map.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L99-L107
go
train
// Delete removes a key from the map if it exists. Returns nothing.
func (m *lockingMap) Delete(key string)
// Delete removes a key from the map if it exists. Returns nothing. func (m *lockingMap) Delete(key string)
{ m.keyLocker.Lock(key) defer m.keyLocker.Unlock(key) m.lock.Lock() defer m.lock.Unlock() delete(m.data, key) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
lockstore/map.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L115-L157
go
train
// AddOrGet returns the current value. You must pass in a LockingMapAddFunc // as the second parameter: if the key you are requesting is not present in the // map then we will call your function and you must return the value or an // error. The LockingMap guarantees that the Get-to-Add phase is done atomically, // i.e., it will hold a lock on this key through as long as your function takes // to run. Returns the value for the key or an error.
func (m *lockingMap) AddOrGet(key string, creator LockingMapAddFunc) (interface{}, error)
// AddOrGet returns the current value. You must pass in a LockingMapAddFunc // as the second parameter: if the key you are requesting is not present in the // map then we will call your function and you must return the value or an // error. The LockingMap guarantees that the Get-to-Add phase is done atomically, // i.e., it will hold a lock on this key through as long as your function takes // to run. Returns the value for the key or an error. func (m *lockingMap) AddOrGet(key string, creator LockingMapAddFunc) (interface{}, error)
{ // Fast and easy path: key exists just return it. if val, ok := m.Get(key); ok { return val, nil } // Does not exist. Prepare to add it by upgrading key lock to a write lock. // This is potentially held for a long time but it's only on the key. m.keyLocker.Lock(key) defer m.keyLocker.Unlock(key) // Reverify that the key has not already been set, but we want to only do this // briefly with a read lock on the main map. val, exists := func() (interface{}, bool) { m.lock.RLock() defer m.lock.RUnlock() // Must also reverify against the check function val, ok := m.data[key] if ok && (m.checkFunc == nil || m.checkFunc(key, val)) { return val, true } return nil, false }() if exists { return val, nil } // With the key write lock held (but NOT the map lock), call the user specified // create function. val, err := creator(key) if err != nil { return nil, err } // Now we need the map's write lock to set this key... m.lock.Lock() defer m.lock.Unlock() // Set and return and we're done! m.data[key] = val return val, nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
lockstore/map.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L163-L178
go
train
// Add safely adds a value to the map if and only if the key is not already in the map. // This is a convenience function if the value you want to add is not hard to calculate. // Else, look at AddOrGet for a more appropriate method for hard-to-derive values // (such as things that require setting up network connections).
func (m *lockingMap) Add(key string, val interface{}) bool
// Add safely adds a value to the map if and only if the key is not already in the map. // This is a convenience function if the value you want to add is not hard to calculate. // Else, look at AddOrGet for a more appropriate method for hard-to-derive values // (such as things that require setting up network connections). func (m *lockingMap) Add(key string, val interface{}) bool
{ m.keyLocker.Lock(key) defer m.keyLocker.Unlock(key) m.lock.Lock() defer m.lock.Unlock() _, ok := m.data[key] if ok && (m.checkFunc == nil || m.checkFunc(key, val)) { return false } // Did not exist or failed to check m.data[key] = val return true }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
lockstore/map.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/lockstore/map.go#L181-L189
go
train
// Set just sets/overwrites the value in the hash.
func (m *lockingMap) Set(key string, val interface{})
// Set just sets/overwrites the value in the hash. func (m *lockingMap) Set(key string, val interface{})
{ m.keyLocker.Lock(key) defer m.keyLocker.Unlock(key) m.lock.Lock() defer m.lock.Unlock() m.data[key] = val }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/managed_connection.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L51-L69
go
train
// This creates a managed connection wrapper.
func NewManagedConn( network string, address string, handle resource_pool.ManagedHandle, pool ConnectionPool, options ConnectionOptions) ManagedConn
// This creates a managed connection wrapper. func NewManagedConn( network string, address string, handle resource_pool.ManagedHandle, pool ConnectionPool, options ConnectionOptions) ManagedConn
{ addr := NetworkAddress{ Network: network, Address: address, } return &managedConnImpl{ addr: addr, handle: handle, pool: pool, options: options, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/managed_connection.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L77-L80
go
train
// See ManagedConn for documentation.
func (c *managedConnImpl) RawConn() net.Conn
// See ManagedConn for documentation. func (c *managedConnImpl) RawConn() net.Conn
{ h, _ := c.handle.Handle() return h.(net.Conn) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/managed_connection.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L103-L131
go
train
// See net.Conn for documentation
func (c *managedConnImpl) Read(b []byte) (n int, err error)
// See net.Conn for documentation func (c *managedConnImpl) Read(b []byte) (n int, err error)
{ conn, err := c.rawConn() if err != nil { return 0, err } if c.options.ReadTimeout > 0 { deadline := c.options.getCurrentTime().Add(c.options.ReadTimeout) _ = conn.SetReadDeadline(deadline) } n, err = conn.Read(b) if err != nil { var localAddr string if conn.LocalAddr() != nil { localAddr = conn.LocalAddr().String() } else { localAddr = "(nil)" } var remoteAddr string if conn.RemoteAddr() != nil { remoteAddr = conn.RemoteAddr().String() } else { remoteAddr = "(nil)" } err = errors.Wrapf(err, "Read error from host: %s <-> %s", localAddr, remoteAddr) } return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/managed_connection.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L134-L149
go
train
// See net.Conn for documentation
func (c *managedConnImpl) Write(b []byte) (n int, err error)
// See net.Conn for documentation func (c *managedConnImpl) Write(b []byte) (n int, err error)
{ conn, err := c.rawConn() if err != nil { return 0, err } if c.options.WriteTimeout > 0 { deadline := c.options.getCurrentTime().Add(c.options.WriteTimeout) _ = conn.SetWriteDeadline(deadline) } n, err = conn.Write(b) if err != nil { err = errors.Wrap(err, "Write error") } return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/managed_connection.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L157-L160
go
train
// See net.Conn for documentation
func (c *managedConnImpl) LocalAddr() net.Addr
// See net.Conn for documentation func (c *managedConnImpl) LocalAddr() net.Addr
{ conn, _ := c.rawConn() return conn.LocalAddr() }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/managed_connection.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/managed_connection.go#L163-L166
go
train
// See net.Conn for documentation
func (c *managedConnImpl) RemoteAddr() net.Addr
// See net.Conn for documentation func (c *managedConnImpl) RemoteAddr() net.Addr
{ conn, _ := c.rawConn() return conn.RemoteAddr() }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/port.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/port.go#L9-L19
go
train
// Returns the port information.
func GetPort(addr net.Addr) (int, error)
// Returns the port information. func GetPort(addr net.Addr) (int, error)
{ _, lport, err := net.SplitHostPort(addr.String()) if err != nil { return -1, err } lportInt, err := strconv.Atoi(lport) if err != nil { return -1, err } return lportInt, nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L37-L41
go
train
// This returns a thread-safe random source.
func NewSource(seed int64) rand.Source
// This returns a thread-safe random source. func NewSource(seed int64) rand.Source
{ return &lockedSource{ src: rand.NewSource(seed), } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L44-L47
go
train
// Generates a seed based on the current time and the process ID.
func GetSeed() int64
// Generates a seed based on the current time and the process ID. func GetSeed() int64
{ now := time.Now() return now.Unix() + int64(now.Nanosecond()) + 12345*int64(os.Getpid()) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L101-L103
go
train
// Dur returns a pseudo-random Duration in [0, max)
func Dur(max time.Duration) time.Duration
// Dur returns a pseudo-random Duration in [0, max) func Dur(max time.Duration) time.Duration
{ return time.Duration(Int63n(int64(max))) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L112-L115
go
train
// Uniformly jitters the provided duration by +/- the given fraction. NOTE: // fraction must be in (0, 1].
func JitterFraction(period time.Duration, fraction float64) time.Duration
// Uniformly jitters the provided duration by +/- the given fraction. NOTE: // fraction must be in (0, 1]. func JitterFraction(period time.Duration, fraction float64) time.Duration
{ fixed := time.Duration(float64(period) * (1 - fraction)) return fixed + Dur(2*(period-fixed)) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L118-L143
go
train
// Samples 'k' unique ints from the range [0, n)
func SampleInts(n int, k int) (res []int, err error)
// Samples 'k' unique ints from the range [0, n) func SampleInts(n int, k int) (res []int, err error)
{ if k < 0 { err = errors.Newf("invalid sample size k") return } if n < k { err = errors.Newf("sample size k larger than n") return } picked := set.NewSet() for picked.Len() < k { i := Intn(n) picked.Add(i) } res = make([]int, k) e := 0 for i := range picked.Iter() { res[e] = i.(int) e++ } return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L146-L159
go
train
// Samples 'k' elements from the given slice
func Sample(population []interface{}, k int) (res []interface{}, err error)
// Samples 'k' elements from the given slice func Sample(population []interface{}, k int) (res []interface{}, err error)
{ n := len(population) idxs, err := SampleInts(n, k) if err != nil { return } res = []interface{}{} for _, idx := range idxs { res = append(res, population[idx]) } return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L163-L184
go
train
// Same as 'Sample' except it returns both the 'picked' sample set and the // 'remaining' elements.
func PickN(population []interface{}, n int) ( picked []interface{}, remaining []interface{}, err error)
// Same as 'Sample' except it returns both the 'picked' sample set and the // 'remaining' elements. func PickN(population []interface{}, n int) ( picked []interface{}, remaining []interface{}, err error)
{ total := len(population) idxs, err := SampleInts(total, n) if err != nil { return } sort.Ints(idxs) picked, remaining = []interface{}{}, []interface{}{} for x, elem := range population { if len(idxs) > 0 && x == idxs[0] { picked = append(picked, elem) idxs = idxs[1:] } else { remaining = append(remaining, elem) } } return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
math2/rand2/rand.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/math2/rand2/rand.go#L195-L200
go
train
// Randomly shuffles the collection in place.
func Shuffle(collection Swapper)
// Randomly shuffles the collection in place. func Shuffle(collection Swapper)
{ // Fisher-Yates shuffle. for i := collection.Len() - 1; i >= 0; i-- { collection.Swap(i, Intn(i+1)) } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/semaphore.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/semaphore.go#L30-L38
go
train
// Create a bounded semaphore. The count parameter must be a positive number. // NOTE: The bounded semaphore will panic if the user tries to Release // beyond the specified count.
func NewBoundedSemaphore(count uint) Semaphore
// Create a bounded semaphore. The count parameter must be a positive number. // NOTE: The bounded semaphore will panic if the user tries to Release // beyond the specified count. func NewBoundedSemaphore(count uint) Semaphore
{ sem := &boundedSemaphore{ slots: make(chan struct{}, int(count)), } for i := 0; i < cap(sem.slots); i++ { sem.slots <- struct{}{} } return sem }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/semaphore.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/semaphore.go#L47-L70
go
train
// TryAcquire returns true if it acquires a resource slot within the // timeout, false otherwise.
func (sem *boundedSemaphore) TryAcquire(timeout time.Duration) bool
// TryAcquire returns true if it acquires a resource slot within the // timeout, false otherwise. func (sem *boundedSemaphore) TryAcquire(timeout time.Duration) bool
{ if timeout > 0 { // Wait until we get a slot or timeout expires. tm := time.NewTimer(timeout) defer tm.Stop() select { case <-sem.slots: return true case <-tm.C: // Timeout expired. In very rare cases this might happen even if // there is a slot available, e.g. GC pause after we create the timer // and select randomly picked this one out of the two available channels. // We should do one final immediate check below. } } // Return true if we have a slot available immediately and false otherwise. select { case <-sem.slots: return true default: return false } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/semaphore.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/semaphore.go#L90-L96
go
train
// This returns an unbound counting semaphore with the specified initial count. // The semaphore counter can be arbitrary large (i.e., Release can be called // unlimited amount of times). // // NOTE: In general, users should use bounded semaphore since it is more // efficient than unbounded semaphore.
func NewUnboundedSemaphore(initialCount int) Semaphore
// This returns an unbound counting semaphore with the specified initial count. // The semaphore counter can be arbitrary large (i.e., Release can be called // unlimited amount of times). // // NOTE: In general, users should use bounded semaphore since it is more // efficient than unbounded semaphore. func NewUnboundedSemaphore(initialCount int) Semaphore
{ res := &unboundedSemaphore{ counter: int64(initialCount), } res.cond.L = &res.lock return res }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L301-L317
go
train
// Returns a representation of sql function call "func_call(c[0], ..., c[n-1])
func SqlFunc(funcName string, expressions ...Expression) Expression
// Returns a representation of sql function call "func_call(c[0], ..., c[n-1]) func SqlFunc(funcName string, expressions ...Expression) Expression
{ f := &funcExpression{ funcName: funcName, } if len(expressions) > 0 { args := make([]Clause, len(expressions), len(expressions)) for i, expr := range expressions { args[i] = expr } f.args = &listClause{ clauses: args, includeParentheses: true, } } return f }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L349-L359
go
train
// Interval returns a representation of duration // in a form "INTERVAL `hour:min:sec:microsec` HOUR_MICROSECOND"
func Interval(duration time.Duration) Expression
// Interval returns a representation of duration // in a form "INTERVAL `hour:min:sec:microsec` HOUR_MICROSECOND" func Interval(duration time.Duration) Expression
{ negative := false if duration < 0 { negative = true duration = -duration } return &intervalExpression{ duration: duration, negative: negative, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L368-L374
go
train
// Returns an escaped literal string
func Literal(v interface{}) Expression
// Returns an escaped literal string func Literal(v interface{}) Expression
{ value, err := sqltypes.BuildValue(v) if err != nil { panic(errors.Wrap(err, "Invalid literal value")) } return &literalExpression{value: value} }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L441-L447
go
train
// Returns a representation of "a=b"
func Eq(lhs, rhs Expression) BoolExpression
// Returns a representation of "a=b" func Eq(lhs, rhs Expression) BoolExpression
{ lit, ok := rhs.(*literalExpression) if ok && sqltypes.Value(lit.value).IsNull() { return newBoolExpression(lhs, rhs, []byte(" IS ")) } return newBoolExpression(lhs, rhs, []byte("=")) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L469-L471
go
train
// Returns a representation of "a<b"
func Lt(lhs Expression, rhs Expression) BoolExpression
// Returns a representation of "a<b" func Lt(lhs Expression, rhs Expression) BoolExpression
{ return newBoolExpression(lhs, rhs, []byte("<")) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L596-L684
go
train
// Returns a representation of "a IN (b[0], ..., b[n-1])", where b is a list // of literals valList must be a slice type
func In(lhs Expression, valList interface{}) BoolExpression
// Returns a representation of "a IN (b[0], ..., b[n-1])", where b is a list // of literals valList must be a slice type func In(lhs Expression, valList interface{}) BoolExpression
{ var clauses []Clause switch val := valList.(type) { // This atrocious body of copy-paste code is due to the fact that if you // try to merge the cases, you can't treat val as a list case []int: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []int32: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []int64: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []uint: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []uint32: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []uint64: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []float64: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []string: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case [][]byte: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []time.Time: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []sqltypes.Numeric: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []sqltypes.Fractional: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []sqltypes.String: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } case []sqltypes.Value: clauses = make([]Clause, 0, len(val)) for _, v := range val { clauses = append(clauses, Literal(v)) } default: return &inExpression{ err: errors.Newf( "Unknown value list type in IN clause: %s", reflect.TypeOf(valList)), } } expr := &inExpression{lhs: lhs} if len(clauses) > 0 { expr.rhs = &listClause{clauses: clauses, includeParentheses: true} } return expr }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/expression.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/expression.go#L706-L714
go
train
// Returns a representation of an if-expression, of the form: // IF (BOOLEAN TEST, VALUE-IF-TRUE, VALUE-IF-FALSE)
func If(conditional BoolExpression, trueExpression Expression, falseExpression Expression) Expression
// Returns a representation of an if-expression, of the form: // IF (BOOLEAN TEST, VALUE-IF-TRUE, VALUE-IF-FALSE) func If(conditional BoolExpression, trueExpression Expression, falseExpression Expression) Expression
{ return &ifExpression{ conditional: conditional, trueExpression: trueExpression, falseExpression: falseExpression, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/raw_ascii_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/raw_ascii_client.go#L30-L38
go
train
// This creates a new memcache RawAsciiClient.
func NewRawAsciiClient(shard int, channel io.ReadWriter) ClientShard
// This creates a new memcache RawAsciiClient. func NewRawAsciiClient(shard int, channel io.ReadWriter) ClientShard
{ return &RawAsciiClient{ shard: shard, channel: channel, validState: true, writer: bufio.NewWriter(channel), reader: bufio.NewReader(channel), } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/string_fields.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/string_fields.go#L31-L66
go
train
// This continas field descriptors for string types as defined by sql/field.h. // In particular: // // Field (abstract) // | // ... // | // +--Field_str (abstract) // | +--Field_longstr // | | +--Field_string // | | +--Field_varstring // | | +--Field_blob // | | +--Field_geom // | | // | +--Field_null // | +--Field_enum // | +--Field_set // ... // This is used for extracting type / length info from string field's metadata.
func parseTypeAndLength(metadata []byte) ( fieldType mysql_proto.FieldType_Type, length int, remaining []byte, err error)
// This continas field descriptors for string types as defined by sql/field.h. // In particular: // // Field (abstract) // | // ... // | // +--Field_str (abstract) // | +--Field_longstr // | | +--Field_string // | | +--Field_varstring // | | +--Field_blob // | | +--Field_geom // | | // | +--Field_null // | +--Field_enum // | +--Field_set // ... // This is used for extracting type / length info from string field's metadata. func parseTypeAndLength(metadata []byte) ( fieldType mysql_proto.FieldType_Type, length int, remaining []byte, err error)
{ if len(metadata) < 2 { return mysql_proto.FieldType_STRING, 0, nil, errors.New( "not enough metadata bytes") } byte1 := int(metadata[0]) byte2 := int(metadata[1]) var realType mysql_proto.FieldType_Type if (byte1 & 0x30) != 0x30 { // see mysql issue #37426 realType = mysql_proto.FieldType_Type(byte1 | 0x30) length = byte2 | (((byte1 & 0x30) ^ 0x30) << 4) } else { realType = mysql_proto.FieldType_Type(byte1) length = byte2 } if realType != mysql_proto.FieldType_SET && realType != mysql_proto.FieldType_ENUM && realType != mysql_proto.FieldType_STRING && realType != mysql_proto.FieldType_VAR_STRING { return mysql_proto.FieldType_STRING, 0, nil, errors.Newf( "Invalid real type: %s (%d)", realType.String(), realType) } return realType, length, metadata[2:], nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/string_fields.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/string_fields.go#L69-L76
go
train
// This returns a field descriptor for FieldType_NULL (i.e., Field_null)
func NewNullFieldDescriptor(nullable NullableColumn) FieldDescriptor
// This returns a field descriptor for FieldType_NULL (i.e., Field_null) func NewNullFieldDescriptor(nullable NullableColumn) FieldDescriptor
{ // A null field can be nullable ... return newFixedLengthFieldDescriptor( mysql_proto.FieldType_NULL, nullable, 0, func(b []byte) interface{} { return nil }) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/string_fields.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/string_fields.go#L121-L136
go
train
// This returns a field descriptor for FieldType_VARCHAR (i.e., Field_varstring)
func NewVarcharFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
// This returns a field descriptor for FieldType_VARCHAR (i.e., Field_varstring) func NewVarcharFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
{ if len(metadata) < 2 { return nil, nil, errors.New("Metadata has too few bytes") } maxLen := int(LittleEndian.Uint16(metadata)) return NewStringFieldDescriptor( mysql_proto.FieldType_VARCHAR, nullable, maxLen), metadata[2:], nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/string_fields.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/string_fields.go#L195-L219
go
train
// This returns a field descriptor for FieldType_BLOB (i.e., Field_blob)
func NewBlobFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
// This returns a field descriptor for FieldType_BLOB (i.e., Field_blob) func NewBlobFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
{ if len(metadata) < 1 { return nil, nil, errors.New("Metadata has too few bytes") } packedLen := LittleEndian.Uint8(metadata) if packedLen > 4 { return nil, nil, errors.New("Invalid packed length") } return &blobFieldDescriptor{ packedLengthFieldDescriptor: packedLengthFieldDescriptor{ baseFieldDescriptor: baseFieldDescriptor{ fieldType: mysql_proto.FieldType_BLOB, isNullable: nullable, }, packedLength: int(packedLen), }, }, metadata[1:], nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/mock_log_file.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/mock_log_file.go#L40-L45
go
train
// Every function for writing into the MockLogFile should acquire the lock via either Write() // or writeWithHeader().
func (mlf *MockLogFile) Write(contents []byte)
// Every function for writing into the MockLogFile should acquire the lock via either Write() // or writeWithHeader(). func (mlf *MockLogFile) Write(contents []byte)
{ mlf.mu.Lock() defer mlf.mu.Unlock() mlf.logBuffer = append(mlf.logBuffer, contents...) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L32-L37
go
train
// Create a new BoundedRWLock with the given capacity. // // RLocks or WLocks beyond this capacity will fail fast with an error.
func NewBoundedRWLock(capacity int) *BoundedRWLock
// Create a new BoundedRWLock with the given capacity. // // RLocks or WLocks beyond this capacity will fail fast with an error. func NewBoundedRWLock(capacity int) *BoundedRWLock
{ return &BoundedRWLock{ waiters: make(chan *rwwait, capacity), control: &sync.Mutex{}, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L42-L66
go
train
// Wait for a read lock for up to 'timeout'. // // Error will be non-nil on timeout or when the wait list is at capacity.
func (rw *BoundedRWLock) RLock(timeout time.Duration) (err error)
// Wait for a read lock for up to 'timeout'. // // Error will be non-nil on timeout or when the wait list is at capacity. func (rw *BoundedRWLock) RLock(timeout time.Duration) (err error)
{ deadline := time.After(timeout) rw.control.Lock() if rw.nextWriter != nil { me := newWait(false) select { case rw.waiters <- me: default: err = errors.New("Waiter capacity reached in RLock") } rw.control.Unlock() if err != nil { return } woken := me.WaitAtomic(deadline) if !woken { return errors.New("Waiter timeout") } } else { rw.readers++ rw.control.Unlock() } return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L72-L79
go
train
// Unlock a read lock. // // Should be called only on a goroutine which has gotten a non-error return // value from RLock().
func (rw *BoundedRWLock) RUnlock()
// Unlock a read lock. // // Should be called only on a goroutine which has gotten a non-error return // value from RLock(). func (rw *BoundedRWLock) RUnlock()
{ rw.control.Lock() rw.readers-- if rw.readers == 0 { rw.processQueue() } rw.control.Unlock() }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L83-L118
go
train
// Lock for writing, waiting up to 'timeout' for successful exclusive // acquisition of the lock.
func (rw *BoundedRWLock) WLock(timeout time.Duration) (err error)
// Lock for writing, waiting up to 'timeout' for successful exclusive // acquisition of the lock. func (rw *BoundedRWLock) WLock(timeout time.Duration) (err error)
{ deadline := time.After(timeout) rw.control.Lock() if rw.readers != 0 || rw.nextWriter != nil { me := newWait(true) if rw.nextWriter == nil { rw.nextWriter = me } else { select { case rw.waiters <- me: default: err = errors.New("Waiter capacity reached in WLock") } } rw.control.Unlock() if err != nil { return } woken := me.WaitAtomic(deadline) if !woken { return errors.New("Waiter timeout") } rw.control.Lock() if rw.readers != 0 { panic("readers??") } if rw.nextWriter != me { panic("not me??") } } else { rw.nextWriter = newWait(true) } rw.control.Unlock() return }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L124-L129
go
train
// Unlock the write lock. // // Should be called only on a goroutine which has gotten a non-error return // value from WLock().
func (rw *BoundedRWLock) WUnlock()
// Unlock the write lock. // // Should be called only on a goroutine which has gotten a non-error return // value from WLock(). func (rw *BoundedRWLock) WUnlock()
{ rw.control.Lock() rw.nextWriter = nil rw.processQueue() rw.control.Unlock() }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L135-L174
go
train
// Walks the queue of eligible waiters (if any) and wakes them (if they're not // timed out). // // Any writer "stops" the walk of the queue.
func (rw *BoundedRWLock) processQueue()
// Walks the queue of eligible waiters (if any) and wakes them (if they're not // timed out). // // Any writer "stops" the walk of the queue. func (rw *BoundedRWLock) processQueue()
{ if rw.readers != 0 { panic("readers??") } if rw.nextWriter != nil { if rw.nextWriter.WakeAtomic() { return } rw.nextWriter = nil } for { var next *rwwait select { case next = <-rw.waiters: default: return } if next.writer { // No readers scheduled yet? if rw.readers == 0 { // If they wake up, no one else gets to go if next.WakeAtomic() { rw.nextWriter = next return } } else { rw.nextWriter = next return } } else { // Reader? Let them enter now. if next.WakeAtomic() { rw.readers++ } } } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L191-L204
go
train
// Wait for a signal on the waiter, with the guarantee that both goroutines // will agree on whether or not the signal was delivered. // // Returns true if the wake occurred, false on timeout.
func (wait *rwwait) WaitAtomic(after <-chan time.Time) bool
// Wait for a signal on the waiter, with the guarantee that both goroutines // will agree on whether or not the signal was delivered. // // Returns true if the wake occurred, false on timeout. func (wait *rwwait) WaitAtomic(after <-chan time.Time) bool
{ select { case <-wait.wake: return true case <-after: } swapped := atomic.CompareAndSwapInt32(&wait.alive, 1, 0) // They're gonna put it. if !swapped { <-wait.wake return true } return false }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
sync2/boundedrwlock.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/sync2/boundedrwlock.go#L210-L218
go
train
// Signal the wait to wake. // // Returns true of the waiter got the signal, false if the waiter timed out // before we could deliver the signal.
func (wait *rwwait) WakeAtomic() bool
// Signal the wait to wake. // // Returns true of the waiter got the signal, false if the waiter timed out // before we could deliver the signal. func (wait *rwwait) WakeAtomic() bool
{ swapped := atomic.CompareAndSwapInt32(&wait.alive, 1, 0) if !swapped { // They've moved on. return false } wait.wake <- true return true }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/xid_event.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/xid_event.go#L50-L63
go
train
// XidEventParser's Parse processes a raw xid event into a XidEvent.
func (p *XidEventParser) Parse(raw *RawV4Event) (Event, error)
// XidEventParser's Parse processes a raw xid event into a XidEvent. func (p *XidEventParser) Parse(raw *RawV4Event) (Event, error)
{ xe := &XidEvent{ Event: raw, } // For convenience, we'll interpret the bytes as little endian, our // dominate computing (intel) platform. _, err := readLittleEndian(raw.VariableLengthData(), &xe.xid) if err != nil { return raw, errors.Wrap(err, "Failed to read xid") } return xe, nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L58-L63
go
train
// This retrieves a single entry from memcache.
func (c *MockClient) Get(key string) GetResponse
// This retrieves a single entry from memcache. func (c *MockClient) Get(key string) GetResponse
{ c.mutex.Lock() defer c.mutex.Unlock() return c.getHelper(key) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L66-L75
go
train
// Batch version of the Get method.
func (c *MockClient) GetMulti(keys []string) map[string]GetResponse
// Batch version of the Get method. func (c *MockClient) GetMulti(keys []string) map[string]GetResponse
{ c.mutex.Lock() defer c.mutex.Unlock() res := make(map[string]GetResponse) for _, key := range keys { res[key] = c.getHelper(key) } return res }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L134-L139
go
train
// This sets a single entry into memcache. If the item's data version id // (aka CAS) is nonzero, the set operation can only succeed if the item // exists in memcache and has a same data version id.
func (c *MockClient) Set(item *Item) MutateResponse
// This sets a single entry into memcache. If the item's data version id // (aka CAS) is nonzero, the set operation can only succeed if the item // exists in memcache and has a same data version id. func (c *MockClient) Set(item *Item) MutateResponse
{ c.mutex.Lock() defer c.mutex.Unlock() return c.setHelper(item) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L143-L152
go
train
// Batch version of the Set method. Note that the response entries // ordering is undefined (i.e., may not match the input ordering).
func (c *MockClient) SetMulti(items []*Item) []MutateResponse
// Batch version of the Set method. Note that the response entries // ordering is undefined (i.e., may not match the input ordering). func (c *MockClient) SetMulti(items []*Item) []MutateResponse
{ c.mutex.Lock() defer c.mutex.Unlock() res := make([]MutateResponse, len(items)) for i, item := range items { res[i] = c.setHelper(item) } return res }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L206-L211
go
train
// This adds a single entry into memcache. Note: Add will fail if the // item already exist in memcache.
func (c *MockClient) Add(item *Item) MutateResponse
// This adds a single entry into memcache. Note: Add will fail if the // item already exist in memcache. func (c *MockClient) Add(item *Item) MutateResponse
{ c.mutex.Lock() defer c.mutex.Unlock() return c.addHelper(item) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L215-L224
go
train
// Batch version of the Add method. Note that the response entries // ordering is undefined (i.e., may not match the input ordering).
func (c *MockClient) AddMulti(items []*Item) []MutateResponse
// Batch version of the Add method. Note that the response entries // ordering is undefined (i.e., may not match the input ordering). func (c *MockClient) AddMulti(items []*Item) []MutateResponse
{ c.mutex.Lock() defer c.mutex.Unlock() res := make([]MutateResponse, len(items)) for i, item := range items { res[i] = c.addHelper(item) } return res }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L228-L232
go
train
// This replaces a single entry in memcache. Note: Replace will fail if // the does not exist in memcache.
func (c *MockClient) Replace(item *Item) MutateResponse
// This replaces a single entry in memcache. Note: Replace will fail if // the does not exist in memcache. func (c *MockClient) Replace(item *Item) MutateResponse
{ return NewMutateErrorResponse( item.Key, errors.Newf("Replace not implemented")) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L235-L260
go
train
// This deletes a single entry from memcache.
func (c *MockClient) Delete(key string) MutateResponse
// This deletes a single entry from memcache. func (c *MockClient) Delete(key string) MutateResponse
{ c.mutex.Lock() defer c.mutex.Unlock() if c.forceFailEverything { return NewMutateResponse( key, StatusInternalError, 0) } _, ok := c.data[key] if !ok { return NewMutateResponse( key, StatusKeyNotFound, 0) } delete(c.data, key) return NewMutateResponse( key, StatusNoError, 0) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L264-L270
go
train
// Batch version of the Delete method. Note that the response entries // ordering is undefined (i.e., may not match the input ordering)
func (c *MockClient) DeleteMulti(keys []string) []MutateResponse
// Batch version of the Delete method. Note that the response entries // ordering is undefined (i.e., may not match the input ordering) func (c *MockClient) DeleteMulti(keys []string) []MutateResponse
{ res := make([]MutateResponse, len(keys)) for i, key := range keys { res[i] = c.Delete(key) } return res }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L274-L276
go
train
// This appends the value bytes to the end of an existing entry. Note that // this does not allow you to extend past the item limit.
func (c *MockClient) Append(key string, value []byte) MutateResponse
// This appends the value bytes to the end of an existing entry. Note that // this does not allow you to extend past the item limit. func (c *MockClient) Append(key string, value []byte) MutateResponse
{ return NewMutateErrorResponse(key, errors.Newf("Append not implemented")) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L355-L365
go
train
// This increments the key's counter by delta. If the counter does not // exist, one of two things may happen: // 1. If the expiration value is all one-bits (0xffffffff), the operation // will fail with StatusNotFound. // 2. For all other expiration values, the operation will succeed by // seeding the value for this key with the provided initValue to expire // with the provided expiration time. The flags will be set to zero. // // NOTE: // 1. If you want to set the value of the counter with add/set/replace, // the objects data must be the ascii representation of the value and // not the byte values of a 64 bit integer. // 2. Incrementing the counter may cause the counter to wrap.
func (c *MockClient) Increment( key string, delta uint64, initValue uint64, expiration uint32) CountResponse
// This increments the key's counter by delta. If the counter does not // exist, one of two things may happen: // 1. If the expiration value is all one-bits (0xffffffff), the operation // will fail with StatusNotFound. // 2. For all other expiration values, the operation will succeed by // seeding the value for this key with the provided initValue to expire // with the provided expiration time. The flags will be set to zero. // // NOTE: // 1. If you want to set the value of the counter with add/set/replace, // the objects data must be the ascii representation of the value and // not the byte values of a 64 bit integer. // 2. Incrementing the counter may cause the counter to wrap. func (c *MockClient) Increment( key string, delta uint64, initValue uint64, expiration uint32) CountResponse
{ c.mutex.Lock() defer c.mutex.Unlock() return c.incrementDecrementHelper(key, delta, initValue, expiration, Increment) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L395-L402
go
train
// This invalidates all existing cache items after expiration number of // seconds.
func (c *MockClient) Flush(expiration uint32) Response
// This invalidates all existing cache items after expiration number of // seconds. func (c *MockClient) Flush(expiration uint32) Response
{ c.mutex.Lock() defer c.mutex.Unlock() // TODO(patrick): Use expiration argument c.data = make(map[string]*Item) return NewResponse(StatusNoError) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
memcache/mock_client.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/memcache/mock_client.go#L406-L408
go
train
// This requests the server statistics. When the key is an empty string, // the server will respond with a "default" set of statistics information.
func (c *MockClient) Stat(statsKey string) StatResponse
// This requests the server statistics. When the key is an empty string, // the server will respond with a "default" set of statistics information. func (c *MockClient) Stat(statsKey string) StatResponse
{ return NewStatErrorResponse(errors.Newf("Stat not implemented"), nil) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/ip.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/ip.go#L19-L28
go
train
// Like os.Hostname but caches first successful result, making it cheap to call it // over and over. // It will also crash whole process if fetching Hostname fails!
func MyHostname() string
// Like os.Hostname but caches first successful result, making it cheap to call it // over and over. // It will also crash whole process if fetching Hostname fails! func MyHostname() string
{ myHostnameOnce.Do(func() { var err error myHostname, err = os.Hostname() if err != nil { log.Fatal(err) } }) return myHostname }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/ip.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/ip.go#L36-L45
go
train
// Resolves `MyHostname()` to an Ip4 address. Caches first successful result, making it // cheap to call it over and over. // It will also crash whole process if resolving the IP fails!
func MyIp4() *net.IPAddr
// Resolves `MyHostname()` to an Ip4 address. Caches first successful result, making it // cheap to call it over and over. // It will also crash whole process if resolving the IP fails! func MyIp4() *net.IPAddr
{ myIp4Once.Do(func() { var err error myIp4, err = net.ResolveIPAddr("ip4", MyHostname()) if err != nil { log.Fatal(err) } }) return myIp4 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/ip.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/ip.go#L53-L62
go
train
// Resolves `MyHostname()` to an Ip6 address. Caches first successful result, making it // cheap to call it over and over. // It will also crash whole process if resolving the IP fails!
func MyIp6() *net.IPAddr
// Resolves `MyHostname()` to an Ip6 address. Caches first successful result, making it // cheap to call it over and over. // It will also crash whole process if resolving the IP fails! func MyIp6() *net.IPAddr
{ myIp6Once.Do(func() { var err error myIp6, err = net.ResolveIPAddr("ip6", MyHostname()) if err != nil { log.Fatal(err) } }) return myIp6 }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/ip.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/ip.go#L68-L99
go
train
// This returns the list of local ip addresses which other hosts can connect // to (NOTE: Loopback ip is ignored). // Also resolves Hostname to an address and adds it to the list too, so // IPs from /etc/hosts can work too.
func GetLocalIPs() ([]*net.IP, error)
// This returns the list of local ip addresses which other hosts can connect // to (NOTE: Loopback ip is ignored). // Also resolves Hostname to an address and adds it to the list too, so // IPs from /etc/hosts can work too. func GetLocalIPs() ([]*net.IP, error)
{ hostname, err := os.Hostname() if err != nil { return nil, errors.Wrap(err, "Failed to lookup hostname") } // Resolves IP Address from Hostname, this way overrides in /etc/hosts // can work too for IP resolution. ipInfo, err := net.ResolveIPAddr("ip4", hostname) if err != nil { return nil, errors.Wrap(err, "Failed to resolve ip") } ips := []*net.IP{&ipInfo.IP} // TODO(zviad): Is rest of the code really necessary? addrs, err := net.InterfaceAddrs() if err != nil { return nil, errors.Wrap(err, "Failed to get interface addresses.") } for _, addr := range addrs { ipnet, ok := addr.(*net.IPNet) if !ok { continue } if ipnet.IP.IsLoopback() { continue } ips = append(ips, &ipnet.IP) } return ips, nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
net2/ip.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/net2/ip.go#L138-L158
go
train
// Resolves hostnames in addresses to actual IP4 addresses. Skips all invalid addresses // and all addresses that can't be resolved. // `addrs` are assumed to be of form: ["<hostname>:<port>", ...] // Returns an error in addition to resolved addresses if not all resolutions succeed.
func ResolveIP4s(addrs []string) ([]string, error)
// Resolves hostnames in addresses to actual IP4 addresses. Skips all invalid addresses // and all addresses that can't be resolved. // `addrs` are assumed to be of form: ["<hostname>:<port>", ...] // Returns an error in addition to resolved addresses if not all resolutions succeed. func ResolveIP4s(addrs []string) ([]string, error)
{ resolvedAddrs := make([]string, 0, len(addrs)) var lastErr error for _, server := range addrs { hostPort := strings.Split(server, ":") if len(hostPort) != 2 { lastErr = errors.Newf( "Skipping invalid address: %s", server) continue } ip, err := net.ResolveIPAddr("ip4", hostPort[0]) if err != nil { lastErr = err continue } resolvedAddrs = append(resolvedAddrs, ip.IP.String()+":"+hostPort[1]) } return resolvedAddrs, lastErr }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/event_reader.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/event_reader.go#L52-L61
go
train
// This returns true if the error returned by the event parser is retryable.
func IsRetryableError(err error) bool
// This returns true if the error returned by the event parser is retryable. func IsRetryableError(err error) bool
{ if err == io.EOF { return true } if _, ok := err.(*FailedToOpenFileError); ok { return true } return false }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L107-L114
go
train
// // UNION SELECT Statement ====================================================== //
func Union(selects ...SelectStatement) UnionStatement
// // UNION SELECT Statement ====================================================== // func Union(selects ...SelectStatement) UnionStatement
{ return &unionStatementImpl{ selects: selects, limit: -1, offset: -1, unique: true, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L142-L148
go
train
// Further filter the query, instead of replacing the filter
func (us *unionStatementImpl) AndWhere(expression BoolExpression) UnionStatement
// Further filter the query, instead of replacing the filter func (us *unionStatementImpl) AndWhere(expression BoolExpression) UnionStatement
{ if us.where == nil { return us.Where(expression) } us.where = And(us.where, expression) return us }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L278-L291
go
train
// // SELECT Statement ============================================================ //
func newSelectStatement( table ReadableTable, projections []Projection) SelectStatement
// // SELECT Statement ============================================================ // func newSelectStatement( table ReadableTable, projections []Projection) SelectStatement
{ return &selectStatementImpl{ table: table, projections: projections, limit: -1, offset: -1, withSharedLock: false, forUpdate: false, distinct: false, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L314-L322
go
train
// Further filter the query, instead of replacing the filter
func (q *selectStatementImpl) AndWhere( expression BoolExpression) SelectStatement
// Further filter the query, instead of replacing the filter func (q *selectStatementImpl) AndWhere( expression BoolExpression) SelectStatement
{ if q.where == nil { return q.Where(expression) } q.where = And(q.where, expression) return q }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L386-L466
go
train
// Return the properly escaped SQL statement, against the specified database
func (q *selectStatementImpl) String(database string) (sql string, err error)
// Return the properly escaped SQL statement, against the specified database func (q *selectStatementImpl) String(database string) (sql string, err error)
{ if !validIdentifierName(database) { return "", errors.New("Invalid database name specified") } buf := new(bytes.Buffer) _, _ = buf.WriteString("SELECT ") if err = writeComment(q.comment, buf); err != nil { return } if q.distinct { _, _ = buf.WriteString("DISTINCT ") } if q.projections == nil || len(q.projections) == 0 { return "", errors.Newf( "No column selected. Generated sql: %s", buf.String()) } for i, col := range q.projections { if i > 0 { _ = buf.WriteByte(',') } if col == nil { return "", errors.Newf( "nil column selected. Generated sql: %s", buf.String()) } if err = col.SerializeSqlForColumnList(buf); err != nil { return } } _, _ = buf.WriteString(" FROM ") if q.table == nil { return "", errors.Newf("nil table. Generated sql: %s", buf.String()) } if err = q.table.SerializeSql(database, buf); err != nil { return } if q.where != nil { _, _ = buf.WriteString(" WHERE ") if err = q.where.SerializeSql(buf); err != nil { return } } if q.group != nil { _, _ = buf.WriteString(" GROUP BY ") if err = q.group.SerializeSql(buf); err != nil { return } } if q.order != nil { _, _ = buf.WriteString(" ORDER BY ") if err = q.order.SerializeSql(buf); err != nil { return } } if q.limit >= 0 { if q.offset >= 0 { _, _ = buf.WriteString(fmt.Sprintf(" LIMIT %d, %d", q.offset, q.limit)) } else { _, _ = buf.WriteString(fmt.Sprintf(" LIMIT %d", q.limit)) } } if q.forUpdate { _, _ = buf.WriteString(" FOR UPDATE") } else if q.withSharedLock { _, _ = buf.WriteString(" LOCK IN SHARE MODE") } return buf.String(), nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L472-L482
go
train
// // INSERT Statement ============================================================ //
func newInsertStatement( t WritableTable, columns ...NonAliasColumn) InsertStatement
// // INSERT Statement ============================================================ // func newInsertStatement( t WritableTable, columns ...NonAliasColumn) InsertStatement
{ return &insertStatementImpl{ table: t, columns: columns, rows: make([][]Expression, 0, 1), onDuplicateKeyUpdates: make([]columnAssignment, 0, 0), } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L651-L657
go
train
// // UPDATE statement =========================================================== //
func newUpdateStatement(table WritableTable) UpdateStatement
// // UPDATE statement =========================================================== // func newUpdateStatement(table WritableTable) UpdateStatement
{ return &updateStatementImpl{ table: table, updateValues: make(map[NonAliasColumn]Expression), limit: -1, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L899-L902
go
train
// AddReadLock takes read lock on the table.
func (s *lockStatementImpl) AddReadLock(t *Table) LockStatement
// AddReadLock takes read lock on the table. func (s *lockStatementImpl) AddReadLock(t *Table) LockStatement
{ s.locks = append(s.locks, tableLock{t: t, w: false}) return s }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L905-L908
go
train
// AddWriteLock takes write lock on the table.
func (s *lockStatementImpl) AddWriteLock(t *Table) LockStatement
// AddWriteLock takes write lock on the table. func (s *lockStatementImpl) AddWriteLock(t *Table) LockStatement
{ s.locks = append(s.locks, tableLock{t: t, w: true}) return s }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqlbuilder/statement.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqlbuilder/statement.go#L959-L964
go
train
// Set GTID_NEXT statement returns a SQL statement that can be used to explicitly set the next GTID.
func NewGtidNextStatement(sid []byte, gno uint64) GtidNextStatement
// Set GTID_NEXT statement returns a SQL statement that can be used to explicitly set the next GTID. func NewGtidNextStatement(sid []byte, gno uint64) GtidNextStatement
{ return &gtidNextStatementImpl{ sid: sid, gno: gno, } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/gtid_log_event.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/gtid_log_event.go#L53-L88
go
train
// GtidLogEventParser's Parse processes a raw gtid log event into a GtidLogEvent.
func (p *GtidLogEventParser) Parse(raw *RawV4Event) (Event, error)
// GtidLogEventParser's Parse processes a raw gtid log event into a GtidLogEvent. func (p *GtidLogEventParser) Parse(raw *RawV4Event) (Event, error)
{ gle := &GtidLogEvent{ Event: raw, } if len(raw.VariableLengthData()) > 0 { return raw, errors.New("GTID binlog event larger than expected size") } data := raw.FixedLengthData() var commitData uint8 data, err := readLittleEndian(data, &commitData) if err != nil { return raw, errors.Wrap(err, "Failed to read commit flag") } if commitData == 0 { gle.commit = false } else if commitData == 1 { gle.commit = true } else { return raw, errors.Newf("Commit data is not 0 or 1: %d", commitData) } data, err = readLittleEndian(data, &gle.sid) if err != nil { return raw, errors.Wrap(err, "Failed to read sid") } data, err = readLittleEndian(data, &gle.gno) if err != nil { return raw, errors.Wrap(err, "Failed to read GNO") } return gle, nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/binlog/bit_fields.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/binlog/bit_fields.go#L28-L44
go
train
// This returns a field descriptor for FieldType_BIT (i.e., Field_bit_as_char)
func NewBitFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
// This returns a field descriptor for FieldType_BIT (i.e., Field_bit_as_char) func NewBitFieldDescriptor(nullable NullableColumn, metadata []byte) ( fd FieldDescriptor, remaining []byte, err error)
{ if len(metadata) < 2 { return nil, nil, errors.New("Metadata has too few bytes") } return &bitFieldDescriptor{ baseFieldDescriptor: baseFieldDescriptor{ fieldType: mysql_proto.FieldType_BIT, isNullable: nullable, }, numBits: ((uint16(metadata[0]) * 8) + uint16(metadata[1])), }, metadata[2:], nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L30-L45
go
train
// This returns a MultiResourcePool, which manages multiple // resource location entries. The handles to each resource location // entry acts independently. // // When createPool is nil, NewSimpleResourcePool is used as default.
func NewMultiResourcePool( options Options, createPool func(Options) ResourcePool) ResourcePool
// This returns a MultiResourcePool, which manages multiple // resource location entries. The handles to each resource location // entry acts independently. // // When createPool is nil, NewSimpleResourcePool is used as default. func NewMultiResourcePool( options Options, createPool func(Options) ResourcePool) ResourcePool
{ if createPool == nil { createPool = NewSimpleResourcePool } return &multiResourcePool{ options: options, createPool: createPool, rwMutex: sync.RWMutex{}, isLameDuck: false, locationPools: make(map[string]ResourcePool), } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L48-L58
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) NumActive() int32
// See ResourcePool for documentation. func (p *multiResourcePool) NumActive() int32
{ total := int32(0) p.rwMutex.RLock() defer p.rwMutex.RUnlock() for _, pool := range p.locationPools { total += pool.NumActive() } return total }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L61-L74
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) ActiveHighWaterMark() int32
// See ResourcePool for documentation. func (p *multiResourcePool) ActiveHighWaterMark() int32
{ high := int32(0) p.rwMutex.RLock() defer p.rwMutex.RUnlock() for _, pool := range p.locationPools { val := pool.ActiveHighWaterMark() if val > high { high = val } } return high }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L77-L87
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) NumIdle() int
// See ResourcePool for documentation. func (p *multiResourcePool) NumIdle() int
{ total := 0 p.rwMutex.RLock() defer p.rwMutex.RUnlock() for _, pool := range p.locationPools { total += pool.NumIdle() } return total }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L90-L115
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) Register(resourceLocation string) error
// See ResourcePool for documentation. func (p *multiResourcePool) Register(resourceLocation string) error
{ if resourceLocation == "" { return errors.New("Registering invalid resource location") } p.rwMutex.Lock() defer p.rwMutex.Unlock() if p.isLameDuck { return errors.Newf( "Cannot register %s to lame duck resource pool", resourceLocation) } if _, inMap := p.locationPools[resourceLocation]; inMap { return nil } pool := p.createPool(p.options) if err := pool.Register(resourceLocation); err != nil { return err } p.locationPools[resourceLocation] = pool return nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L118-L128
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) Unregister(resourceLocation string) error
// See ResourcePool for documentation. func (p *multiResourcePool) Unregister(resourceLocation string) error
{ p.rwMutex.Lock() defer p.rwMutex.Unlock() if pool, inMap := p.locationPools[resourceLocation]; inMap { _ = pool.Unregister("") pool.EnterLameDuckMode() delete(p.locationPools, resourceLocation) } return nil }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L143-L153
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) Get( resourceLocation string) (ManagedHandle, error)
// See ResourcePool for documentation. func (p *multiResourcePool) Get( resourceLocation string) (ManagedHandle, error)
{ pool := p.getPool(resourceLocation) if pool == nil { return nil, errors.Newf( "%s is not registered in the resource pool", resourceLocation) } return pool.Get(resourceLocation) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L156-L165
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) Release(handle ManagedHandle) error
// See ResourcePool for documentation. func (p *multiResourcePool) Release(handle ManagedHandle) error
{ pool := p.getPool(handle.ResourceLocation()) if pool == nil { return errors.New( "Resource pool cannot take control of a handle owned " + "by another resource pool") } return pool.Release(handle) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
resource_pool/multi_resource_pool.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/resource_pool/multi_resource_pool.go#L180-L189
go
train
// See ResourcePool for documentation.
func (p *multiResourcePool) EnterLameDuckMode()
// See ResourcePool for documentation. func (p *multiResourcePool) EnterLameDuckMode()
{ p.rwMutex.Lock() defer p.rwMutex.Unlock() p.isLameDuck = true for _, pool := range p.locationPools { pool.EnterLameDuckMode() } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L79-L84
go
train
// Raw returns the raw bytes. All types are currently implemented as []byte.
func (v Value) Raw() []byte
// Raw returns the raw bytes. All types are currently implemented as []byte. func (v Value) Raw() []byte
{ if v.Inner == nil { return nil } return v.Inner.raw() }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L87-L92
go
train
// String returns the raw value as a string
func (v Value) String() string
// String returns the raw value as a string func (v Value) String() string
{ if v.Inner == nil { return "" } return string(v.Inner.raw()) }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L95-L103
go
train
// EncodeSql encodes the value into an SQL statement. Can be binary.
func (v Value) EncodeSql(b encoding2.BinaryWriter)
// EncodeSql encodes the value into an SQL statement. Can be binary. func (v Value) EncodeSql(b encoding2.BinaryWriter)
{ if v.Inner == nil { if _, err := b.Write(nullstr); err != nil { panic(err) } } else { v.Inner.encodeSql(b) } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L106-L114
go
train
// EncodeAscii encodes the value using 7-bit clean ascii bytes.
func (v Value) EncodeAscii(b encoding2.BinaryWriter)
// EncodeAscii encodes the value using 7-bit clean ascii bytes. func (v Value) EncodeAscii(b encoding2.BinaryWriter)
{ if v.Inner == nil { if _, err := b.Write(nullstr); err != nil { panic(err) } } else { v.Inner.encodeAscii(b) } }
dropbox/godropbox
5749d3b71cbefd8eacc316df3f0a6fcb9991bb51
database/sqltypes/sqltypes.go
https://github.com/dropbox/godropbox/blob/5749d3b71cbefd8eacc316df3f0a6fcb9991bb51/database/sqltypes/sqltypes.go#L117-L122
go
train
// MarshalBinary helps implement BinaryMarshaler interface for Value.
func (v Value) MarshalBinary() ([]byte, error)
// MarshalBinary helps implement BinaryMarshaler interface for Value. func (v Value) MarshalBinary() ([]byte, error)
{ if v.IsNull() { return []byte{byte(NullType)}, nil } return v.Inner.MarshalBinary() }