repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
btcsuite/btcutil | coinset/coins.go | Coins | func (cs *CoinSet) Coins() []Coin {
coins := make([]Coin, cs.coinList.Len())
for i, e := 0, cs.coinList.Front(); e != nil; i, e = i+1, e.Next() {
coins[i] = e.Value.(Coin)
}
return coins
} | go | func (cs *CoinSet) Coins() []Coin {
coins := make([]Coin, cs.coinList.Len())
for i, e := 0, cs.coinList.Front(); e != nil; i, e = i+1, e.Next() {
coins[i] = e.Value.(Coin)
}
return coins
} | [
"func",
"(",
"cs",
"*",
"CoinSet",
")",
"Coins",
"(",
")",
"[",
"]",
"Coin",
"{",
"coins",
":=",
"make",
"(",
"[",
"]",
"Coin",
",",
"cs",
".",
"coinList",
".",
"Len",
"(",
")",
")",
"\n",
"for",
"i",
",",
"e",
":=",
"0",
",",
"cs",
".",
... | // Coins returns a new slice of the coins contained in the set. | [
"Coins",
"returns",
"a",
"new",
"slice",
"of",
"the",
"coins",
"contained",
"in",
"the",
"set",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L64-L70 | train |
btcsuite/btcutil | coinset/coins.go | PushCoin | func (cs *CoinSet) PushCoin(c Coin) {
cs.coinList.PushBack(c)
cs.totalValue += c.Value()
cs.totalValueAge += c.ValueAge()
} | go | func (cs *CoinSet) PushCoin(c Coin) {
cs.coinList.PushBack(c)
cs.totalValue += c.Value()
cs.totalValueAge += c.ValueAge()
} | [
"func",
"(",
"cs",
"*",
"CoinSet",
")",
"PushCoin",
"(",
"c",
"Coin",
")",
"{",
"cs",
".",
"coinList",
".",
"PushBack",
"(",
"c",
")",
"\n",
"cs",
".",
"totalValue",
"+=",
"c",
".",
"Value",
"(",
")",
"\n",
"cs",
".",
"totalValueAge",
"+=",
"c",
... | // PushCoin adds a coin to the end of the list and updates
// the cached value amounts. | [
"PushCoin",
"adds",
"a",
"coin",
"to",
"the",
"end",
"of",
"the",
"list",
"and",
"updates",
"the",
"cached",
"value",
"amounts",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L90-L94 | train |
btcsuite/btcutil | coinset/coins.go | PopCoin | func (cs *CoinSet) PopCoin() Coin {
back := cs.coinList.Back()
if back == nil {
return nil
}
return cs.removeElement(back)
} | go | func (cs *CoinSet) PopCoin() Coin {
back := cs.coinList.Back()
if back == nil {
return nil
}
return cs.removeElement(back)
} | [
"func",
"(",
"cs",
"*",
"CoinSet",
")",
"PopCoin",
"(",
")",
"Coin",
"{",
"back",
":=",
"cs",
".",
"coinList",
".",
"Back",
"(",
")",
"\n",
"if",
"back",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"cs",
".",
"removeElement",
"(... | // PopCoin removes the last coin on the list and returns it. | [
"PopCoin",
"removes",
"the",
"last",
"coin",
"on",
"the",
"list",
"and",
"returns",
"it",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L97-L103 | train |
btcsuite/btcutil | coinset/coins.go | ShiftCoin | func (cs *CoinSet) ShiftCoin() Coin {
front := cs.coinList.Front()
if front == nil {
return nil
}
return cs.removeElement(front)
} | go | func (cs *CoinSet) ShiftCoin() Coin {
front := cs.coinList.Front()
if front == nil {
return nil
}
return cs.removeElement(front)
} | [
"func",
"(",
"cs",
"*",
"CoinSet",
")",
"ShiftCoin",
"(",
")",
"Coin",
"{",
"front",
":=",
"cs",
".",
"coinList",
".",
"Front",
"(",
")",
"\n",
"if",
"front",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"cs",
".",
"removeElement",... | // ShiftCoin removes the first coin on the list and returns it. | [
"ShiftCoin",
"removes",
"the",
"first",
"coin",
"on",
"the",
"list",
"and",
"returns",
"it",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L106-L112 | train |
btcsuite/btcutil | coinset/coins.go | removeElement | func (cs *CoinSet) removeElement(e *list.Element) Coin {
c := e.Value.(Coin)
cs.coinList.Remove(e)
cs.totalValue -= c.Value()
cs.totalValueAge -= c.ValueAge()
return c
} | go | func (cs *CoinSet) removeElement(e *list.Element) Coin {
c := e.Value.(Coin)
cs.coinList.Remove(e)
cs.totalValue -= c.Value()
cs.totalValueAge -= c.ValueAge()
return c
} | [
"func",
"(",
"cs",
"*",
"CoinSet",
")",
"removeElement",
"(",
"e",
"*",
"list",
".",
"Element",
")",
"Coin",
"{",
"c",
":=",
"e",
".",
"Value",
".",
"(",
"Coin",
")",
"\n",
"cs",
".",
"coinList",
".",
"Remove",
"(",
"e",
")",
"\n",
"cs",
".",
... | // removeElement updates the cached value amounts in the CoinSet,
// removes the element from the list, then returns the Coin that
// was removed to the caller. | [
"removeElement",
"updates",
"the",
"cached",
"value",
"amounts",
"in",
"the",
"CoinSet",
"removes",
"the",
"element",
"from",
"the",
"list",
"then",
"returns",
"the",
"Coin",
"that",
"was",
"removed",
"to",
"the",
"caller",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L117-L123 | train |
btcsuite/btcutil | coinset/coins.go | NewMsgTxWithInputCoins | func NewMsgTxWithInputCoins(txVersion int32, inputCoins Coins) *wire.MsgTx {
msgTx := wire.NewMsgTx(txVersion)
coins := inputCoins.Coins()
msgTx.TxIn = make([]*wire.TxIn, len(coins))
for i, coin := range coins {
msgTx.TxIn[i] = &wire.TxIn{
PreviousOutPoint: wire.OutPoint{
Hash: *coin.Hash(),
Index: coin.Index(),
},
SignatureScript: nil,
Sequence: wire.MaxTxInSequenceNum,
}
}
return msgTx
} | go | func NewMsgTxWithInputCoins(txVersion int32, inputCoins Coins) *wire.MsgTx {
msgTx := wire.NewMsgTx(txVersion)
coins := inputCoins.Coins()
msgTx.TxIn = make([]*wire.TxIn, len(coins))
for i, coin := range coins {
msgTx.TxIn[i] = &wire.TxIn{
PreviousOutPoint: wire.OutPoint{
Hash: *coin.Hash(),
Index: coin.Index(),
},
SignatureScript: nil,
Sequence: wire.MaxTxInSequenceNum,
}
}
return msgTx
} | [
"func",
"NewMsgTxWithInputCoins",
"(",
"txVersion",
"int32",
",",
"inputCoins",
"Coins",
")",
"*",
"wire",
".",
"MsgTx",
"{",
"msgTx",
":=",
"wire",
".",
"NewMsgTx",
"(",
"txVersion",
")",
"\n",
"coins",
":=",
"inputCoins",
".",
"Coins",
"(",
")",
"\n",
... | // NewMsgTxWithInputCoins takes the coins in the CoinSet and makes them
// the inputs to a new wire.MsgTx which is returned. | [
"NewMsgTxWithInputCoins",
"takes",
"the",
"coins",
"in",
"the",
"CoinSet",
"and",
"makes",
"them",
"the",
"inputs",
"to",
"a",
"new",
"wire",
".",
"MsgTx",
"which",
"is",
"returned",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L127-L142 | train |
btcsuite/btcutil | coinset/coins.go | CoinSelect | func (s MinIndexCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) {
cs := NewCoinSet(nil)
for n := 0; n < len(coins) && n < s.MaxInputs; n++ {
cs.PushCoin(coins[n])
if satisfiesTargetValue(targetValue, s.MinChangeAmount, cs.TotalValue()) {
return cs, nil
}
}
return nil, ErrCoinsNoSelectionAvailable
} | go | func (s MinIndexCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) {
cs := NewCoinSet(nil)
for n := 0; n < len(coins) && n < s.MaxInputs; n++ {
cs.PushCoin(coins[n])
if satisfiesTargetValue(targetValue, s.MinChangeAmount, cs.TotalValue()) {
return cs, nil
}
}
return nil, ErrCoinsNoSelectionAvailable
} | [
"func",
"(",
"s",
"MinIndexCoinSelector",
")",
"CoinSelect",
"(",
"targetValue",
"btcutil",
".",
"Amount",
",",
"coins",
"[",
"]",
"Coin",
")",
"(",
"Coins",
",",
"error",
")",
"{",
"cs",
":=",
"NewCoinSet",
"(",
"nil",
")",
"\n",
"for",
"n",
":=",
"... | // CoinSelect will attempt to select coins using the algorithm described
// in the MinIndexCoinSelector struct. | [
"CoinSelect",
"will",
"attempt",
"to",
"select",
"coins",
"using",
"the",
"algorithm",
"described",
"in",
"the",
"MinIndexCoinSelector",
"struct",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L181-L190 | train |
btcsuite/btcutil | coinset/coins.go | CoinSelect | func (s MinNumberCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) {
sortedCoins := make([]Coin, 0, len(coins))
sortedCoins = append(sortedCoins, coins...)
sort.Sort(sort.Reverse(byAmount(sortedCoins)))
return MinIndexCoinSelector(s).CoinSelect(targetValue, sortedCoins)
} | go | func (s MinNumberCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) {
sortedCoins := make([]Coin, 0, len(coins))
sortedCoins = append(sortedCoins, coins...)
sort.Sort(sort.Reverse(byAmount(sortedCoins)))
return MinIndexCoinSelector(s).CoinSelect(targetValue, sortedCoins)
} | [
"func",
"(",
"s",
"MinNumberCoinSelector",
")",
"CoinSelect",
"(",
"targetValue",
"btcutil",
".",
"Amount",
",",
"coins",
"[",
"]",
"Coin",
")",
"(",
"Coins",
",",
"error",
")",
"{",
"sortedCoins",
":=",
"make",
"(",
"[",
"]",
"Coin",
",",
"0",
",",
... | // CoinSelect will attempt to select coins using the algorithm described
// in the MinNumberCoinSelector struct. | [
"CoinSelect",
"will",
"attempt",
"to",
"select",
"coins",
"using",
"the",
"algorithm",
"described",
"in",
"the",
"MinNumberCoinSelector",
"struct",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L202-L208 | train |
btcsuite/btcutil | coinset/coins.go | CoinSelect | func (s MinPriorityCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) {
possibleCoins := make([]Coin, 0, len(coins))
possibleCoins = append(possibleCoins, coins...)
sort.Sort(byValueAge(possibleCoins))
// find the first coin with sufficient valueAge
cutoffIndex := -1
for i := 0; i < len(possibleCoins); i++ {
if possibleCoins[i].ValueAge() >= s.MinAvgValueAgePerInput {
cutoffIndex = i
break
}
}
if cutoffIndex < 0 {
return nil, ErrCoinsNoSelectionAvailable
}
// create sets of input coins that will obey minimum average valueAge
for i := cutoffIndex; i < len(possibleCoins); i++ {
possibleHighCoins := possibleCoins[cutoffIndex : i+1]
// choose a set of high-enough valueAge coins
highSelect, err := (&MinNumberCoinSelector{
MaxInputs: s.MaxInputs,
MinChangeAmount: s.MinChangeAmount,
}).CoinSelect(targetValue, possibleHighCoins)
if err != nil {
// attempt to add available low priority to make a solution
for numLow := 1; numLow <= cutoffIndex && numLow+(i-cutoffIndex) <= s.MaxInputs; numLow++ {
allHigh := NewCoinSet(possibleCoins[cutoffIndex : i+1])
newTargetValue := targetValue - allHigh.TotalValue()
newMaxInputs := allHigh.Num() + numLow
if newMaxInputs > numLow {
newMaxInputs = numLow
}
newMinAvgValueAge := ((s.MinAvgValueAgePerInput * int64(allHigh.Num()+numLow)) - allHigh.TotalValueAge()) / int64(numLow)
// find the minimum priority that can be added to set
lowSelect, err := (&MinPriorityCoinSelector{
MaxInputs: newMaxInputs,
MinChangeAmount: s.MinChangeAmount,
MinAvgValueAgePerInput: newMinAvgValueAge,
}).CoinSelect(newTargetValue, possibleCoins[0:cutoffIndex])
if err != nil {
continue
}
for _, coin := range lowSelect.Coins() {
allHigh.PushCoin(coin)
}
return allHigh, nil
}
// oh well, couldn't fix, try to add more high priority to the set.
} else {
extendedCoins := NewCoinSet(highSelect.Coins())
// attempt to lower priority towards target with lowest ones first
for n := 0; n < cutoffIndex; n++ {
if extendedCoins.Num() >= s.MaxInputs {
break
}
if possibleCoins[n].ValueAge() == 0 {
continue
}
extendedCoins.PushCoin(possibleCoins[n])
if extendedCoins.TotalValueAge()/int64(extendedCoins.Num()) < s.MinAvgValueAgePerInput {
extendedCoins.PopCoin()
continue
}
}
return extendedCoins, nil
}
}
return nil, ErrCoinsNoSelectionAvailable
} | go | func (s MinPriorityCoinSelector) CoinSelect(targetValue btcutil.Amount, coins []Coin) (Coins, error) {
possibleCoins := make([]Coin, 0, len(coins))
possibleCoins = append(possibleCoins, coins...)
sort.Sort(byValueAge(possibleCoins))
// find the first coin with sufficient valueAge
cutoffIndex := -1
for i := 0; i < len(possibleCoins); i++ {
if possibleCoins[i].ValueAge() >= s.MinAvgValueAgePerInput {
cutoffIndex = i
break
}
}
if cutoffIndex < 0 {
return nil, ErrCoinsNoSelectionAvailable
}
// create sets of input coins that will obey minimum average valueAge
for i := cutoffIndex; i < len(possibleCoins); i++ {
possibleHighCoins := possibleCoins[cutoffIndex : i+1]
// choose a set of high-enough valueAge coins
highSelect, err := (&MinNumberCoinSelector{
MaxInputs: s.MaxInputs,
MinChangeAmount: s.MinChangeAmount,
}).CoinSelect(targetValue, possibleHighCoins)
if err != nil {
// attempt to add available low priority to make a solution
for numLow := 1; numLow <= cutoffIndex && numLow+(i-cutoffIndex) <= s.MaxInputs; numLow++ {
allHigh := NewCoinSet(possibleCoins[cutoffIndex : i+1])
newTargetValue := targetValue - allHigh.TotalValue()
newMaxInputs := allHigh.Num() + numLow
if newMaxInputs > numLow {
newMaxInputs = numLow
}
newMinAvgValueAge := ((s.MinAvgValueAgePerInput * int64(allHigh.Num()+numLow)) - allHigh.TotalValueAge()) / int64(numLow)
// find the minimum priority that can be added to set
lowSelect, err := (&MinPriorityCoinSelector{
MaxInputs: newMaxInputs,
MinChangeAmount: s.MinChangeAmount,
MinAvgValueAgePerInput: newMinAvgValueAge,
}).CoinSelect(newTargetValue, possibleCoins[0:cutoffIndex])
if err != nil {
continue
}
for _, coin := range lowSelect.Coins() {
allHigh.PushCoin(coin)
}
return allHigh, nil
}
// oh well, couldn't fix, try to add more high priority to the set.
} else {
extendedCoins := NewCoinSet(highSelect.Coins())
// attempt to lower priority towards target with lowest ones first
for n := 0; n < cutoffIndex; n++ {
if extendedCoins.Num() >= s.MaxInputs {
break
}
if possibleCoins[n].ValueAge() == 0 {
continue
}
extendedCoins.PushCoin(possibleCoins[n])
if extendedCoins.TotalValueAge()/int64(extendedCoins.Num()) < s.MinAvgValueAgePerInput {
extendedCoins.PopCoin()
continue
}
}
return extendedCoins, nil
}
}
return nil, ErrCoinsNoSelectionAvailable
} | [
"func",
"(",
"s",
"MinPriorityCoinSelector",
")",
"CoinSelect",
"(",
"targetValue",
"btcutil",
".",
"Amount",
",",
"coins",
"[",
"]",
"Coin",
")",
"(",
"Coins",
",",
"error",
")",
"{",
"possibleCoins",
":=",
"make",
"(",
"[",
"]",
"Coin",
",",
"0",
","... | // CoinSelect will attempt to select coins using the algorithm described
// in the MinPriorityCoinSelector struct. | [
"CoinSelect",
"will",
"attempt",
"to",
"select",
"coins",
"using",
"the",
"algorithm",
"described",
"in",
"the",
"MinPriorityCoinSelector",
"struct",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L250-L331 | train |
btcsuite/btcutil | coinset/coins.go | txOut | func (c *SimpleCoin) txOut() *wire.TxOut {
return c.Tx.MsgTx().TxOut[c.TxIndex]
} | go | func (c *SimpleCoin) txOut() *wire.TxOut {
return c.Tx.MsgTx().TxOut[c.TxIndex]
} | [
"func",
"(",
"c",
"*",
"SimpleCoin",
")",
"txOut",
"(",
")",
"*",
"wire",
".",
"TxOut",
"{",
"return",
"c",
".",
"Tx",
".",
"MsgTx",
"(",
")",
".",
"TxOut",
"[",
"c",
".",
"TxIndex",
"]",
"\n",
"}"
] | // txOut returns the TxOut of the transaction the Coin represents | [
"txOut",
"returns",
"the",
"TxOut",
"of",
"the",
"transaction",
"the",
"Coin",
"represents"
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/coinset/coins.go#L368-L370 | train |
btcsuite/btcutil | gcs/builder/builder.go | DeriveKey | func DeriveKey(keyHash *chainhash.Hash) [gcs.KeySize]byte {
var key [gcs.KeySize]byte
copy(key[:], keyHash.CloneBytes()[:])
return key
} | go | func DeriveKey(keyHash *chainhash.Hash) [gcs.KeySize]byte {
var key [gcs.KeySize]byte
copy(key[:], keyHash.CloneBytes()[:])
return key
} | [
"func",
"DeriveKey",
"(",
"keyHash",
"*",
"chainhash",
".",
"Hash",
")",
"[",
"gcs",
".",
"KeySize",
"]",
"byte",
"{",
"var",
"key",
"[",
"gcs",
".",
"KeySize",
"]",
"byte",
"\n",
"copy",
"(",
"key",
"[",
":",
"]",
",",
"keyHash",
".",
"CloneBytes"... | // DeriveKey is a utility function that derives a key from a chainhash.Hash by
// truncating the bytes of the hash to the appopriate key size. | [
"DeriveKey",
"is",
"a",
"utility",
"function",
"that",
"derives",
"a",
"key",
"from",
"a",
"chainhash",
".",
"Hash",
"by",
"truncating",
"the",
"bytes",
"of",
"the",
"hash",
"to",
"the",
"appopriate",
"key",
"size",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L63-L67 | train |
btcsuite/btcutil | gcs/builder/builder.go | Key | func (b *GCSBuilder) Key() ([gcs.KeySize]byte, error) {
// Do nothing if the builder's errored out.
if b.err != nil {
return [gcs.KeySize]byte{}, b.err
}
return b.key, nil
} | go | func (b *GCSBuilder) Key() ([gcs.KeySize]byte, error) {
// Do nothing if the builder's errored out.
if b.err != nil {
return [gcs.KeySize]byte{}, b.err
}
return b.key, nil
} | [
"func",
"(",
"b",
"*",
"GCSBuilder",
")",
"Key",
"(",
")",
"(",
"[",
"gcs",
".",
"KeySize",
"]",
"byte",
",",
"error",
")",
"{",
"// Do nothing if the builder's errored out.",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"[",
"gcs",
".",
"KeySize... | // Key retrieves the key with which the builder will build a filter. This is
// useful if the builder is created with a random initial key. | [
"Key",
"retrieves",
"the",
"key",
"with",
"which",
"the",
"builder",
"will",
"build",
"a",
"filter",
".",
"This",
"is",
"useful",
"if",
"the",
"builder",
"is",
"created",
"with",
"a",
"random",
"initial",
"key",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L71-L78 | train |
btcsuite/btcutil | gcs/builder/builder.go | AddHash | func (b *GCSBuilder) AddHash(hash *chainhash.Hash) *GCSBuilder {
// Do nothing if the builder's already errored out.
if b.err != nil {
return b
}
return b.AddEntry(hash.CloneBytes())
} | go | func (b *GCSBuilder) AddHash(hash *chainhash.Hash) *GCSBuilder {
// Do nothing if the builder's already errored out.
if b.err != nil {
return b
}
return b.AddEntry(hash.CloneBytes())
} | [
"func",
"(",
"b",
"*",
"GCSBuilder",
")",
"AddHash",
"(",
"hash",
"*",
"chainhash",
".",
"Hash",
")",
"*",
"GCSBuilder",
"{",
"// Do nothing if the builder's already errored out.",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"b",
"\n",
"}",
"\n\n",
... | // AddHash adds a chainhash.Hash to the list of entries to be included in the
// GCS filter when it's built. | [
"AddHash",
"adds",
"a",
"chainhash",
".",
"Hash",
"to",
"the",
"list",
"of",
"entries",
"to",
"be",
"included",
"in",
"the",
"GCS",
"filter",
"when",
"it",
"s",
"built",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L181-L188 | train |
btcsuite/btcutil | gcs/builder/builder.go | AddWitness | func (b *GCSBuilder) AddWitness(witness wire.TxWitness) *GCSBuilder {
// Do nothing if the builder's already errored out.
if b.err != nil {
return b
}
return b.AddEntries(witness)
} | go | func (b *GCSBuilder) AddWitness(witness wire.TxWitness) *GCSBuilder {
// Do nothing if the builder's already errored out.
if b.err != nil {
return b
}
return b.AddEntries(witness)
} | [
"func",
"(",
"b",
"*",
"GCSBuilder",
")",
"AddWitness",
"(",
"witness",
"wire",
".",
"TxWitness",
")",
"*",
"GCSBuilder",
"{",
"// Do nothing if the builder's already errored out.",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"b",
"\n",
"}",
"\n\n",
"... | // AddWitness adds each item of the passed filter stack to the filter, and then
// adds each item as a script. | [
"AddWitness",
"adds",
"each",
"item",
"of",
"the",
"passed",
"filter",
"stack",
"to",
"the",
"filter",
"and",
"then",
"adds",
"each",
"item",
"as",
"a",
"script",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L192-L199 | train |
btcsuite/btcutil | gcs/builder/builder.go | Build | func (b *GCSBuilder) Build() (*gcs.Filter, error) {
// Do nothing if the builder's already errored out.
if b.err != nil {
return nil, b.err
}
// We'll ensure that all the parmaters we need to actually build the
// filter properly are set.
if b.p == 0 {
return nil, fmt.Errorf("p value is not set, cannot build")
}
if b.m == 0 {
return nil, fmt.Errorf("m value is not set, cannot build")
}
dataSlice := make([][]byte, 0, len(b.data))
for item := range b.data {
dataSlice = append(dataSlice, []byte(item))
}
return gcs.BuildGCSFilter(b.p, b.m, b.key, dataSlice)
} | go | func (b *GCSBuilder) Build() (*gcs.Filter, error) {
// Do nothing if the builder's already errored out.
if b.err != nil {
return nil, b.err
}
// We'll ensure that all the parmaters we need to actually build the
// filter properly are set.
if b.p == 0 {
return nil, fmt.Errorf("p value is not set, cannot build")
}
if b.m == 0 {
return nil, fmt.Errorf("m value is not set, cannot build")
}
dataSlice := make([][]byte, 0, len(b.data))
for item := range b.data {
dataSlice = append(dataSlice, []byte(item))
}
return gcs.BuildGCSFilter(b.p, b.m, b.key, dataSlice)
} | [
"func",
"(",
"b",
"*",
"GCSBuilder",
")",
"Build",
"(",
")",
"(",
"*",
"gcs",
".",
"Filter",
",",
"error",
")",
"{",
"// Do nothing if the builder's already errored out.",
"if",
"b",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"b",
".",
"err",
... | // Build returns a function which builds a GCS filter with the given parameters
// and data. | [
"Build",
"returns",
"a",
"function",
"which",
"builds",
"a",
"GCS",
"filter",
"with",
"the",
"given",
"parameters",
"and",
"data",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L203-L224 | train |
btcsuite/btcutil | gcs/builder/builder.go | WithKeyPNM | func WithKeyPNM(key [gcs.KeySize]byte, p uint8, n uint32, m uint64) *GCSBuilder {
b := GCSBuilder{}
return b.SetKey(key).SetP(p).SetM(m).Preallocate(n)
} | go | func WithKeyPNM(key [gcs.KeySize]byte, p uint8, n uint32, m uint64) *GCSBuilder {
b := GCSBuilder{}
return b.SetKey(key).SetP(p).SetM(m).Preallocate(n)
} | [
"func",
"WithKeyPNM",
"(",
"key",
"[",
"gcs",
".",
"KeySize",
"]",
"byte",
",",
"p",
"uint8",
",",
"n",
"uint32",
",",
"m",
"uint64",
")",
"*",
"GCSBuilder",
"{",
"b",
":=",
"GCSBuilder",
"{",
"}",
"\n",
"return",
"b",
".",
"SetKey",
"(",
"key",
... | // WithKeyPNM creates a GCSBuilder with specified key and the passed
// probability, modulus and estimated filter size. | [
"WithKeyPNM",
"creates",
"a",
"GCSBuilder",
"with",
"specified",
"key",
"and",
"the",
"passed",
"probability",
"modulus",
"and",
"estimated",
"filter",
"size",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L228-L231 | train |
btcsuite/btcutil | gcs/builder/builder.go | WithKeyPM | func WithKeyPM(key [gcs.KeySize]byte, p uint8, m uint64) *GCSBuilder {
return WithKeyPNM(key, p, 0, m)
} | go | func WithKeyPM(key [gcs.KeySize]byte, p uint8, m uint64) *GCSBuilder {
return WithKeyPNM(key, p, 0, m)
} | [
"func",
"WithKeyPM",
"(",
"key",
"[",
"gcs",
".",
"KeySize",
"]",
"byte",
",",
"p",
"uint8",
",",
"m",
"uint64",
")",
"*",
"GCSBuilder",
"{",
"return",
"WithKeyPNM",
"(",
"key",
",",
"p",
",",
"0",
",",
"m",
")",
"\n",
"}"
] | // WithKeyPM creates a GCSBuilder with specified key and the passed
// probability. Estimated filter size is set to zero, which means more
// reallocations are done when building the filter. | [
"WithKeyPM",
"creates",
"a",
"GCSBuilder",
"with",
"specified",
"key",
"and",
"the",
"passed",
"probability",
".",
"Estimated",
"filter",
"size",
"is",
"set",
"to",
"zero",
"which",
"means",
"more",
"reallocations",
"are",
"done",
"when",
"building",
"the",
"f... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L236-L238 | train |
btcsuite/btcutil | gcs/builder/builder.go | WithKeyHashPNM | func WithKeyHashPNM(keyHash *chainhash.Hash, p uint8, n uint32,
m uint64) *GCSBuilder {
return WithKeyPNM(DeriveKey(keyHash), p, n, m)
} | go | func WithKeyHashPNM(keyHash *chainhash.Hash, p uint8, n uint32,
m uint64) *GCSBuilder {
return WithKeyPNM(DeriveKey(keyHash), p, n, m)
} | [
"func",
"WithKeyHashPNM",
"(",
"keyHash",
"*",
"chainhash",
".",
"Hash",
",",
"p",
"uint8",
",",
"n",
"uint32",
",",
"m",
"uint64",
")",
"*",
"GCSBuilder",
"{",
"return",
"WithKeyPNM",
"(",
"DeriveKey",
"(",
"keyHash",
")",
",",
"p",
",",
"n",
",",
"... | // WithKeyHashPNM creates a GCSBuilder with key derived from the specified
// chainhash.Hash and the passed probability and estimated filter size. | [
"WithKeyHashPNM",
"creates",
"a",
"GCSBuilder",
"with",
"key",
"derived",
"from",
"the",
"specified",
"chainhash",
".",
"Hash",
"and",
"the",
"passed",
"probability",
"and",
"estimated",
"filter",
"size",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L249-L253 | train |
btcsuite/btcutil | gcs/builder/builder.go | WithKeyHashPM | func WithKeyHashPM(keyHash *chainhash.Hash, p uint8, m uint64) *GCSBuilder {
return WithKeyHashPNM(keyHash, p, 0, m)
} | go | func WithKeyHashPM(keyHash *chainhash.Hash, p uint8, m uint64) *GCSBuilder {
return WithKeyHashPNM(keyHash, p, 0, m)
} | [
"func",
"WithKeyHashPM",
"(",
"keyHash",
"*",
"chainhash",
".",
"Hash",
",",
"p",
"uint8",
",",
"m",
"uint64",
")",
"*",
"GCSBuilder",
"{",
"return",
"WithKeyHashPNM",
"(",
"keyHash",
",",
"p",
",",
"0",
",",
"m",
")",
"\n",
"}"
] | // WithKeyHashPM creates a GCSBuilder with key derived from the specified
// chainhash.Hash and the passed probability. Estimated filter size is set to
// zero, which means more reallocations are done when building the filter. | [
"WithKeyHashPM",
"creates",
"a",
"GCSBuilder",
"with",
"key",
"derived",
"from",
"the",
"specified",
"chainhash",
".",
"Hash",
"and",
"the",
"passed",
"probability",
".",
"Estimated",
"filter",
"size",
"is",
"set",
"to",
"zero",
"which",
"means",
"more",
"real... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L258-L260 | train |
btcsuite/btcutil | gcs/builder/builder.go | WithRandomKeyPNM | func WithRandomKeyPNM(p uint8, n uint32, m uint64) *GCSBuilder {
key, err := RandomKey()
if err != nil {
b := GCSBuilder{err: err}
return &b
}
return WithKeyPNM(key, p, n, m)
} | go | func WithRandomKeyPNM(p uint8, n uint32, m uint64) *GCSBuilder {
key, err := RandomKey()
if err != nil {
b := GCSBuilder{err: err}
return &b
}
return WithKeyPNM(key, p, n, m)
} | [
"func",
"WithRandomKeyPNM",
"(",
"p",
"uint8",
",",
"n",
"uint32",
",",
"m",
"uint64",
")",
"*",
"GCSBuilder",
"{",
"key",
",",
"err",
":=",
"RandomKey",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"b",
":=",
"GCSBuilder",
"{",
"err",
":",
"err"... | // WithRandomKeyPNM creates a GCSBuilder with a cryptographically random key and
// the passed probability and estimated filter size. | [
"WithRandomKeyPNM",
"creates",
"a",
"GCSBuilder",
"with",
"a",
"cryptographically",
"random",
"key",
"and",
"the",
"passed",
"probability",
"and",
"estimated",
"filter",
"size",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L272-L279 | train |
btcsuite/btcutil | gcs/builder/builder.go | BuildBasicFilter | func BuildBasicFilter(block *wire.MsgBlock, prevOutScripts [][]byte) (*gcs.Filter, error) {
blockHash := block.BlockHash()
b := WithKeyHash(&blockHash)
// If the filter had an issue with the specified key, then we force it
// to bubble up here by calling the Key() function.
_, err := b.Key()
if err != nil {
return nil, err
}
// In order to build a basic filter, we'll range over the entire block,
// adding each whole script itself.
for _, tx := range block.Transactions {
// For each output in a transaction, we'll add each of the
// individual data pushes within the script.
for _, txOut := range tx.TxOut {
if len(txOut.PkScript) == 0 {
continue
}
// In order to allow the filters to later be committed
// to within an OP_RETURN output, we ignore all
// OP_RETURNs to avoid a circular dependency.
if txOut.PkScript[0] == txscript.OP_RETURN {
continue
}
b.AddEntry(txOut.PkScript)
}
}
// In the second pass, we'll also add all the prevOutScripts
// individually as elements.
for _, prevScript := range prevOutScripts {
if len(prevScript) == 0 {
continue
}
b.AddEntry(prevScript)
}
return b.Build()
} | go | func BuildBasicFilter(block *wire.MsgBlock, prevOutScripts [][]byte) (*gcs.Filter, error) {
blockHash := block.BlockHash()
b := WithKeyHash(&blockHash)
// If the filter had an issue with the specified key, then we force it
// to bubble up here by calling the Key() function.
_, err := b.Key()
if err != nil {
return nil, err
}
// In order to build a basic filter, we'll range over the entire block,
// adding each whole script itself.
for _, tx := range block.Transactions {
// For each output in a transaction, we'll add each of the
// individual data pushes within the script.
for _, txOut := range tx.TxOut {
if len(txOut.PkScript) == 0 {
continue
}
// In order to allow the filters to later be committed
// to within an OP_RETURN output, we ignore all
// OP_RETURNs to avoid a circular dependency.
if txOut.PkScript[0] == txscript.OP_RETURN {
continue
}
b.AddEntry(txOut.PkScript)
}
}
// In the second pass, we'll also add all the prevOutScripts
// individually as elements.
for _, prevScript := range prevOutScripts {
if len(prevScript) == 0 {
continue
}
b.AddEntry(prevScript)
}
return b.Build()
} | [
"func",
"BuildBasicFilter",
"(",
"block",
"*",
"wire",
".",
"MsgBlock",
",",
"prevOutScripts",
"[",
"]",
"[",
"]",
"byte",
")",
"(",
"*",
"gcs",
".",
"Filter",
",",
"error",
")",
"{",
"blockHash",
":=",
"block",
".",
"BlockHash",
"(",
")",
"\n",
"b",... | // BuildBasicFilter builds a basic GCS filter from a block. A basic GCS filter
// will contain all the previous output scripts spent by inputs within a block,
// as well as the data pushes within all the outputs created within a block. | [
"BuildBasicFilter",
"builds",
"a",
"basic",
"GCS",
"filter",
"from",
"a",
"block",
".",
"A",
"basic",
"GCS",
"filter",
"will",
"contain",
"all",
"the",
"previous",
"output",
"scripts",
"spent",
"by",
"inputs",
"within",
"a",
"block",
"as",
"well",
"as",
"t... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L299-L342 | train |
btcsuite/btcutil | gcs/builder/builder.go | GetFilterHash | func GetFilterHash(filter *gcs.Filter) (chainhash.Hash, error) {
filterData, err := filter.NBytes()
if err != nil {
return chainhash.Hash{}, err
}
return chainhash.DoubleHashH(filterData), nil
} | go | func GetFilterHash(filter *gcs.Filter) (chainhash.Hash, error) {
filterData, err := filter.NBytes()
if err != nil {
return chainhash.Hash{}, err
}
return chainhash.DoubleHashH(filterData), nil
} | [
"func",
"GetFilterHash",
"(",
"filter",
"*",
"gcs",
".",
"Filter",
")",
"(",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"filterData",
",",
"err",
":=",
"filter",
".",
"NBytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"chainhas... | // GetFilterHash returns the double-SHA256 of the filter. | [
"GetFilterHash",
"returns",
"the",
"double",
"-",
"SHA256",
"of",
"the",
"filter",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L345-L352 | train |
btcsuite/btcutil | gcs/builder/builder.go | MakeHeaderForFilter | func MakeHeaderForFilter(filter *gcs.Filter, prevHeader chainhash.Hash) (chainhash.Hash, error) {
filterTip := make([]byte, 2*chainhash.HashSize)
filterHash, err := GetFilterHash(filter)
if err != nil {
return chainhash.Hash{}, err
}
// In the buffer we created above we'll compute hash || prevHash as an
// intermediate value.
copy(filterTip, filterHash[:])
copy(filterTip[chainhash.HashSize:], prevHeader[:])
// The final filter hash is the double-sha256 of the hash computed
// above.
return chainhash.DoubleHashH(filterTip), nil
} | go | func MakeHeaderForFilter(filter *gcs.Filter, prevHeader chainhash.Hash) (chainhash.Hash, error) {
filterTip := make([]byte, 2*chainhash.HashSize)
filterHash, err := GetFilterHash(filter)
if err != nil {
return chainhash.Hash{}, err
}
// In the buffer we created above we'll compute hash || prevHash as an
// intermediate value.
copy(filterTip, filterHash[:])
copy(filterTip[chainhash.HashSize:], prevHeader[:])
// The final filter hash is the double-sha256 of the hash computed
// above.
return chainhash.DoubleHashH(filterTip), nil
} | [
"func",
"MakeHeaderForFilter",
"(",
"filter",
"*",
"gcs",
".",
"Filter",
",",
"prevHeader",
"chainhash",
".",
"Hash",
")",
"(",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"filterTip",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
"*",
"chainhas... | // MakeHeaderForFilter makes a filter chain header for a filter, given the
// filter and the previous filter chain header. | [
"MakeHeaderForFilter",
"makes",
"a",
"filter",
"chain",
"header",
"for",
"a",
"filter",
"given",
"the",
"filter",
"and",
"the",
"previous",
"filter",
"chain",
"header",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/gcs/builder/builder.go#L356-L371 | train |
btcsuite/btcutil | block.go | Bytes | func (b *Block) Bytes() ([]byte, error) {
// Return the cached serialized bytes if it has already been generated.
if len(b.serializedBlock) != 0 {
return b.serializedBlock, nil
}
// Serialize the MsgBlock.
w := bytes.NewBuffer(make([]byte, 0, b.msgBlock.SerializeSize()))
err := b.msgBlock.Serialize(w)
if err != nil {
return nil, err
}
serializedBlock := w.Bytes()
// Cache the serialized bytes and return them.
b.serializedBlock = serializedBlock
return serializedBlock, nil
} | go | func (b *Block) Bytes() ([]byte, error) {
// Return the cached serialized bytes if it has already been generated.
if len(b.serializedBlock) != 0 {
return b.serializedBlock, nil
}
// Serialize the MsgBlock.
w := bytes.NewBuffer(make([]byte, 0, b.msgBlock.SerializeSize()))
err := b.msgBlock.Serialize(w)
if err != nil {
return nil, err
}
serializedBlock := w.Bytes()
// Cache the serialized bytes and return them.
b.serializedBlock = serializedBlock
return serializedBlock, nil
} | [
"func",
"(",
"b",
"*",
"Block",
")",
"Bytes",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Return the cached serialized bytes if it has already been generated.",
"if",
"len",
"(",
"b",
".",
"serializedBlock",
")",
"!=",
"0",
"{",
"return",
"b... | // Bytes returns the serialized bytes for the Block. This is equivalent to
// calling Serialize on the underlying wire.MsgBlock, however it caches the
// result so subsequent calls are more efficient. | [
"Bytes",
"returns",
"the",
"serialized",
"bytes",
"for",
"the",
"Block",
".",
"This",
"is",
"equivalent",
"to",
"calling",
"Serialize",
"on",
"the",
"underlying",
"wire",
".",
"MsgBlock",
"however",
"it",
"caches",
"the",
"result",
"so",
"subsequent",
"calls",... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L53-L70 | train |
btcsuite/btcutil | block.go | BytesNoWitness | func (b *Block) BytesNoWitness() ([]byte, error) {
// Return the cached serialized bytes if it has already been generated.
if len(b.serializedBlockNoWitness) != 0 {
return b.serializedBlockNoWitness, nil
}
// Serialize the MsgBlock.
var w bytes.Buffer
err := b.msgBlock.SerializeNoWitness(&w)
if err != nil {
return nil, err
}
serializedBlock := w.Bytes()
// Cache the serialized bytes and return them.
b.serializedBlockNoWitness = serializedBlock
return serializedBlock, nil
} | go | func (b *Block) BytesNoWitness() ([]byte, error) {
// Return the cached serialized bytes if it has already been generated.
if len(b.serializedBlockNoWitness) != 0 {
return b.serializedBlockNoWitness, nil
}
// Serialize the MsgBlock.
var w bytes.Buffer
err := b.msgBlock.SerializeNoWitness(&w)
if err != nil {
return nil, err
}
serializedBlock := w.Bytes()
// Cache the serialized bytes and return them.
b.serializedBlockNoWitness = serializedBlock
return serializedBlock, nil
} | [
"func",
"(",
"b",
"*",
"Block",
")",
"BytesNoWitness",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Return the cached serialized bytes if it has already been generated.",
"if",
"len",
"(",
"b",
".",
"serializedBlockNoWitness",
")",
"!=",
"0",
"{"... | // BytesNoWitness returns the serialized bytes for the block with transactions
// encoded without any witness data. | [
"BytesNoWitness",
"returns",
"the",
"serialized",
"bytes",
"for",
"the",
"block",
"with",
"transactions",
"encoded",
"without",
"any",
"witness",
"data",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L74-L91 | train |
btcsuite/btcutil | block.go | Hash | func (b *Block) Hash() *chainhash.Hash {
// Return the cached block hash if it has already been generated.
if b.blockHash != nil {
return b.blockHash
}
// Cache the block hash and return it.
hash := b.msgBlock.BlockHash()
b.blockHash = &hash
return &hash
} | go | func (b *Block) Hash() *chainhash.Hash {
// Return the cached block hash if it has already been generated.
if b.blockHash != nil {
return b.blockHash
}
// Cache the block hash and return it.
hash := b.msgBlock.BlockHash()
b.blockHash = &hash
return &hash
} | [
"func",
"(",
"b",
"*",
"Block",
")",
"Hash",
"(",
")",
"*",
"chainhash",
".",
"Hash",
"{",
"// Return the cached block hash if it has already been generated.",
"if",
"b",
".",
"blockHash",
"!=",
"nil",
"{",
"return",
"b",
".",
"blockHash",
"\n",
"}",
"\n\n",
... | // Hash returns the block identifier hash for the Block. This is equivalent to
// calling BlockHash on the underlying wire.MsgBlock, however it caches the
// result so subsequent calls are more efficient. | [
"Hash",
"returns",
"the",
"block",
"identifier",
"hash",
"for",
"the",
"Block",
".",
"This",
"is",
"equivalent",
"to",
"calling",
"BlockHash",
"on",
"the",
"underlying",
"wire",
".",
"MsgBlock",
"however",
"it",
"caches",
"the",
"result",
"so",
"subsequent",
... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L96-L106 | train |
btcsuite/btcutil | block.go | TxHash | func (b *Block) TxHash(txNum int) (*chainhash.Hash, error) {
// Attempt to get a wrapped transaction for the specified index. It
// will be created lazily if needed or simply return the cached version
// if it has already been generated.
tx, err := b.Tx(txNum)
if err != nil {
return nil, err
}
// Defer to the wrapped transaction which will return the cached hash if
// it has already been generated.
return tx.Hash(), nil
} | go | func (b *Block) TxHash(txNum int) (*chainhash.Hash, error) {
// Attempt to get a wrapped transaction for the specified index. It
// will be created lazily if needed or simply return the cached version
// if it has already been generated.
tx, err := b.Tx(txNum)
if err != nil {
return nil, err
}
// Defer to the wrapped transaction which will return the cached hash if
// it has already been generated.
return tx.Hash(), nil
} | [
"func",
"(",
"b",
"*",
"Block",
")",
"TxHash",
"(",
"txNum",
"int",
")",
"(",
"*",
"chainhash",
".",
"Hash",
",",
"error",
")",
"{",
"// Attempt to get a wrapped transaction for the specified index. It",
"// will be created lazily if needed or simply return the cached vers... | // TxHash returns the hash for the requested transaction number in the Block.
// The supplied index is 0 based. That is to say, the first transaction in the
// block is txNum 0. This is equivalent to calling TxHash on the underlying
// wire.MsgTx, however it caches the result so subsequent calls are more
// efficient. | [
"TxHash",
"returns",
"the",
"hash",
"for",
"the",
"requested",
"transaction",
"number",
"in",
"the",
"Block",
".",
"The",
"supplied",
"index",
"is",
"0",
"based",
".",
"That",
"is",
"to",
"say",
"the",
"first",
"transaction",
"in",
"the",
"block",
"is",
... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L176-L188 | train |
btcsuite/btcutil | block.go | TxLoc | func (b *Block) TxLoc() ([]wire.TxLoc, error) {
rawMsg, err := b.Bytes()
if err != nil {
return nil, err
}
rbuf := bytes.NewBuffer(rawMsg)
var mblock wire.MsgBlock
txLocs, err := mblock.DeserializeTxLoc(rbuf)
if err != nil {
return nil, err
}
return txLocs, err
} | go | func (b *Block) TxLoc() ([]wire.TxLoc, error) {
rawMsg, err := b.Bytes()
if err != nil {
return nil, err
}
rbuf := bytes.NewBuffer(rawMsg)
var mblock wire.MsgBlock
txLocs, err := mblock.DeserializeTxLoc(rbuf)
if err != nil {
return nil, err
}
return txLocs, err
} | [
"func",
"(",
"b",
"*",
"Block",
")",
"TxLoc",
"(",
")",
"(",
"[",
"]",
"wire",
".",
"TxLoc",
",",
"error",
")",
"{",
"rawMsg",
",",
"err",
":=",
"b",
".",
"Bytes",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
... | // TxLoc returns the offsets and lengths of each transaction in a raw block.
// It is used to allow fast indexing into transactions within the raw byte
// stream. | [
"TxLoc",
"returns",
"the",
"offsets",
"and",
"lengths",
"of",
"each",
"transaction",
"in",
"a",
"raw",
"block",
".",
"It",
"is",
"used",
"to",
"allow",
"fast",
"indexing",
"into",
"transactions",
"within",
"the",
"raw",
"byte",
"stream",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L193-L206 | train |
btcsuite/btcutil | block.go | NewBlock | func NewBlock(msgBlock *wire.MsgBlock) *Block {
return &Block{
msgBlock: msgBlock,
blockHeight: BlockHeightUnknown,
}
} | go | func NewBlock(msgBlock *wire.MsgBlock) *Block {
return &Block{
msgBlock: msgBlock,
blockHeight: BlockHeightUnknown,
}
} | [
"func",
"NewBlock",
"(",
"msgBlock",
"*",
"wire",
".",
"MsgBlock",
")",
"*",
"Block",
"{",
"return",
"&",
"Block",
"{",
"msgBlock",
":",
"msgBlock",
",",
"blockHeight",
":",
"BlockHeightUnknown",
",",
"}",
"\n",
"}"
] | // NewBlock returns a new instance of a bitcoin block given an underlying
// wire.MsgBlock. See Block. | [
"NewBlock",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"an",
"underlying",
"wire",
".",
"MsgBlock",
".",
"See",
"Block",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L221-L226 | train |
btcsuite/btcutil | block.go | NewBlockFromBytes | func NewBlockFromBytes(serializedBlock []byte) (*Block, error) {
br := bytes.NewReader(serializedBlock)
b, err := NewBlockFromReader(br)
if err != nil {
return nil, err
}
b.serializedBlock = serializedBlock
return b, nil
} | go | func NewBlockFromBytes(serializedBlock []byte) (*Block, error) {
br := bytes.NewReader(serializedBlock)
b, err := NewBlockFromReader(br)
if err != nil {
return nil, err
}
b.serializedBlock = serializedBlock
return b, nil
} | [
"func",
"NewBlockFromBytes",
"(",
"serializedBlock",
"[",
"]",
"byte",
")",
"(",
"*",
"Block",
",",
"error",
")",
"{",
"br",
":=",
"bytes",
".",
"NewReader",
"(",
"serializedBlock",
")",
"\n",
"b",
",",
"err",
":=",
"NewBlockFromReader",
"(",
"br",
")",
... | // NewBlockFromBytes returns a new instance of a bitcoin block given the
// serialized bytes. See Block. | [
"NewBlockFromBytes",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"the",
"serialized",
"bytes",
".",
"See",
"Block",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L230-L238 | train |
btcsuite/btcutil | block.go | NewBlockFromReader | func NewBlockFromReader(r io.Reader) (*Block, error) {
// Deserialize the bytes into a MsgBlock.
var msgBlock wire.MsgBlock
err := msgBlock.Deserialize(r)
if err != nil {
return nil, err
}
b := Block{
msgBlock: &msgBlock,
blockHeight: BlockHeightUnknown,
}
return &b, nil
} | go | func NewBlockFromReader(r io.Reader) (*Block, error) {
// Deserialize the bytes into a MsgBlock.
var msgBlock wire.MsgBlock
err := msgBlock.Deserialize(r)
if err != nil {
return nil, err
}
b := Block{
msgBlock: &msgBlock,
blockHeight: BlockHeightUnknown,
}
return &b, nil
} | [
"func",
"NewBlockFromReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Block",
",",
"error",
")",
"{",
"// Deserialize the bytes into a MsgBlock.",
"var",
"msgBlock",
"wire",
".",
"MsgBlock",
"\n",
"err",
":=",
"msgBlock",
".",
"Deserialize",
"(",
"r",
... | // NewBlockFromReader returns a new instance of a bitcoin block given a
// Reader to deserialize the block. See Block. | [
"NewBlockFromReader",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"a",
"Reader",
"to",
"deserialize",
"the",
"block",
".",
"See",
"Block",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L242-L255 | train |
btcsuite/btcutil | block.go | NewBlockFromBlockAndBytes | func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block {
return &Block{
msgBlock: msgBlock,
serializedBlock: serializedBlock,
blockHeight: BlockHeightUnknown,
}
} | go | func NewBlockFromBlockAndBytes(msgBlock *wire.MsgBlock, serializedBlock []byte) *Block {
return &Block{
msgBlock: msgBlock,
serializedBlock: serializedBlock,
blockHeight: BlockHeightUnknown,
}
} | [
"func",
"NewBlockFromBlockAndBytes",
"(",
"msgBlock",
"*",
"wire",
".",
"MsgBlock",
",",
"serializedBlock",
"[",
"]",
"byte",
")",
"*",
"Block",
"{",
"return",
"&",
"Block",
"{",
"msgBlock",
":",
"msgBlock",
",",
"serializedBlock",
":",
"serializedBlock",
",",... | // NewBlockFromBlockAndBytes returns a new instance of a bitcoin block given
// an underlying wire.MsgBlock and the serialized bytes for it. See Block. | [
"NewBlockFromBlockAndBytes",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"block",
"given",
"an",
"underlying",
"wire",
".",
"MsgBlock",
"and",
"the",
"serialized",
"bytes",
"for",
"it",
".",
"See",
"Block",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/block.go#L259-L265 | train |
btcsuite/btcutil | base58/base58.go | Decode | func Decode(b string) []byte {
answer := big.NewInt(0)
j := big.NewInt(1)
scratch := new(big.Int)
for i := len(b) - 1; i >= 0; i-- {
tmp := b58[b[i]]
if tmp == 255 {
return []byte("")
}
scratch.SetInt64(int64(tmp))
scratch.Mul(j, scratch)
answer.Add(answer, scratch)
j.Mul(j, bigRadix)
}
tmpval := answer.Bytes()
var numZeros int
for numZeros = 0; numZeros < len(b); numZeros++ {
if b[numZeros] != alphabetIdx0 {
break
}
}
flen := numZeros + len(tmpval)
val := make([]byte, flen)
copy(val[numZeros:], tmpval)
return val
} | go | func Decode(b string) []byte {
answer := big.NewInt(0)
j := big.NewInt(1)
scratch := new(big.Int)
for i := len(b) - 1; i >= 0; i-- {
tmp := b58[b[i]]
if tmp == 255 {
return []byte("")
}
scratch.SetInt64(int64(tmp))
scratch.Mul(j, scratch)
answer.Add(answer, scratch)
j.Mul(j, bigRadix)
}
tmpval := answer.Bytes()
var numZeros int
for numZeros = 0; numZeros < len(b); numZeros++ {
if b[numZeros] != alphabetIdx0 {
break
}
}
flen := numZeros + len(tmpval)
val := make([]byte, flen)
copy(val[numZeros:], tmpval)
return val
} | [
"func",
"Decode",
"(",
"b",
"string",
")",
"[",
"]",
"byte",
"{",
"answer",
":=",
"big",
".",
"NewInt",
"(",
"0",
")",
"\n",
"j",
":=",
"big",
".",
"NewInt",
"(",
"1",
")",
"\n\n",
"scratch",
":=",
"new",
"(",
"big",
".",
"Int",
")",
"\n",
"f... | // Decode decodes a modified base58 string to a byte slice. | [
"Decode",
"decodes",
"a",
"modified",
"base58",
"string",
"to",
"a",
"byte",
"slice",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/base58/base58.go#L17-L46 | train |
btcsuite/btcutil | wif.go | NewWIF | func NewWIF(privKey *btcec.PrivateKey, net *chaincfg.Params, compress bool) (*WIF, error) {
if net == nil {
return nil, errors.New("no network")
}
return &WIF{privKey, compress, net.PrivateKeyID}, nil
} | go | func NewWIF(privKey *btcec.PrivateKey, net *chaincfg.Params, compress bool) (*WIF, error) {
if net == nil {
return nil, errors.New("no network")
}
return &WIF{privKey, compress, net.PrivateKeyID}, nil
} | [
"func",
"NewWIF",
"(",
"privKey",
"*",
"btcec",
".",
"PrivateKey",
",",
"net",
"*",
"chaincfg",
".",
"Params",
",",
"compress",
"bool",
")",
"(",
"*",
"WIF",
",",
"error",
")",
"{",
"if",
"net",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
"."... | // NewWIF creates a new WIF structure to export an address and its private key
// as a string encoded in the Wallet Import Format. The compress argument
// specifies whether the address intended to be imported or exported was created
// by serializing the public key compressed rather than uncompressed. | [
"NewWIF",
"creates",
"a",
"new",
"WIF",
"structure",
"to",
"export",
"an",
"address",
"and",
"its",
"private",
"key",
"as",
"a",
"string",
"encoded",
"in",
"the",
"Wallet",
"Import",
"Format",
".",
"The",
"compress",
"argument",
"specifies",
"whether",
"the"... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/wif.go#L52-L57 | train |
btcsuite/btcutil | wif.go | IsForNet | func (w *WIF) IsForNet(net *chaincfg.Params) bool {
return w.netID == net.PrivateKeyID
} | go | func (w *WIF) IsForNet(net *chaincfg.Params) bool {
return w.netID == net.PrivateKeyID
} | [
"func",
"(",
"w",
"*",
"WIF",
")",
"IsForNet",
"(",
"net",
"*",
"chaincfg",
".",
"Params",
")",
"bool",
"{",
"return",
"w",
".",
"netID",
"==",
"net",
".",
"PrivateKeyID",
"\n",
"}"
] | // IsForNet returns whether or not the decoded WIF structure is associated
// with the passed bitcoin network. | [
"IsForNet",
"returns",
"whether",
"or",
"not",
"the",
"decoded",
"WIF",
"structure",
"is",
"associated",
"with",
"the",
"passed",
"bitcoin",
"network",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/wif.go#L61-L63 | train |
btcsuite/btcutil | wif.go | SerializePubKey | func (w *WIF) SerializePubKey() []byte {
pk := (*btcec.PublicKey)(&w.PrivKey.PublicKey)
if w.CompressPubKey {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
} | go | func (w *WIF) SerializePubKey() []byte {
pk := (*btcec.PublicKey)(&w.PrivKey.PublicKey)
if w.CompressPubKey {
return pk.SerializeCompressed()
}
return pk.SerializeUncompressed()
} | [
"func",
"(",
"w",
"*",
"WIF",
")",
"SerializePubKey",
"(",
")",
"[",
"]",
"byte",
"{",
"pk",
":=",
"(",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"&",
"w",
".",
"PrivKey",
".",
"PublicKey",
")",
"\n",
"if",
"w",
".",
"CompressPubKey",
"{",
"retur... | // SerializePubKey serializes the associated public key of the imported or
// exported private key in either a compressed or uncompressed format. The
// serialization format chosen depends on the value of w.CompressPubKey. | [
"SerializePubKey",
"serializes",
"the",
"associated",
"public",
"key",
"of",
"the",
"imported",
"or",
"exported",
"private",
"key",
"in",
"either",
"a",
"compressed",
"or",
"uncompressed",
"format",
".",
"The",
"serialization",
"format",
"chosen",
"depends",
"on",... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/wif.go#L153-L159 | train |
btcsuite/btcutil | bech32/bech32.go | Decode | func Decode(bech string) (string, []byte, error) {
// The maximum allowed length for a bech32 string is 90. It must also
// be at least 8 characters, since it needs a non-empty HRP, a
// separator, and a 6 character checksum.
if len(bech) < 8 || len(bech) > 90 {
return "", nil, fmt.Errorf("invalid bech32 string length %d",
len(bech))
}
// Only ASCII characters between 33 and 126 are allowed.
for i := 0; i < len(bech); i++ {
if bech[i] < 33 || bech[i] > 126 {
return "", nil, fmt.Errorf("invalid character in "+
"string: '%c'", bech[i])
}
}
// The characters must be either all lowercase or all uppercase.
lower := strings.ToLower(bech)
upper := strings.ToUpper(bech)
if bech != lower && bech != upper {
return "", nil, fmt.Errorf("string not all lowercase or all " +
"uppercase")
}
// We'll work with the lowercase string from now on.
bech = lower
// The string is invalid if the last '1' is non-existent, it is the
// first character of the string (no human-readable part) or one of the
// last 6 characters of the string (since checksum cannot contain '1'),
// or if the string is more than 90 characters in total.
one := strings.LastIndexByte(bech, '1')
if one < 1 || one+7 > len(bech) {
return "", nil, fmt.Errorf("invalid index of 1")
}
// The human-readable part is everything before the last '1'.
hrp := bech[:one]
data := bech[one+1:]
// Each character corresponds to the byte with value of the index in
// 'charset'.
decoded, err := toBytes(data)
if err != nil {
return "", nil, fmt.Errorf("failed converting data to bytes: "+
"%v", err)
}
if !bech32VerifyChecksum(hrp, decoded) {
moreInfo := ""
checksum := bech[len(bech)-6:]
expected, err := toChars(bech32Checksum(hrp,
decoded[:len(decoded)-6]))
if err == nil {
moreInfo = fmt.Sprintf("Expected %v, got %v.",
expected, checksum)
}
return "", nil, fmt.Errorf("checksum failed. " + moreInfo)
}
// We exclude the last 6 bytes, which is the checksum.
return hrp, decoded[:len(decoded)-6], nil
} | go | func Decode(bech string) (string, []byte, error) {
// The maximum allowed length for a bech32 string is 90. It must also
// be at least 8 characters, since it needs a non-empty HRP, a
// separator, and a 6 character checksum.
if len(bech) < 8 || len(bech) > 90 {
return "", nil, fmt.Errorf("invalid bech32 string length %d",
len(bech))
}
// Only ASCII characters between 33 and 126 are allowed.
for i := 0; i < len(bech); i++ {
if bech[i] < 33 || bech[i] > 126 {
return "", nil, fmt.Errorf("invalid character in "+
"string: '%c'", bech[i])
}
}
// The characters must be either all lowercase or all uppercase.
lower := strings.ToLower(bech)
upper := strings.ToUpper(bech)
if bech != lower && bech != upper {
return "", nil, fmt.Errorf("string not all lowercase or all " +
"uppercase")
}
// We'll work with the lowercase string from now on.
bech = lower
// The string is invalid if the last '1' is non-existent, it is the
// first character of the string (no human-readable part) or one of the
// last 6 characters of the string (since checksum cannot contain '1'),
// or if the string is more than 90 characters in total.
one := strings.LastIndexByte(bech, '1')
if one < 1 || one+7 > len(bech) {
return "", nil, fmt.Errorf("invalid index of 1")
}
// The human-readable part is everything before the last '1'.
hrp := bech[:one]
data := bech[one+1:]
// Each character corresponds to the byte with value of the index in
// 'charset'.
decoded, err := toBytes(data)
if err != nil {
return "", nil, fmt.Errorf("failed converting data to bytes: "+
"%v", err)
}
if !bech32VerifyChecksum(hrp, decoded) {
moreInfo := ""
checksum := bech[len(bech)-6:]
expected, err := toChars(bech32Checksum(hrp,
decoded[:len(decoded)-6]))
if err == nil {
moreInfo = fmt.Sprintf("Expected %v, got %v.",
expected, checksum)
}
return "", nil, fmt.Errorf("checksum failed. " + moreInfo)
}
// We exclude the last 6 bytes, which is the checksum.
return hrp, decoded[:len(decoded)-6], nil
} | [
"func",
"Decode",
"(",
"bech",
"string",
")",
"(",
"string",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// The maximum allowed length for a bech32 string is 90. It must also",
"// be at least 8 characters, since it needs a non-empty HRP, a",
"// separator, and a 6 character ... | // Decode decodes a bech32 encoded string, returning the human-readable
// part and the data part excluding the checksum. | [
"Decode",
"decodes",
"a",
"bech32",
"encoded",
"string",
"returning",
"the",
"human",
"-",
"readable",
"part",
"and",
"the",
"data",
"part",
"excluding",
"the",
"checksum",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bech32/bech32.go#L18-L80 | train |
btcsuite/btcutil | bech32/bech32.go | ConvertBits | func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {
if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 {
return nil, fmt.Errorf("only bit groups between 1 and 8 allowed")
}
// The final bytes, each byte encoding toBits bits.
var regrouped []byte
// Keep track of the next byte we create and how many bits we have
// added to it out of the toBits goal.
nextByte := byte(0)
filledBits := uint8(0)
for _, b := range data {
// Discard unused bits.
b = b << (8 - fromBits)
// How many bits remaining to extract from the input data.
remFromBits := fromBits
for remFromBits > 0 {
// How many bits remaining to be added to the next byte.
remToBits := toBits - filledBits
// The number of bytes to next extract is the minimum of
// remFromBits and remToBits.
toExtract := remFromBits
if remToBits < toExtract {
toExtract = remToBits
}
// Add the next bits to nextByte, shifting the already
// added bits to the left.
nextByte = (nextByte << toExtract) | (b >> (8 - toExtract))
// Discard the bits we just extracted and get ready for
// next iteration.
b = b << toExtract
remFromBits -= toExtract
filledBits += toExtract
// If the nextByte is completely filled, we add it to
// our regrouped bytes and start on the next byte.
if filledBits == toBits {
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
}
}
// We pad any unfinished group if specified.
if pad && filledBits > 0 {
nextByte = nextByte << (toBits - filledBits)
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
// Any incomplete group must be <= 4 bits, and all zeroes.
if filledBits > 0 && (filledBits > 4 || nextByte != 0) {
return nil, fmt.Errorf("invalid incomplete group")
}
return regrouped, nil
} | go | func ConvertBits(data []byte, fromBits, toBits uint8, pad bool) ([]byte, error) {
if fromBits < 1 || fromBits > 8 || toBits < 1 || toBits > 8 {
return nil, fmt.Errorf("only bit groups between 1 and 8 allowed")
}
// The final bytes, each byte encoding toBits bits.
var regrouped []byte
// Keep track of the next byte we create and how many bits we have
// added to it out of the toBits goal.
nextByte := byte(0)
filledBits := uint8(0)
for _, b := range data {
// Discard unused bits.
b = b << (8 - fromBits)
// How many bits remaining to extract from the input data.
remFromBits := fromBits
for remFromBits > 0 {
// How many bits remaining to be added to the next byte.
remToBits := toBits - filledBits
// The number of bytes to next extract is the minimum of
// remFromBits and remToBits.
toExtract := remFromBits
if remToBits < toExtract {
toExtract = remToBits
}
// Add the next bits to nextByte, shifting the already
// added bits to the left.
nextByte = (nextByte << toExtract) | (b >> (8 - toExtract))
// Discard the bits we just extracted and get ready for
// next iteration.
b = b << toExtract
remFromBits -= toExtract
filledBits += toExtract
// If the nextByte is completely filled, we add it to
// our regrouped bytes and start on the next byte.
if filledBits == toBits {
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
}
}
// We pad any unfinished group if specified.
if pad && filledBits > 0 {
nextByte = nextByte << (toBits - filledBits)
regrouped = append(regrouped, nextByte)
filledBits = 0
nextByte = 0
}
// Any incomplete group must be <= 4 bits, and all zeroes.
if filledBits > 0 && (filledBits > 4 || nextByte != 0) {
return nil, fmt.Errorf("invalid incomplete group")
}
return regrouped, nil
} | [
"func",
"ConvertBits",
"(",
"data",
"[",
"]",
"byte",
",",
"fromBits",
",",
"toBits",
"uint8",
",",
"pad",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"fromBits",
"<",
"1",
"||",
"fromBits",
">",
"8",
"||",
"toBits",
"<",
"1... | // ConvertBits converts a byte slice where each byte is encoding fromBits bits,
// to a byte slice where each byte is encoding toBits bits. | [
"ConvertBits",
"converts",
"a",
"byte",
"slice",
"where",
"each",
"byte",
"is",
"encoding",
"fromBits",
"bits",
"to",
"a",
"byte",
"slice",
"where",
"each",
"byte",
"is",
"encoding",
"toBits",
"bits",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/bech32/bech32.go#L131-L196 | train |
btcsuite/btcutil | tx.go | Hash | func (t *Tx) Hash() *chainhash.Hash {
// Return the cached hash if it has already been generated.
if t.txHash != nil {
return t.txHash
}
// Cache the hash and return it.
hash := t.msgTx.TxHash()
t.txHash = &hash
return &hash
} | go | func (t *Tx) Hash() *chainhash.Hash {
// Return the cached hash if it has already been generated.
if t.txHash != nil {
return t.txHash
}
// Cache the hash and return it.
hash := t.msgTx.TxHash()
t.txHash = &hash
return &hash
} | [
"func",
"(",
"t",
"*",
"Tx",
")",
"Hash",
"(",
")",
"*",
"chainhash",
".",
"Hash",
"{",
"// Return the cached hash if it has already been generated.",
"if",
"t",
".",
"txHash",
"!=",
"nil",
"{",
"return",
"t",
".",
"txHash",
"\n",
"}",
"\n\n",
"// Cache the ... | // Hash returns the hash of the transaction. This is equivalent to
// calling TxHash on the underlying wire.MsgTx, however it caches the
// result so subsequent calls are more efficient. | [
"Hash",
"returns",
"the",
"hash",
"of",
"the",
"transaction",
".",
"This",
"is",
"equivalent",
"to",
"calling",
"TxHash",
"on",
"the",
"underlying",
"wire",
".",
"MsgTx",
"however",
"it",
"caches",
"the",
"result",
"so",
"subsequent",
"calls",
"are",
"more",... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L41-L51 | train |
btcsuite/btcutil | tx.go | HasWitness | func (t *Tx) HasWitness() bool {
if t.txHashWitness != nil {
return *t.txHasWitness
}
hasWitness := t.msgTx.HasWitness()
t.txHasWitness = &hasWitness
return hasWitness
} | go | func (t *Tx) HasWitness() bool {
if t.txHashWitness != nil {
return *t.txHasWitness
}
hasWitness := t.msgTx.HasWitness()
t.txHasWitness = &hasWitness
return hasWitness
} | [
"func",
"(",
"t",
"*",
"Tx",
")",
"HasWitness",
"(",
")",
"bool",
"{",
"if",
"t",
".",
"txHashWitness",
"!=",
"nil",
"{",
"return",
"*",
"t",
".",
"txHasWitness",
"\n",
"}",
"\n\n",
"hasWitness",
":=",
"t",
".",
"msgTx",
".",
"HasWitness",
"(",
")"... | // HasWitness returns false if none of the inputs within the transaction
// contain witness data, true false otherwise. This equivalent to calling
// HasWitness on the underlying wire.MsgTx, however it caches the result so
// subsequent calls are more efficient. | [
"HasWitness",
"returns",
"false",
"if",
"none",
"of",
"the",
"inputs",
"within",
"the",
"transaction",
"contain",
"witness",
"data",
"true",
"false",
"otherwise",
".",
"This",
"equivalent",
"to",
"calling",
"HasWitness",
"on",
"the",
"underlying",
"wire",
".",
... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L72-L80 | train |
btcsuite/btcutil | tx.go | NewTx | func NewTx(msgTx *wire.MsgTx) *Tx {
return &Tx{
msgTx: msgTx,
txIndex: TxIndexUnknown,
}
} | go | func NewTx(msgTx *wire.MsgTx) *Tx {
return &Tx{
msgTx: msgTx,
txIndex: TxIndexUnknown,
}
} | [
"func",
"NewTx",
"(",
"msgTx",
"*",
"wire",
".",
"MsgTx",
")",
"*",
"Tx",
"{",
"return",
"&",
"Tx",
"{",
"msgTx",
":",
"msgTx",
",",
"txIndex",
":",
"TxIndexUnknown",
",",
"}",
"\n",
"}"
] | // NewTx returns a new instance of a bitcoin transaction given an underlying
// wire.MsgTx. See Tx. | [
"NewTx",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"transaction",
"given",
"an",
"underlying",
"wire",
".",
"MsgTx",
".",
"See",
"Tx",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L95-L100 | train |
btcsuite/btcutil | tx.go | NewTxFromBytes | func NewTxFromBytes(serializedTx []byte) (*Tx, error) {
br := bytes.NewReader(serializedTx)
return NewTxFromReader(br)
} | go | func NewTxFromBytes(serializedTx []byte) (*Tx, error) {
br := bytes.NewReader(serializedTx)
return NewTxFromReader(br)
} | [
"func",
"NewTxFromBytes",
"(",
"serializedTx",
"[",
"]",
"byte",
")",
"(",
"*",
"Tx",
",",
"error",
")",
"{",
"br",
":=",
"bytes",
".",
"NewReader",
"(",
"serializedTx",
")",
"\n",
"return",
"NewTxFromReader",
"(",
"br",
")",
"\n",
"}"
] | // NewTxFromBytes returns a new instance of a bitcoin transaction given the
// serialized bytes. See Tx. | [
"NewTxFromBytes",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"transaction",
"given",
"the",
"serialized",
"bytes",
".",
"See",
"Tx",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L104-L107 | train |
btcsuite/btcutil | tx.go | NewTxFromReader | func NewTxFromReader(r io.Reader) (*Tx, error) {
// Deserialize the bytes into a MsgTx.
var msgTx wire.MsgTx
err := msgTx.Deserialize(r)
if err != nil {
return nil, err
}
t := Tx{
msgTx: &msgTx,
txIndex: TxIndexUnknown,
}
return &t, nil
} | go | func NewTxFromReader(r io.Reader) (*Tx, error) {
// Deserialize the bytes into a MsgTx.
var msgTx wire.MsgTx
err := msgTx.Deserialize(r)
if err != nil {
return nil, err
}
t := Tx{
msgTx: &msgTx,
txIndex: TxIndexUnknown,
}
return &t, nil
} | [
"func",
"NewTxFromReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"Tx",
",",
"error",
")",
"{",
"// Deserialize the bytes into a MsgTx.",
"var",
"msgTx",
"wire",
".",
"MsgTx",
"\n",
"err",
":=",
"msgTx",
".",
"Deserialize",
"(",
"r",
")",
"\n",
"i... | // NewTxFromReader returns a new instance of a bitcoin transaction given a
// Reader to deserialize the transaction. See Tx. | [
"NewTxFromReader",
"returns",
"a",
"new",
"instance",
"of",
"a",
"bitcoin",
"transaction",
"given",
"a",
"Reader",
"to",
"deserialize",
"the",
"transaction",
".",
"See",
"Tx",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/tx.go#L111-L124 | train |
btcsuite/btcutil | txsort/txsort.go | Sort | func Sort(tx *wire.MsgTx) *wire.MsgTx {
txCopy := tx.Copy()
sort.Sort(sortableInputSlice(txCopy.TxIn))
sort.Sort(sortableOutputSlice(txCopy.TxOut))
return txCopy
} | go | func Sort(tx *wire.MsgTx) *wire.MsgTx {
txCopy := tx.Copy()
sort.Sort(sortableInputSlice(txCopy.TxIn))
sort.Sort(sortableOutputSlice(txCopy.TxOut))
return txCopy
} | [
"func",
"Sort",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"*",
"wire",
".",
"MsgTx",
"{",
"txCopy",
":=",
"tx",
".",
"Copy",
"(",
")",
"\n",
"sort",
".",
"Sort",
"(",
"sortableInputSlice",
"(",
"txCopy",
".",
"TxIn",
")",
")",
"\n",
"sort",
".",... | // Sort returns a new transaction with the inputs and outputs sorted based on
// BIP 69. The passed transaction is not modified and the new transaction
// might have a different hash if any sorting was done. | [
"Sort",
"returns",
"a",
"new",
"transaction",
"with",
"the",
"inputs",
"and",
"outputs",
"sorted",
"based",
"on",
"BIP",
"69",
".",
"The",
"passed",
"transaction",
"is",
"not",
"modified",
"and",
"the",
"new",
"transaction",
"might",
"have",
"a",
"different"... | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/txsort/txsort.go#L38-L43 | train |
btcsuite/btcutil | txsort/txsort.go | IsSorted | func IsSorted(tx *wire.MsgTx) bool {
if !sort.IsSorted(sortableInputSlice(tx.TxIn)) {
return false
}
if !sort.IsSorted(sortableOutputSlice(tx.TxOut)) {
return false
}
return true
} | go | func IsSorted(tx *wire.MsgTx) bool {
if !sort.IsSorted(sortableInputSlice(tx.TxIn)) {
return false
}
if !sort.IsSorted(sortableOutputSlice(tx.TxOut)) {
return false
}
return true
} | [
"func",
"IsSorted",
"(",
"tx",
"*",
"wire",
".",
"MsgTx",
")",
"bool",
"{",
"if",
"!",
"sort",
".",
"IsSorted",
"(",
"sortableInputSlice",
"(",
"tx",
".",
"TxIn",
")",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"!",
"sort",
".",
"IsSorted"... | // IsSorted checks whether tx has inputs and outputs sorted according to BIP
// 69. | [
"IsSorted",
"checks",
"whether",
"tx",
"has",
"inputs",
"and",
"outputs",
"sorted",
"according",
"to",
"BIP",
"69",
"."
] | 9e5f4b9a998d263e3ce9c56664a7816001ac8000 | https://github.com/btcsuite/btcutil/blob/9e5f4b9a998d263e3ce9c56664a7816001ac8000/txsort/txsort.go#L47-L55 | train |
logpacker/PayPal-Go-SDK | types.go | MarshalJSON | func (t JSONTime) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf(`"%s"`, time.Time(t).UTC().Format(time.RFC3339))
return []byte(stamp), nil
} | go | func (t JSONTime) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf(`"%s"`, time.Time(t).UTC().Format(time.RFC3339))
return []byte(stamp), nil
} | [
"func",
"(",
"t",
"JSONTime",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"stamp",
":=",
"fmt",
".",
"Sprintf",
"(",
"`\"%s\"`",
",",
"time",
".",
"Time",
"(",
"t",
")",
".",
"UTC",
"(",
")",
".",
"Format",
"(",... | // MarshalJSON for JSONTime | [
"MarshalJSON",
"for",
"JSONTime"
] | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/types.go#L607-L610 | train |
logpacker/PayPal-Go-SDK | client.go | NewClient | func NewClient(clientID string, secret string, APIBase string) (*Client, error) {
if clientID == "" || secret == "" || APIBase == "" {
return nil, errors.New("ClientID, Secret and APIBase are required to create a Client")
}
return &Client{
Client: &http.Client{},
ClientID: clientID,
Secret: secret,
APIBase: APIBase,
}, nil
} | go | func NewClient(clientID string, secret string, APIBase string) (*Client, error) {
if clientID == "" || secret == "" || APIBase == "" {
return nil, errors.New("ClientID, Secret and APIBase are required to create a Client")
}
return &Client{
Client: &http.Client{},
ClientID: clientID,
Secret: secret,
APIBase: APIBase,
}, nil
} | [
"func",
"NewClient",
"(",
"clientID",
"string",
",",
"secret",
"string",
",",
"APIBase",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"if",
"clientID",
"==",
"\"",
"\"",
"||",
"secret",
"==",
"\"",
"\"",
"||",
"APIBase",
"==",
"\"",
"\"... | // NewClient returns new Client struct
// APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox | [
"NewClient",
"returns",
"new",
"Client",
"struct",
"APIBase",
"is",
"a",
"base",
"API",
"URL",
"for",
"testing",
"you",
"can",
"use",
"paypalsdk",
".",
"APIBaseSandBox"
] | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L17-L28 | train |
logpacker/PayPal-Go-SDK | client.go | SetAccessToken | func (c *Client) SetAccessToken(token string) {
c.Token = &TokenResponse{
Token: token,
}
c.tokenExpiresAt = time.Time{}
} | go | func (c *Client) SetAccessToken(token string) {
c.Token = &TokenResponse{
Token: token,
}
c.tokenExpiresAt = time.Time{}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetAccessToken",
"(",
"token",
"string",
")",
"{",
"c",
".",
"Token",
"=",
"&",
"TokenResponse",
"{",
"Token",
":",
"token",
",",
"}",
"\n",
"c",
".",
"tokenExpiresAt",
"=",
"time",
".",
"Time",
"{",
"}",
"\n"... | // SetAccessToken sets saved token to current client | [
"SetAccessToken",
"sets",
"saved",
"token",
"to",
"current",
"client"
] | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L60-L65 | train |
logpacker/PayPal-Go-SDK | client.go | Send | func (c *Client) Send(req *http.Request, v interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
c.log(req, resp)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errResp := &ErrorResponse{Response: resp}
data, err = ioutil.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
json.Unmarshal(data, errResp)
}
return errResp
}
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
return nil
}
return json.NewDecoder(resp.Body).Decode(v)
} | go | func (c *Client) Send(req *http.Request, v interface{}) error {
var (
err error
resp *http.Response
data []byte
)
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
c.log(req, resp)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errResp := &ErrorResponse{Response: resp}
data, err = ioutil.ReadAll(resp.Body)
if err == nil && len(data) > 0 {
json.Unmarshal(data, errResp)
}
return errResp
}
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
return nil
}
return json.NewDecoder(resp.Body).Decode(v)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Send",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"(",
"err",
"error",
"\n",
"resp",
"*",
"http",
".",
"Response",
"\n",
"data",
"[",
"]",
"byte",
"... | // Send makes a request to the API, the response body will be
// unmarshaled into v, or if v is an io.Writer, the response will
// be written to it without decoding | [
"Send",
"makes",
"a",
"request",
"to",
"the",
"API",
"the",
"response",
"body",
"will",
"be",
"unmarshaled",
"into",
"v",
"or",
"if",
"v",
"is",
"an",
"io",
".",
"Writer",
"the",
"response",
"will",
"be",
"written",
"to",
"it",
"without",
"decoding"
] | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L76-L121 | train |
logpacker/PayPal-Go-SDK | client.go | SendWithAuth | func (c *Client) SendWithAuth(req *http.Request, v interface{}) error {
c.Lock()
// Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)`
// to happen outside of the locked section.
if c.Token != nil {
if !c.tokenExpiresAt.IsZero() && c.tokenExpiresAt.Sub(time.Now()) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(); err != nil {
c.Unlock()
return err
}
}
req.Header.Set("Authorization", "Bearer "+c.Token.Token)
}
// Unlock the client mutex before sending the request, this allows multiple requests
// to be in progress at the same time.
c.Unlock()
return c.Send(req, v)
} | go | func (c *Client) SendWithAuth(req *http.Request, v interface{}) error {
c.Lock()
// Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)`
// to happen outside of the locked section.
if c.Token != nil {
if !c.tokenExpiresAt.IsZero() && c.tokenExpiresAt.Sub(time.Now()) < RequestNewTokenBeforeExpiresIn {
// c.Token will be updated in GetAccessToken call
if _, err := c.GetAccessToken(); err != nil {
c.Unlock()
return err
}
}
req.Header.Set("Authorization", "Bearer "+c.Token.Token)
}
// Unlock the client mutex before sending the request, this allows multiple requests
// to be in progress at the same time.
c.Unlock()
return c.Send(req, v)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SendWithAuth",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"// Note: Here we do not want to `defer c.Unlock()` because we need `c.Send(...)`... | // SendWithAuth makes a request to the API and apply OAuth2 header automatically.
// If the access token soon to be expired or already expired, it will try to get a new one before
// making the main request
// client.Token will be updated when changed | [
"SendWithAuth",
"makes",
"a",
"request",
"to",
"the",
"API",
"and",
"apply",
"OAuth2",
"header",
"automatically",
".",
"If",
"the",
"access",
"token",
"soon",
"to",
"be",
"expired",
"or",
"already",
"expired",
"it",
"will",
"try",
"to",
"get",
"a",
"new",
... | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L127-L148 | train |
logpacker/PayPal-Go-SDK | client.go | NewRequest | func (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error) {
var buf io.Reader
if payload != nil {
var b []byte
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequest(method, url, buf)
} | go | func (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error) {
var buf io.Reader
if payload != nil {
var b []byte
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequest(method, url, buf)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"NewRequest",
"(",
"method",
",",
"url",
"string",
",",
"payload",
"interface",
"{",
"}",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"var",
"buf",
"io",
".",
"Reader",
"\n",
"if",
"payload",... | // NewRequest constructs a request
// Convert payload to a JSON | [
"NewRequest",
"constructs",
"a",
"request",
"Convert",
"payload",
"to",
"a",
"JSON"
] | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L159-L170 | train |
logpacker/PayPal-Go-SDK | client.go | log | func (c *Client) log(r *http.Request, resp *http.Response) {
if c.Log != nil {
var (
reqDump string
respDump []byte
)
if r != nil {
reqDump = fmt.Sprintf("%s %s. Data: %s", r.Method, r.URL.String(), r.Form.Encode())
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}
c.Log.Write([]byte(fmt.Sprintf("Request: %s\nResponse: %s\n", reqDump, string(respDump))))
}
} | go | func (c *Client) log(r *http.Request, resp *http.Response) {
if c.Log != nil {
var (
reqDump string
respDump []byte
)
if r != nil {
reqDump = fmt.Sprintf("%s %s. Data: %s", r.Method, r.URL.String(), r.Form.Encode())
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}
c.Log.Write([]byte(fmt.Sprintf("Request: %s\nResponse: %s\n", reqDump, string(respDump))))
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"log",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"resp",
"*",
"http",
".",
"Response",
")",
"{",
"if",
"c",
".",
"Log",
"!=",
"nil",
"{",
"var",
"(",
"reqDump",
"string",
"\n",
"respDump",
"[",
"]",
"byte... | // log will dump request and response to the log file | [
"log",
"will",
"dump",
"request",
"and",
"response",
"to",
"the",
"log",
"file"
] | 17ba889ca032031de3a3317087493307ca801dd9 | https://github.com/logpacker/PayPal-Go-SDK/blob/17ba889ca032031de3a3317087493307ca801dd9/client.go#L173-L189 | train |
didip/tollbooth | libstring/libstring.go | StringInSlice | func StringInSlice(sliceString []string, needle string) bool {
for _, b := range sliceString {
if b == needle {
return true
}
}
return false
} | go | func StringInSlice(sliceString []string, needle string) bool {
for _, b := range sliceString {
if b == needle {
return true
}
}
return false
} | [
"func",
"StringInSlice",
"(",
"sliceString",
"[",
"]",
"string",
",",
"needle",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"sliceString",
"{",
"if",
"b",
"==",
"needle",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return... | // StringInSlice finds needle in a slice of strings. | [
"StringInSlice",
"finds",
"needle",
"in",
"a",
"slice",
"of",
"strings",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/libstring/libstring.go#L11-L18 | train |
didip/tollbooth | tollbooth.go | setResponseHeaders | func setResponseHeaders(lmt *limiter.Limiter, w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Rate-Limit-Limit", fmt.Sprintf("%.2f", lmt.GetMax()))
w.Header().Add("X-Rate-Limit-Duration", "1")
w.Header().Add("X-Rate-Limit-Request-Forwarded-For", r.Header.Get("X-Forwarded-For"))
w.Header().Add("X-Rate-Limit-Request-Remote-Addr", r.RemoteAddr)
} | go | func setResponseHeaders(lmt *limiter.Limiter, w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Rate-Limit-Limit", fmt.Sprintf("%.2f", lmt.GetMax()))
w.Header().Add("X-Rate-Limit-Duration", "1")
w.Header().Add("X-Rate-Limit-Request-Forwarded-For", r.Header.Get("X-Forwarded-For"))
w.Header().Add("X-Rate-Limit-Request-Remote-Addr", r.RemoteAddr)
} | [
"func",
"setResponseHeaders",
"(",
"lmt",
"*",
"limiter",
".",
"Limiter",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf... | // setResponseHeaders configures X-Rate-Limit-Limit and X-Rate-Limit-Duration | [
"setResponseHeaders",
"configures",
"X",
"-",
"Rate",
"-",
"Limit",
"-",
"Limit",
"and",
"X",
"-",
"Rate",
"-",
"Limit",
"-",
"Duration"
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L16-L21 | train |
didip/tollbooth | tollbooth.go | NewLimiter | func NewLimiter(max float64, tbOptions *limiter.ExpirableOptions) *limiter.Limiter {
return limiter.New(tbOptions).SetMax(max).SetBurst(int(math.Max(1, max)))
} | go | func NewLimiter(max float64, tbOptions *limiter.ExpirableOptions) *limiter.Limiter {
return limiter.New(tbOptions).SetMax(max).SetBurst(int(math.Max(1, max)))
} | [
"func",
"NewLimiter",
"(",
"max",
"float64",
",",
"tbOptions",
"*",
"limiter",
".",
"ExpirableOptions",
")",
"*",
"limiter",
".",
"Limiter",
"{",
"return",
"limiter",
".",
"New",
"(",
"tbOptions",
")",
".",
"SetMax",
"(",
"max",
")",
".",
"SetBurst",
"("... | // NewLimiter is a convenience function to limiter.New. | [
"NewLimiter",
"is",
"a",
"convenience",
"function",
"to",
"limiter",
".",
"New",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L24-L26 | train |
didip/tollbooth | tollbooth.go | LimitHandler | func LimitHandler(lmt *limiter.Limiter, next http.Handler) http.Handler {
middle := func(w http.ResponseWriter, r *http.Request) {
httpError := LimitByRequest(lmt, w, r)
if httpError != nil {
lmt.ExecOnLimitReached(w, r)
w.Header().Add("Content-Type", lmt.GetMessageContentType())
w.WriteHeader(httpError.StatusCode)
w.Write([]byte(httpError.Message))
return
}
// There's no rate-limit error, serve the next handler.
next.ServeHTTP(w, r)
}
return http.HandlerFunc(middle)
} | go | func LimitHandler(lmt *limiter.Limiter, next http.Handler) http.Handler {
middle := func(w http.ResponseWriter, r *http.Request) {
httpError := LimitByRequest(lmt, w, r)
if httpError != nil {
lmt.ExecOnLimitReached(w, r)
w.Header().Add("Content-Type", lmt.GetMessageContentType())
w.WriteHeader(httpError.StatusCode)
w.Write([]byte(httpError.Message))
return
}
// There's no rate-limit error, serve the next handler.
next.ServeHTTP(w, r)
}
return http.HandlerFunc(middle)
} | [
"func",
"LimitHandler",
"(",
"lmt",
"*",
"limiter",
".",
"Limiter",
",",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"middle",
":=",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{... | // LimitHandler is a middleware that performs rate-limiting given http.Handler struct. | [
"LimitHandler",
"is",
"a",
"middleware",
"that",
"performs",
"rate",
"-",
"limiting",
"given",
"http",
".",
"Handler",
"struct",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L159-L175 | train |
didip/tollbooth | tollbooth.go | LimitFuncHandler | func LimitFuncHandler(lmt *limiter.Limiter, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler {
return LimitHandler(lmt, http.HandlerFunc(nextFunc))
} | go | func LimitFuncHandler(lmt *limiter.Limiter, nextFunc func(http.ResponseWriter, *http.Request)) http.Handler {
return LimitHandler(lmt, http.HandlerFunc(nextFunc))
} | [
"func",
"LimitFuncHandler",
"(",
"lmt",
"*",
"limiter",
".",
"Limiter",
",",
"nextFunc",
"func",
"(",
"http",
".",
"ResponseWriter",
",",
"*",
"http",
".",
"Request",
")",
")",
"http",
".",
"Handler",
"{",
"return",
"LimitHandler",
"(",
"lmt",
",",
"http... | // LimitFuncHandler is a middleware that performs rate-limiting given request handler function. | [
"LimitFuncHandler",
"is",
"a",
"middleware",
"that",
"performs",
"rate",
"-",
"limiting",
"given",
"request",
"handler",
"function",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/tollbooth.go#L178-L180 | train |
didip/tollbooth | errors/errors.go | Error | func (httperror *HTTPError) Error() string {
return fmt.Sprintf("%v: %v", httperror.StatusCode, httperror.Message)
} | go | func (httperror *HTTPError) Error() string {
return fmt.Sprintf("%v: %v", httperror.StatusCode, httperror.Message)
} | [
"func",
"(",
"httperror",
"*",
"HTTPError",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"httperror",
".",
"StatusCode",
",",
"httperror",
".",
"Message",
")",
"\n",
"}"
] | // Error returns error message. | [
"Error",
"returns",
"error",
"message",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/errors/errors.go#L13-L15 | train |
didip/tollbooth | limiter/limiter.go | New | func New(generalExpirableOptions *ExpirableOptions) *Limiter {
lmt := &Limiter{}
lmt.SetMessageContentType("text/plain; charset=utf-8").
SetMessage("You have reached maximum request limit.").
SetStatusCode(429).
SetOnLimitReached(nil).
SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}).
SetForwardedForIndexFromBehind(0).
SetHeaders(make(map[string][]string))
if generalExpirableOptions != nil {
lmt.generalExpirableOptions = generalExpirableOptions
} else {
lmt.generalExpirableOptions = &ExpirableOptions{}
}
// Default for ExpireJobInterval is every minute.
if lmt.generalExpirableOptions.ExpireJobInterval <= 0 {
lmt.generalExpirableOptions.ExpireJobInterval = time.Minute
}
// Default for DefaultExpirationTTL is 10 years.
if lmt.generalExpirableOptions.DefaultExpirationTTL <= 0 {
lmt.generalExpirableOptions.DefaultExpirationTTL = 87600 * time.Hour
}
lmt.tokenBuckets = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
lmt.basicAuthUsers = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
return lmt
} | go | func New(generalExpirableOptions *ExpirableOptions) *Limiter {
lmt := &Limiter{}
lmt.SetMessageContentType("text/plain; charset=utf-8").
SetMessage("You have reached maximum request limit.").
SetStatusCode(429).
SetOnLimitReached(nil).
SetIPLookups([]string{"RemoteAddr", "X-Forwarded-For", "X-Real-IP"}).
SetForwardedForIndexFromBehind(0).
SetHeaders(make(map[string][]string))
if generalExpirableOptions != nil {
lmt.generalExpirableOptions = generalExpirableOptions
} else {
lmt.generalExpirableOptions = &ExpirableOptions{}
}
// Default for ExpireJobInterval is every minute.
if lmt.generalExpirableOptions.ExpireJobInterval <= 0 {
lmt.generalExpirableOptions.ExpireJobInterval = time.Minute
}
// Default for DefaultExpirationTTL is 10 years.
if lmt.generalExpirableOptions.DefaultExpirationTTL <= 0 {
lmt.generalExpirableOptions.DefaultExpirationTTL = 87600 * time.Hour
}
lmt.tokenBuckets = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
lmt.basicAuthUsers = gocache.New(
lmt.generalExpirableOptions.DefaultExpirationTTL,
lmt.generalExpirableOptions.ExpireJobInterval,
)
return lmt
} | [
"func",
"New",
"(",
"generalExpirableOptions",
"*",
"ExpirableOptions",
")",
"*",
"Limiter",
"{",
"lmt",
":=",
"&",
"Limiter",
"{",
"}",
"\n\n",
"lmt",
".",
"SetMessageContentType",
"(",
"\"",
"\"",
")",
".",
"SetMessage",
"(",
"\"",
"\"",
")",
".",
"Set... | // New is a constructor for Limiter. | [
"New",
"is",
"a",
"constructor",
"for",
"Limiter",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L14-L52 | train |
didip/tollbooth | limiter/limiter.go | SetTokenBucketExpirationTTL | func (l *Limiter) SetTokenBucketExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.tokenBucketExpirationTTL = ttl
l.Unlock()
return l
} | go | func (l *Limiter) SetTokenBucketExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.tokenBucketExpirationTTL = ttl
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetTokenBucketExpirationTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"tokenBucketExpirationTTL",
"=",
"ttl",
"\n",
"l",
".",
"Unlock",
"(",
")",... | // SetTokenBucketExpirationTTL is thread-safe way of setting custom token bucket expiration TTL. | [
"SetTokenBucketExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"custom",
"token",
"bucket",
"expiration",
"TTL",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L106-L112 | train |
didip/tollbooth | limiter/limiter.go | GetTokenBucketExpirationTTL | func (l *Limiter) GetTokenBucketExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.tokenBucketExpirationTTL
} | go | func (l *Limiter) GetTokenBucketExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.tokenBucketExpirationTTL
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetTokenBucketExpirationTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"tokenBucketExpirationTTL",
"\n",
"}"
] | // GettokenBucketExpirationTTL is thread-safe way of getting custom token bucket expiration TTL. | [
"GettokenBucketExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"custom",
"token",
"bucket",
"expiration",
"TTL",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L115-L119 | train |
didip/tollbooth | limiter/limiter.go | SetBasicAuthExpirationTTL | func (l *Limiter) SetBasicAuthExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.basicAuthExpirationTTL = ttl
l.Unlock()
return l
} | go | func (l *Limiter) SetBasicAuthExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.basicAuthExpirationTTL = ttl
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetBasicAuthExpirationTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"basicAuthExpirationTTL",
"=",
"ttl",
"\n",
"l",
".",
"Unlock",
"(",
")",
"... | // SetBasicAuthExpirationTTL is thread-safe way of setting custom basic auth expiration TTL. | [
"SetBasicAuthExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L122-L128 | train |
didip/tollbooth | limiter/limiter.go | GetBasicAuthExpirationTTL | func (l *Limiter) GetBasicAuthExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.basicAuthExpirationTTL
} | go | func (l *Limiter) GetBasicAuthExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.basicAuthExpirationTTL
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetBasicAuthExpirationTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"basicAuthExpirationTTL",
"\n",
"}"
] | // GetBasicAuthExpirationTTL is thread-safe way of getting custom basic auth expiration TTL. | [
"GetBasicAuthExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L131-L135 | train |
didip/tollbooth | limiter/limiter.go | SetHeaderEntryExpirationTTL | func (l *Limiter) SetHeaderEntryExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.headerEntryExpirationTTL = ttl
l.Unlock()
return l
} | go | func (l *Limiter) SetHeaderEntryExpirationTTL(ttl time.Duration) *Limiter {
l.Lock()
l.headerEntryExpirationTTL = ttl
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetHeaderEntryExpirationTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"headerEntryExpirationTTL",
"=",
"ttl",
"\n",
"l",
".",
"Unlock",
"(",
")",... | // SetHeaderEntryExpirationTTL is thread-safe way of setting custom basic auth expiration TTL. | [
"SetHeaderEntryExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L138-L144 | train |
didip/tollbooth | limiter/limiter.go | GetHeaderEntryExpirationTTL | func (l *Limiter) GetHeaderEntryExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.headerEntryExpirationTTL
} | go | func (l *Limiter) GetHeaderEntryExpirationTTL() time.Duration {
l.RLock()
defer l.RUnlock()
return l.headerEntryExpirationTTL
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetHeaderEntryExpirationTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"headerEntryExpirationTTL",
"\n",
"}"
] | // GetHeaderEntryExpirationTTL is thread-safe way of getting custom basic auth expiration TTL. | [
"GetHeaderEntryExpirationTTL",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"custom",
"basic",
"auth",
"expiration",
"TTL",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L147-L151 | train |
didip/tollbooth | limiter/limiter.go | SetMax | func (l *Limiter) SetMax(max float64) *Limiter {
l.Lock()
l.max = max
l.Unlock()
return l
} | go | func (l *Limiter) SetMax(max float64) *Limiter {
l.Lock()
l.max = max
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetMax",
"(",
"max",
"float64",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"max",
"=",
"max",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] | // SetMax is thread-safe way of setting maximum number of requests to limit per duration. | [
"SetMax",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"maximum",
"number",
"of",
"requests",
"to",
"limit",
"per",
"duration",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L154-L160 | train |
didip/tollbooth | limiter/limiter.go | GetMax | func (l *Limiter) GetMax() float64 {
l.RLock()
defer l.RUnlock()
return l.max
} | go | func (l *Limiter) GetMax() float64 {
l.RLock()
defer l.RUnlock()
return l.max
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetMax",
"(",
")",
"float64",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"max",
"\n",
"}"
] | // GetMax is thread-safe way of getting maximum number of requests to limit per duration. | [
"GetMax",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"maximum",
"number",
"of",
"requests",
"to",
"limit",
"per",
"duration",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L163-L167 | train |
didip/tollbooth | limiter/limiter.go | SetBurst | func (l *Limiter) SetBurst(burst int) *Limiter {
l.Lock()
l.burst = burst
l.Unlock()
return l
} | go | func (l *Limiter) SetBurst(burst int) *Limiter {
l.Lock()
l.burst = burst
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetBurst",
"(",
"burst",
"int",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"burst",
"=",
"burst",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] | // SetBurst is thread-safe way of setting maximum burst size. | [
"SetBurst",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"maximum",
"burst",
"size",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L170-L176 | train |
didip/tollbooth | limiter/limiter.go | GetBurst | func (l *Limiter) GetBurst() int {
l.RLock()
defer l.RUnlock()
return l.burst
} | go | func (l *Limiter) GetBurst() int {
l.RLock()
defer l.RUnlock()
return l.burst
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetBurst",
"(",
")",
"int",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"l",
".",
"burst",
"\n",
"}"
] | // GetBurst is thread-safe way of setting maximum burst size. | [
"GetBurst",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"maximum",
"burst",
"size",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L179-L184 | train |
didip/tollbooth | limiter/limiter.go | SetMessage | func (l *Limiter) SetMessage(msg string) *Limiter {
l.Lock()
l.message = msg
l.Unlock()
return l
} | go | func (l *Limiter) SetMessage(msg string) *Limiter {
l.Lock()
l.message = msg
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetMessage",
"(",
"msg",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"message",
"=",
"msg",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n",
"}"
] | // SetMessage is thread-safe way of setting HTTP message when limit is reached. | [
"SetMessage",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"HTTP",
"message",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L187-L193 | train |
didip/tollbooth | limiter/limiter.go | GetMessage | func (l *Limiter) GetMessage() string {
l.RLock()
defer l.RUnlock()
return l.message
} | go | func (l *Limiter) GetMessage() string {
l.RLock()
defer l.RUnlock()
return l.message
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetMessage",
"(",
")",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"message",
"\n",
"}"
] | // GetMessage is thread-safe way of getting HTTP message when limit is reached. | [
"GetMessage",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"HTTP",
"message",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L196-L200 | train |
didip/tollbooth | limiter/limiter.go | SetMessageContentType | func (l *Limiter) SetMessageContentType(contentType string) *Limiter {
l.Lock()
l.messageContentType = contentType
l.Unlock()
return l
} | go | func (l *Limiter) SetMessageContentType(contentType string) *Limiter {
l.Lock()
l.messageContentType = contentType
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetMessageContentType",
"(",
"contentType",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"messageContentType",
"=",
"contentType",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"r... | // SetMessageContentType is thread-safe way of setting HTTP message Content-Type when limit is reached. | [
"SetMessageContentType",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"HTTP",
"message",
"Content",
"-",
"Type",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L203-L209 | train |
didip/tollbooth | limiter/limiter.go | GetMessageContentType | func (l *Limiter) GetMessageContentType() string {
l.RLock()
defer l.RUnlock()
return l.messageContentType
} | go | func (l *Limiter) GetMessageContentType() string {
l.RLock()
defer l.RUnlock()
return l.messageContentType
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetMessageContentType",
"(",
")",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"messageContentType",
"\n",
"}"
] | // GetMessageContentType is thread-safe way of getting HTTP message Content-Type when limit is reached. | [
"GetMessageContentType",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"HTTP",
"message",
"Content",
"-",
"Type",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L212-L216 | train |
didip/tollbooth | limiter/limiter.go | SetStatusCode | func (l *Limiter) SetStatusCode(statusCode int) *Limiter {
l.Lock()
l.statusCode = statusCode
l.Unlock()
return l
} | go | func (l *Limiter) SetStatusCode(statusCode int) *Limiter {
l.Lock()
l.statusCode = statusCode
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetStatusCode",
"(",
"statusCode",
"int",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"statusCode",
"=",
"statusCode",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"l",
"\n"... | // SetStatusCode is thread-safe way of setting HTTP status code when limit is reached. | [
"SetStatusCode",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"HTTP",
"status",
"code",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L219-L225 | train |
didip/tollbooth | limiter/limiter.go | GetStatusCode | func (l *Limiter) GetStatusCode() int {
l.RLock()
defer l.RUnlock()
return l.statusCode
} | go | func (l *Limiter) GetStatusCode() int {
l.RLock()
defer l.RUnlock()
return l.statusCode
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetStatusCode",
"(",
")",
"int",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"statusCode",
"\n",
"}"
] | // GetStatusCode is thread-safe way of getting HTTP status code when limit is reached. | [
"GetStatusCode",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"HTTP",
"status",
"code",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L228-L232 | train |
didip/tollbooth | limiter/limiter.go | SetOnLimitReached | func (l *Limiter) SetOnLimitReached(fn func(w http.ResponseWriter, r *http.Request)) *Limiter {
l.Lock()
l.onLimitReached = fn
l.Unlock()
return l
} | go | func (l *Limiter) SetOnLimitReached(fn func(w http.ResponseWriter, r *http.Request)) *Limiter {
l.Lock()
l.onLimitReached = fn
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetOnLimitReached",
"(",
"fn",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"onLimitReache... | // SetOnLimitReached is thread-safe way of setting after-rejection function when limit is reached. | [
"SetOnLimitReached",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"after",
"-",
"rejection",
"function",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L235-L241 | train |
didip/tollbooth | limiter/limiter.go | ExecOnLimitReached | func (l *Limiter) ExecOnLimitReached(w http.ResponseWriter, r *http.Request) {
l.RLock()
defer l.RUnlock()
fn := l.onLimitReached
if fn != nil {
fn(w, r)
}
} | go | func (l *Limiter) ExecOnLimitReached(w http.ResponseWriter, r *http.Request) {
l.RLock()
defer l.RUnlock()
fn := l.onLimitReached
if fn != nil {
fn(w, r)
}
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"ExecOnLimitReached",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n\n",
"fn",
":=",
... | // ExecOnLimitReached is thread-safe way of executing after-rejection function when limit is reached. | [
"ExecOnLimitReached",
"is",
"thread",
"-",
"safe",
"way",
"of",
"executing",
"after",
"-",
"rejection",
"function",
"when",
"limit",
"is",
"reached",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L244-L252 | train |
didip/tollbooth | limiter/limiter.go | SetIPLookups | func (l *Limiter) SetIPLookups(ipLookups []string) *Limiter {
l.Lock()
l.ipLookups = ipLookups
l.Unlock()
return l
} | go | func (l *Limiter) SetIPLookups(ipLookups []string) *Limiter {
l.Lock()
l.ipLookups = ipLookups
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetIPLookups",
"(",
"ipLookups",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"ipLookups",
"=",
"ipLookups",
"\n",
"l",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
... | // SetIPLookups is thread-safe way of setting list of places to look up IP address. | [
"SetIPLookups",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"list",
"of",
"places",
"to",
"look",
"up",
"IP",
"address",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L255-L261 | train |
didip/tollbooth | limiter/limiter.go | GetIPLookups | func (l *Limiter) GetIPLookups() []string {
l.RLock()
defer l.RUnlock()
return l.ipLookups
} | go | func (l *Limiter) GetIPLookups() []string {
l.RLock()
defer l.RUnlock()
return l.ipLookups
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetIPLookups",
"(",
")",
"[",
"]",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"ipLookups",
"\n",
"}"
] | // GetIPLookups is thread-safe way of getting list of places to look up IP address. | [
"GetIPLookups",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"list",
"of",
"places",
"to",
"look",
"up",
"IP",
"address",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L264-L268 | train |
didip/tollbooth | limiter/limiter.go | SetForwardedForIndexFromBehind | func (l *Limiter) SetForwardedForIndexFromBehind(forwardedForIndex int) *Limiter {
l.Lock()
l.forwardedForIndex = forwardedForIndex
l.Unlock()
return l
} | go | func (l *Limiter) SetForwardedForIndexFromBehind(forwardedForIndex int) *Limiter {
l.Lock()
l.forwardedForIndex = forwardedForIndex
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetForwardedForIndexFromBehind",
"(",
"forwardedForIndex",
"int",
")",
"*",
"Limiter",
"{",
"l",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"forwardedForIndex",
"=",
"forwardedForIndex",
"\n",
"l",
".",
"Unlock",
"(",
")... | // SetForwardedForIndexFromBehind is thread-safe way of setting which X-Forwarded-For index to choose. | [
"SetForwardedForIndexFromBehind",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"which",
"X",
"-",
"Forwarded",
"-",
"For",
"index",
"to",
"choose",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L271-L277 | train |
didip/tollbooth | limiter/limiter.go | GetForwardedForIndexFromBehind | func (l *Limiter) GetForwardedForIndexFromBehind() int {
l.RLock()
defer l.RUnlock()
return l.forwardedForIndex
} | go | func (l *Limiter) GetForwardedForIndexFromBehind() int {
l.RLock()
defer l.RUnlock()
return l.forwardedForIndex
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetForwardedForIndexFromBehind",
"(",
")",
"int",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"defer",
"l",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"l",
".",
"forwardedForIndex",
"\n",
"}"
] | // GetForwardedForIndexFromBehind is thread-safe way of getting which X-Forwarded-For index to choose. | [
"GetForwardedForIndexFromBehind",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"which",
"X",
"-",
"Forwarded",
"-",
"For",
"index",
"to",
"choose",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L280-L284 | train |
didip/tollbooth | limiter/limiter.go | SetBasicAuthUsers | func (l *Limiter) SetBasicAuthUsers(basicAuthUsers []string) *Limiter {
ttl := l.GetBasicAuthExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
for _, basicAuthUser := range basicAuthUsers {
l.basicAuthUsers.Set(basicAuthUser, true, ttl)
}
return l
} | go | func (l *Limiter) SetBasicAuthUsers(basicAuthUsers []string) *Limiter {
ttl := l.GetBasicAuthExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
for _, basicAuthUser := range basicAuthUsers {
l.basicAuthUsers.Set(basicAuthUser, true, ttl)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetBasicAuthUsers",
"(",
"basicAuthUsers",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"ttl",
":=",
"l",
".",
"GetBasicAuthExpirationTTL",
"(",
")",
"\n",
"if",
"ttl",
"<=",
"0",
"{",
"ttl",
"=",
"l",
".",
"g... | // SetBasicAuthUsers is thread-safe way of setting list of basic auth usernames to limit. | [
"SetBasicAuthUsers",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"list",
"of",
"basic",
"auth",
"usernames",
"to",
"limit",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L303-L314 | train |
didip/tollbooth | limiter/limiter.go | GetBasicAuthUsers | func (l *Limiter) GetBasicAuthUsers() []string {
asMap := l.basicAuthUsers.Items()
var basicAuthUsers []string
for basicAuthUser, _ := range asMap {
basicAuthUsers = append(basicAuthUsers, basicAuthUser)
}
return basicAuthUsers
} | go | func (l *Limiter) GetBasicAuthUsers() []string {
asMap := l.basicAuthUsers.Items()
var basicAuthUsers []string
for basicAuthUser, _ := range asMap {
basicAuthUsers = append(basicAuthUsers, basicAuthUser)
}
return basicAuthUsers
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetBasicAuthUsers",
"(",
")",
"[",
"]",
"string",
"{",
"asMap",
":=",
"l",
".",
"basicAuthUsers",
".",
"Items",
"(",
")",
"\n\n",
"var",
"basicAuthUsers",
"[",
"]",
"string",
"\n",
"for",
"basicAuthUser",
",",
"_... | // GetBasicAuthUsers is thread-safe way of getting list of basic auth usernames to limit. | [
"GetBasicAuthUsers",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"list",
"of",
"basic",
"auth",
"usernames",
"to",
"limit",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L317-L326 | train |
didip/tollbooth | limiter/limiter.go | RemoveBasicAuthUsers | func (l *Limiter) RemoveBasicAuthUsers(basicAuthUsers []string) *Limiter {
for _, toBeRemoved := range basicAuthUsers {
l.basicAuthUsers.Delete(toBeRemoved)
}
return l
} | go | func (l *Limiter) RemoveBasicAuthUsers(basicAuthUsers []string) *Limiter {
for _, toBeRemoved := range basicAuthUsers {
l.basicAuthUsers.Delete(toBeRemoved)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"RemoveBasicAuthUsers",
"(",
"basicAuthUsers",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"for",
"_",
",",
"toBeRemoved",
":=",
"range",
"basicAuthUsers",
"{",
"l",
".",
"basicAuthUsers",
".",
"Delete",
"(",
"toBeR... | // RemoveBasicAuthUsers is thread-safe way of removing basic auth usernames from existing list. | [
"RemoveBasicAuthUsers",
"is",
"thread",
"-",
"safe",
"way",
"of",
"removing",
"basic",
"auth",
"usernames",
"from",
"existing",
"list",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L329-L335 | train |
didip/tollbooth | limiter/limiter.go | SetHeaders | func (l *Limiter) SetHeaders(headers map[string][]string) *Limiter {
if l.headers == nil {
l.headers = make(map[string]*gocache.Cache)
}
for header, entries := range headers {
l.SetHeader(header, entries)
}
return l
} | go | func (l *Limiter) SetHeaders(headers map[string][]string) *Limiter {
if l.headers == nil {
l.headers = make(map[string]*gocache.Cache)
}
for header, entries := range headers {
l.SetHeader(header, entries)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetHeaders",
"(",
"headers",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"if",
"l",
".",
"headers",
"==",
"nil",
"{",
"l",
".",
"headers",
"=",
"make",
"(",
"map",
"[",
"string"... | // SetHeaders is thread-safe way of setting map of HTTP headers to limit. | [
"SetHeaders",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"map",
"of",
"HTTP",
"headers",
"to",
"limit",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L338-L348 | train |
didip/tollbooth | limiter/limiter.go | GetHeaders | func (l *Limiter) GetHeaders() map[string][]string {
results := make(map[string][]string)
l.RLock()
defer l.RUnlock()
for header, entriesAsGoCache := range l.headers {
entries := make([]string, 0)
for entry, _ := range entriesAsGoCache.Items() {
entries = append(entries, entry)
}
results[header] = entries
}
return results
} | go | func (l *Limiter) GetHeaders() map[string][]string {
results := make(map[string][]string)
l.RLock()
defer l.RUnlock()
for header, entriesAsGoCache := range l.headers {
entries := make([]string, 0)
for entry, _ := range entriesAsGoCache.Items() {
entries = append(entries, entry)
}
results[header] = entries
}
return results
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetHeaders",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"results",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n\n",
"l",
".",
"RLock",
"(",
")",
"\n",
"def... | // GetHeaders is thread-safe way of getting map of HTTP headers to limit. | [
"GetHeaders",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"map",
"of",
"HTTP",
"headers",
"to",
"limit",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L351-L368 | train |
didip/tollbooth | limiter/limiter.go | SetHeader | func (l *Limiter) SetHeader(header string, entries []string) *Limiter {
l.RLock()
existing, found := l.headers[header]
l.RUnlock()
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
if !found {
existing = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
}
for _, entry := range entries {
existing.Set(entry, true, ttl)
}
l.Lock()
l.headers[header] = existing
l.Unlock()
return l
} | go | func (l *Limiter) SetHeader(header string, entries []string) *Limiter {
l.RLock()
existing, found := l.headers[header]
l.RUnlock()
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
if !found {
existing = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
}
for _, entry := range entries {
existing.Set(entry, true, ttl)
}
l.Lock()
l.headers[header] = existing
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"SetHeader",
"(",
"header",
"string",
",",
"entries",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"existing",
",",
"found",
":=",
"l",
".",
"headers",
"[",
"header",
"]",
... | // SetHeader is thread-safe way of setting entries of 1 HTTP header. | [
"SetHeader",
"is",
"thread",
"-",
"safe",
"way",
"of",
"setting",
"entries",
"of",
"1",
"HTTP",
"header",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L371-L394 | train |
didip/tollbooth | limiter/limiter.go | GetHeader | func (l *Limiter) GetHeader(header string) []string {
l.RLock()
entriesAsGoCache := l.headers[header]
l.RUnlock()
entriesAsMap := entriesAsGoCache.Items()
entries := make([]string, 0)
for entry, _ := range entriesAsMap {
entries = append(entries, entry)
}
return entries
} | go | func (l *Limiter) GetHeader(header string) []string {
l.RLock()
entriesAsGoCache := l.headers[header]
l.RUnlock()
entriesAsMap := entriesAsGoCache.Items()
entries := make([]string, 0)
for entry, _ := range entriesAsMap {
entries = append(entries, entry)
}
return entries
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"GetHeader",
"(",
"header",
"string",
")",
"[",
"]",
"string",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"entriesAsGoCache",
":=",
"l",
".",
"headers",
"[",
"header",
"]",
"\n",
"l",
".",
"RUnlock",
"(",
")",
... | // GetHeader is thread-safe way of getting entries of 1 HTTP header. | [
"GetHeader",
"is",
"thread",
"-",
"safe",
"way",
"of",
"getting",
"entries",
"of",
"1",
"HTTP",
"header",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L397-L410 | train |
didip/tollbooth | limiter/limiter.go | RemoveHeader | func (l *Limiter) RemoveHeader(header string) *Limiter {
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
l.Lock()
l.headers[header] = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
l.Unlock()
return l
} | go | func (l *Limiter) RemoveHeader(header string) *Limiter {
ttl := l.GetHeaderEntryExpirationTTL()
if ttl <= 0 {
ttl = l.generalExpirableOptions.DefaultExpirationTTL
}
l.Lock()
l.headers[header] = gocache.New(ttl, l.generalExpirableOptions.ExpireJobInterval)
l.Unlock()
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"RemoveHeader",
"(",
"header",
"string",
")",
"*",
"Limiter",
"{",
"ttl",
":=",
"l",
".",
"GetHeaderEntryExpirationTTL",
"(",
")",
"\n",
"if",
"ttl",
"<=",
"0",
"{",
"ttl",
"=",
"l",
".",
"generalExpirableOptions",
... | // RemoveHeader is thread-safe way of removing entries of 1 HTTP header. | [
"RemoveHeader",
"is",
"thread",
"-",
"safe",
"way",
"of",
"removing",
"entries",
"of",
"1",
"HTTP",
"header",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L413-L424 | train |
didip/tollbooth | limiter/limiter.go | RemoveHeaderEntries | func (l *Limiter) RemoveHeaderEntries(header string, entriesForRemoval []string) *Limiter {
l.RLock()
entries, found := l.headers[header]
l.RUnlock()
if !found {
return l
}
for _, toBeRemoved := range entriesForRemoval {
entries.Delete(toBeRemoved)
}
return l
} | go | func (l *Limiter) RemoveHeaderEntries(header string, entriesForRemoval []string) *Limiter {
l.RLock()
entries, found := l.headers[header]
l.RUnlock()
if !found {
return l
}
for _, toBeRemoved := range entriesForRemoval {
entries.Delete(toBeRemoved)
}
return l
} | [
"func",
"(",
"l",
"*",
"Limiter",
")",
"RemoveHeaderEntries",
"(",
"header",
"string",
",",
"entriesForRemoval",
"[",
"]",
"string",
")",
"*",
"Limiter",
"{",
"l",
".",
"RLock",
"(",
")",
"\n",
"entries",
",",
"found",
":=",
"l",
".",
"headers",
"[",
... | // RemoveHeaderEntries is thread-safe way of adding new entries to 1 HTTP header rule. | [
"RemoveHeaderEntries",
"is",
"thread",
"-",
"safe",
"way",
"of",
"adding",
"new",
"entries",
"to",
"1",
"HTTP",
"header",
"rule",
"."
] | b10a036da5f05864224ee09432e489b32a6b2d1d | https://github.com/didip/tollbooth/blob/b10a036da5f05864224ee09432e489b32a6b2d1d/limiter/limiter.go#L427-L441 | train |
AlecAivazis/survey | survey.go | WithStdio | func WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt {
return func(options *AskOptions) error {
options.Stdio.In = in
options.Stdio.Out = out
options.Stdio.Err = err
return nil
}
} | go | func WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt {
return func(options *AskOptions) error {
options.Stdio.In = in
options.Stdio.Out = out
options.Stdio.Err = err
return nil
}
} | [
"func",
"WithStdio",
"(",
"in",
"terminal",
".",
"FileReader",
",",
"out",
"terminal",
".",
"FileWriter",
",",
"err",
"io",
".",
"Writer",
")",
"AskOpt",
"{",
"return",
"func",
"(",
"options",
"*",
"AskOptions",
")",
"error",
"{",
"options",
".",
"Stdio"... | // WithStdio specifies the standard input, output and error files survey
// interacts with. By default, these are os.Stdin, os.Stdout, and os.Stderr. | [
"WithStdio",
"specifies",
"the",
"standard",
"input",
"output",
"and",
"error",
"files",
"survey",
"interacts",
"with",
".",
"By",
"default",
"these",
"are",
"os",
".",
"Stdin",
"os",
".",
"Stdout",
"and",
"os",
".",
"Stderr",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/survey.go#L67-L74 | train |
AlecAivazis/survey | survey.go | paginate | func paginate(page int, choices []string, sel int) ([]string, int) {
// the number of elements to show in a single page
var pageSize int
// if the select has a specific page size
if page != 0 {
// use the specified one
pageSize = page
// otherwise the select does not have a page size
} else {
// use the package default
pageSize = PageSize
}
var start, end, cursor int
if len(choices) < pageSize {
// if we dont have enough options to fill a page
start = 0
end = len(choices)
cursor = sel
} else if sel < pageSize/2 {
// if we are in the first half page
start = 0
end = pageSize
cursor = sel
} else if len(choices)-sel-1 < pageSize/2 {
// if we are in the last half page
start = len(choices) - pageSize
end = len(choices)
cursor = sel - start
} else {
// somewhere in the middle
above := pageSize / 2
below := pageSize - above
cursor = pageSize / 2
start = sel - above
end = sel + below
}
// return the subset we care about and the index
return choices[start:end], cursor
} | go | func paginate(page int, choices []string, sel int) ([]string, int) {
// the number of elements to show in a single page
var pageSize int
// if the select has a specific page size
if page != 0 {
// use the specified one
pageSize = page
// otherwise the select does not have a page size
} else {
// use the package default
pageSize = PageSize
}
var start, end, cursor int
if len(choices) < pageSize {
// if we dont have enough options to fill a page
start = 0
end = len(choices)
cursor = sel
} else if sel < pageSize/2 {
// if we are in the first half page
start = 0
end = pageSize
cursor = sel
} else if len(choices)-sel-1 < pageSize/2 {
// if we are in the last half page
start = len(choices) - pageSize
end = len(choices)
cursor = sel - start
} else {
// somewhere in the middle
above := pageSize / 2
below := pageSize - above
cursor = pageSize / 2
start = sel - above
end = sel + below
}
// return the subset we care about and the index
return choices[start:end], cursor
} | [
"func",
"paginate",
"(",
"page",
"int",
",",
"choices",
"[",
"]",
"string",
",",
"sel",
"int",
")",
"(",
"[",
"]",
"string",
",",
"int",
")",
"{",
"// the number of elements to show in a single page",
"var",
"pageSize",
"int",
"\n",
"// if the select has a speci... | // paginate returns a single page of choices given the page size, the total list of
// possible choices, and the current selected index in the total list. | [
"paginate",
"returns",
"a",
"single",
"page",
"of",
"choices",
"given",
"the",
"page",
"size",
"the",
"total",
"list",
"of",
"possible",
"choices",
"and",
"the",
"current",
"selected",
"index",
"in",
"the",
"total",
"list",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/survey.go#L210-L255 | train |
AlecAivazis/survey | transform.go | ComposeTransformers | func ComposeTransformers(transformers ...Transformer) Transformer {
// return a transformer that calls each one sequentially
return func(ans interface{}) interface{} {
// execute each transformer
for _, t := range transformers {
ans = t(ans)
}
return ans
}
} | go | func ComposeTransformers(transformers ...Transformer) Transformer {
// return a transformer that calls each one sequentially
return func(ans interface{}) interface{} {
// execute each transformer
for _, t := range transformers {
ans = t(ans)
}
return ans
}
} | [
"func",
"ComposeTransformers",
"(",
"transformers",
"...",
"Transformer",
")",
"Transformer",
"{",
"// return a transformer that calls each one sequentially",
"return",
"func",
"(",
"ans",
"interface",
"{",
"}",
")",
"interface",
"{",
"}",
"{",
"// execute each transforme... | // ComposeTransformers is a variadic function used to create one transformer from many. | [
"ComposeTransformers",
"is",
"a",
"variadic",
"function",
"used",
"to",
"create",
"one",
"transformer",
"from",
"many",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/transform.go#L67-L76 | train |
AlecAivazis/survey | validate.go | Required | func Required(val interface{}) error {
// the reflect value of the result
value := reflect.ValueOf(val)
// if the value passed in is the zero value of the appropriate type
if isZero(value) && value.Kind() != reflect.Bool {
return errors.New("Value is required")
}
return nil
} | go | func Required(val interface{}) error {
// the reflect value of the result
value := reflect.ValueOf(val)
// if the value passed in is the zero value of the appropriate type
if isZero(value) && value.Kind() != reflect.Bool {
return errors.New("Value is required")
}
return nil
} | [
"func",
"Required",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// the reflect value of the result",
"value",
":=",
"reflect",
".",
"ValueOf",
"(",
"val",
")",
"\n\n",
"// if the value passed in is the zero value of the appropriate type",
"if",
"isZero",
"(",... | // Required does not allow an empty value | [
"Required",
"does",
"not",
"allow",
"an",
"empty",
"value"
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L10-L19 | train |
AlecAivazis/survey | validate.go | MaxLength | func MaxLength(length int) Validator {
// return a validator that checks the length of the string
return func(val interface{}) error {
if str, ok := val.(string); ok {
// if the string is longer than the given value
if len([]rune(str)) > length {
// yell loudly
return fmt.Errorf("value is too long. Max length is %v", length)
}
} else {
// otherwise we cannot convert the value into a string and cannot enforce length
return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name())
}
// the input is fine
return nil
}
} | go | func MaxLength(length int) Validator {
// return a validator that checks the length of the string
return func(val interface{}) error {
if str, ok := val.(string); ok {
// if the string is longer than the given value
if len([]rune(str)) > length {
// yell loudly
return fmt.Errorf("value is too long. Max length is %v", length)
}
} else {
// otherwise we cannot convert the value into a string and cannot enforce length
return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name())
}
// the input is fine
return nil
}
} | [
"func",
"MaxLength",
"(",
"length",
"int",
")",
"Validator",
"{",
"// return a validator that checks the length of the string",
"return",
"func",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"str",
",",
"ok",
":=",
"val",
".",
"(",
"string",
")"... | // MaxLength requires that the string is no longer than the specified value | [
"MaxLength",
"requires",
"that",
"the",
"string",
"is",
"no",
"longer",
"than",
"the",
"specified",
"value"
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L22-L39 | train |
AlecAivazis/survey | validate.go | ComposeValidators | func ComposeValidators(validators ...Validator) Validator {
// return a validator that calls each one sequentially
return func(val interface{}) error {
// execute each validator
for _, validator := range validators {
// if the answer's value is not valid
if err := validator(val); err != nil {
// return the error
return err
}
}
// we passed all validators, the answer is valid
return nil
}
} | go | func ComposeValidators(validators ...Validator) Validator {
// return a validator that calls each one sequentially
return func(val interface{}) error {
// execute each validator
for _, validator := range validators {
// if the answer's value is not valid
if err := validator(val); err != nil {
// return the error
return err
}
}
// we passed all validators, the answer is valid
return nil
}
} | [
"func",
"ComposeValidators",
"(",
"validators",
"...",
"Validator",
")",
"Validator",
"{",
"// return a validator that calls each one sequentially",
"return",
"func",
"(",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// execute each validator",
"for",
"_",
",",
"... | // ComposeValidators is a variadic function used to create one validator from many. | [
"ComposeValidators",
"is",
"a",
"variadic",
"function",
"used",
"to",
"create",
"one",
"validator",
"from",
"many",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L62-L76 | train |
AlecAivazis/survey | validate.go | isZero | func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Slice, reflect.Map:
return v.Len() == 0
}
// compare the types directly with more general coverage
return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
} | go | func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Slice, reflect.Map:
return v.Len() == 0
}
// compare the types directly with more general coverage
return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
} | [
"func",
"isZero",
"(",
"v",
"reflect",
".",
"Value",
")",
"bool",
"{",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
":",
"return",
"v",
".",
"Len",
"(",
")",
"==",
"0",
"\n",
"}",
"\n\n... | // isZero returns true if the passed value is the zero object | [
"isZero",
"returns",
"true",
"if",
"the",
"passed",
"value",
"is",
"the",
"zero",
"object"
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/validate.go#L79-L87 | train |
AlecAivazis/survey | terminal/cursor.go | Up | func (c *Cursor) Up(n int) {
fmt.Fprintf(c.Out, "\x1b[%dA", n)
} | go | func (c *Cursor) Up(n int) {
fmt.Fprintf(c.Out, "\x1b[%dA", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Up",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
] | // Up moves the cursor n cells to up. | [
"Up",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"up",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L23-L25 | train |
AlecAivazis/survey | terminal/cursor.go | Down | func (c *Cursor) Down(n int) {
fmt.Fprintf(c.Out, "\x1b[%dB", n)
} | go | func (c *Cursor) Down(n int) {
fmt.Fprintf(c.Out, "\x1b[%dB", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Down",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
] | // Down moves the cursor n cells to down. | [
"Down",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"down",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L28-L30 | train |
AlecAivazis/survey | terminal/cursor.go | Forward | func (c *Cursor) Forward(n int) {
fmt.Fprintf(c.Out, "\x1b[%dC", n)
} | go | func (c *Cursor) Forward(n int) {
fmt.Fprintf(c.Out, "\x1b[%dC", n)
} | [
"func",
"(",
"c",
"*",
"Cursor",
")",
"Forward",
"(",
"n",
"int",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"c",
".",
"Out",
",",
"\"",
"\\x1b",
"\"",
",",
"n",
")",
"\n",
"}"
] | // Forward moves the cursor n cells to right. | [
"Forward",
"moves",
"the",
"cursor",
"n",
"cells",
"to",
"right",
"."
] | a84846dc69f1fbe032f4534f92e937684b9a3710 | https://github.com/AlecAivazis/survey/blob/a84846dc69f1fbe032f4534f92e937684b9a3710/terminal/cursor.go#L33-L35 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.