_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q14300 | PostForm | train | func (c *Context) PostForm(key string, defaultValue ...string) string {
r := c.Request
r.ParseMultipartForm(32 << 20)
if vs := r.PostForm[key]; len(vs) > 0 {
return vs[0]
}
if len(defaultValue) > 0 {
return defaultValue[0]
}
return ""
} | go | {
"resource": ""
} |
q14301 | Next | train | func (c *Context) Next() error {
c.index++
for n := len(c.handlers); c.index < n; c.index++ {
if err := c.handlers[c.index](c); err != nil {
return err
}
}
return nil
} | go | {
"resource": ""
} |
q14302 | Read | train | func (c *Context) Read(data interface{}) error {
if c.Request.Method != "GET" {
t := getContentType(c.Request)
if reader, ok := DataReaders[t]; ok {
return reader.Read(c.Request, data)
}
}
return DefaultFormDataReader.Read(c.Request, data)
} | go | {
"resource": ""
} |
q14303 | negotiateLanguage | train | func negotiateLanguage(r *http.Request, offers []string, defaultOffer string) string {
bestOffer := defaultOffer
bestQ := -1.0
specs := header.ParseAccept(r.Header, "Accept-Language")
for _, offer := range offers {
for _, spec := range specs {
if spec.Q > bestQ && (spec.Value == "*" || spec.Value == offer) {
bestQ = spec.Q
bestOffer = offer
}
}
}
if bestQ == 0 {
bestOffer = defaultOffer
}
return bestOffer
} | go | {
"resource": ""
} |
q14304 | ReadFormData | train | func ReadFormData(form map[string][]string, data interface{}) error {
rv := reflect.ValueOf(data)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.New("data must be a pointer")
}
rv = indirect(rv)
if rv.Kind() != reflect.Struct {
return errors.New("data must be a pointer to a struct")
}
return readForm(form, "", rv)
} | go | {
"resource": ""
} |
q14305 | DefaultJWTTokenHandler | train | func DefaultJWTTokenHandler(c *routing.Context, token *jwt.Token) error {
c.Set("JWT", token)
return nil
} | go | {
"resource": ""
} |
q14306 | NewJWT | train | func NewJWT(claims jwt.MapClaims, signingKey string, signingMethod ...jwt.SigningMethod) (string, error) {
var sm jwt.SigningMethod = jwt.SigningMethodHS256
if len(signingMethod) > 0 {
sm = signingMethod[0]
}
return jwt.NewWithClaims(sm, claims).SignedString([]byte(signingKey))
} | go | {
"resource": ""
} |
q14307 | New | train | func New() *Router {
r := &Router{
namedRoutes: make(map[string]*Route),
stores: make(map[string]routeStore),
}
r.RouteGroup = *newRouteGroup("", r, make([]Handler, 0))
r.NotFound(MethodNotAllowedHandler, NotFoundHandler)
r.pool.New = func() interface{} {
return &Context{
pvalues: make([]string, r.maxParams),
router: r,
}
}
return r
} | go | {
"resource": ""
} |
q14308 | ServeHTTP | train | func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
c := r.pool.Get().(*Context)
c.init(res, req)
if r.UseEscapedPath {
c.handlers, c.pnames = r.find(req.Method, r.normalizeRequestPath(req.URL.EscapedPath()), c.pvalues)
for i, v := range c.pvalues {
c.pvalues[i], _ = url.QueryUnescape(v)
}
} else {
c.handlers, c.pnames = r.find(req.Method, r.normalizeRequestPath(req.URL.Path), c.pvalues)
}
if err := c.Next(); err != nil {
r.handleError(c, err)
}
r.pool.Put(c)
} | go | {
"resource": ""
} |
q14309 | Use | train | func (r *Router) Use(handlers ...Handler) {
r.RouteGroup.Use(handlers...)
r.notFoundHandlers = combineHandlers(r.handlers, r.notFound)
} | go | {
"resource": ""
} |
q14310 | NotFound | train | func (r *Router) NotFound(handlers ...Handler) {
r.notFound = handlers
r.notFoundHandlers = combineHandlers(r.handlers, r.notFound)
} | go | {
"resource": ""
} |
q14311 | Find | train | func (r *Router) Find(method, path string) (handlers []Handler, params map[string]string) {
pvalues := make([]string, r.maxParams)
handlers, pnames := r.find(method, path, pvalues)
params = make(map[string]string, len(pnames))
for i, n := range pnames {
params[n] = pvalues[i]
}
return handlers, params
} | go | {
"resource": ""
} |
q14312 | HTTPHandlerFunc | train | func HTTPHandlerFunc(h http.HandlerFunc) Handler {
return func(c *Context) error {
h(c.Response, c.Request)
return nil
}
} | go | {
"resource": ""
} |
q14313 | newStore | train | func newStore() *store {
return &store{
root: &node{
static: true,
children: make([]*node, 256),
pchildren: make([]*node, 0),
pindex: -1,
pnames: []string{},
},
}
} | go | {
"resource": ""
} |
q14314 | Add | train | func (s *store) Add(key string, data interface{}) int {
s.count++
return s.root.add(key, data, s.count)
} | go | {
"resource": ""
} |
q14315 | Get | train | func (s *store) Get(path string, pvalues []string) (data interface{}, pnames []string) {
data, pnames, _ = s.root.get(path, pvalues)
return
} | go | {
"resource": ""
} |
q14316 | add | train | func (n *node) add(key string, data interface{}, order int) int {
matched := 0
// find the common prefix
for ; matched < len(key) && matched < len(n.key); matched++ {
if key[matched] != n.key[matched] {
break
}
}
if matched == len(n.key) {
if matched == len(key) {
// the node key is the same as the key: make the current node as data node
// if the node is already a data node, ignore the new data since we only care the first matched node
if n.data == nil {
n.data = data
n.order = order
}
return n.pindex + 1
}
// the node key is a prefix of the key: create a child node
newKey := key[matched:]
// try adding to a static child
if child := n.children[newKey[0]]; child != nil {
if pn := child.add(newKey, data, order); pn >= 0 {
return pn
}
}
// try adding to a param child
for _, child := range n.pchildren {
if pn := child.add(newKey, data, order); pn >= 0 {
return pn
}
}
return n.addChild(newKey, data, order)
}
if matched == 0 || !n.static {
// no common prefix, or partial common prefix with a non-static node: should skip this node
return -1
}
// the node key shares a partial prefix with the key: split the node key
n1 := &node{
static: true,
key: n.key[matched:],
data: n.data,
order: n.order,
minOrder: n.minOrder,
pchildren: n.pchildren,
children: n.children,
pindex: n.pindex,
pnames: n.pnames,
}
n.key = key[0:matched]
n.data = nil
n.pchildren = make([]*node, 0)
n.children = make([]*node, 256)
n.children[n1.key[0]] = n1
return n.add(key, data, order)
} | go | {
"resource": ""
} |
q14317 | addChild | train | func (n *node) addChild(key string, data interface{}, order int) int {
// find the first occurrence of a param token
p0, p1 := -1, -1
for i := 0; i < len(key); i++ {
if p0 < 0 && key[i] == '<' {
p0 = i
}
if p0 >= 0 && key[i] == '>' {
p1 = i
break
}
}
if p0 > 0 && p1 > 0 || p1 < 0 {
// param token occurs after a static string, or no param token: create a static node
child := &node{
static: true,
key: key,
minOrder: order,
children: make([]*node, 256),
pchildren: make([]*node, 0),
pindex: n.pindex,
pnames: n.pnames,
}
n.children[key[0]] = child
if p1 > 0 {
// param token occurs after a static string
child.key = key[:p0]
n = child
} else {
// no param token: done adding the child
child.data = data
child.order = order
return child.pindex + 1
}
}
// add param node
child := &node{
static: false,
key: key[p0 : p1+1],
minOrder: order,
children: make([]*node, 256),
pchildren: make([]*node, 0),
pindex: n.pindex,
pnames: n.pnames,
}
pattern := ""
pname := key[p0+1 : p1]
for i := p0 + 1; i < p1; i++ {
if key[i] == ':' {
pname = key[p0+1 : i]
pattern = key[i+1 : p1]
break
}
}
if pattern != "" {
// the param token contains a regular expression
child.regex = regexp.MustCompile("^" + pattern)
}
pnames := make([]string, len(n.pnames)+1)
copy(pnames, n.pnames)
pnames[len(n.pnames)] = pname
child.pnames = pnames
child.pindex = len(pnames) - 1
n.pchildren = append(n.pchildren, child)
if p1 == len(key)-1 {
// the param token is at the end of the key
child.data = data
child.order = order
return child.pindex + 1
}
// process the rest of the key
return child.addChild(key[p1+1:], data, order)
} | go | {
"resource": ""
} |
q14318 | get | train | func (n *node) get(key string, pvalues []string) (data interface{}, pnames []string, order int) {
order = math.MaxInt32
repeat:
if n.static {
// check if the node key is a prefix of the given key
// a slightly optimized version of strings.HasPrefix
nkl := len(n.key)
if nkl > len(key) {
return
}
for i := nkl - 1; i >= 0; i-- {
if n.key[i] != key[i] {
return
}
}
key = key[nkl:]
} else if n.regex != nil {
// param node with regular expression
if n.regex.String() == "^.*" {
pvalues[n.pindex] = key
key = ""
} else if match := n.regex.FindStringIndex(key); match != nil {
pvalues[n.pindex] = key[0:match[1]]
key = key[match[1]:]
} else {
return
}
} else {
// param node matching non-"/" characters
i, kl := 0, len(key)
for ; i < kl; i++ {
if key[i] == '/' {
pvalues[n.pindex] = key[0:i]
key = key[i:]
break
}
}
if i == kl {
pvalues[n.pindex] = key
key = ""
}
}
if len(key) > 0 {
// find a static child that can match the rest of the key
if child := n.children[key[0]]; child != nil {
if len(n.pchildren) == 0 {
// use goto to avoid recursion when no param children
n = child
goto repeat
}
data, pnames, order = child.get(key, pvalues)
}
} else if n.data != nil {
// do not return yet: a param node may match an empty string with smaller order
data, pnames, order = n.data, n.pnames, n.order
}
// try matching param children
tvalues := pvalues
allocated := false
for _, child := range n.pchildren {
if child.minOrder >= order {
continue
}
if data != nil && !allocated {
tvalues = make([]string, len(pvalues))
allocated = true
}
if d, p, s := child.get(key, tvalues); d != nil && s < order {
if allocated {
for i := child.pindex; i < len(p); i++ {
pvalues[i] = tvalues[i]
}
}
data, pnames, order = d, p, s
}
}
return
} | go | {
"resource": ""
} |
q14319 | safeSet | train | func (b *BitSet) safeSet() []uint64 {
if b.set == nil {
b.set = make([]uint64, wordsNeeded(0))
}
return b.set
} | go | {
"resource": ""
} |
q14320 | wordsNeeded | train | func wordsNeeded(i uint) int {
if i > (Cap() - wordSize + 1) {
return int(Cap() >> log2WordSize)
}
return int((i + (wordSize - 1)) >> log2WordSize)
} | go | {
"resource": ""
} |
q14321 | New | train | func New(length uint) (bset *BitSet) {
defer func() {
if r := recover(); r != nil {
bset = &BitSet{
0,
make([]uint64, 0),
}
}
}()
bset = &BitSet{
length,
make([]uint64, wordsNeeded(length)),
}
return bset
} | go | {
"resource": ""
} |
q14322 | extendSetMaybe | train | func (b *BitSet) extendSetMaybe(i uint) {
if i >= b.length { // if we need more bits, make 'em
nsize := wordsNeeded(i + 1)
if b.set == nil {
b.set = make([]uint64, nsize)
} else if cap(b.set) >= nsize {
b.set = b.set[:nsize] // fast resize
} else if len(b.set) < nsize {
newset := make([]uint64, nsize, 2*nsize) // increase capacity 2x
copy(newset, b.set)
b.set = newset
}
b.length = i + 1
}
} | go | {
"resource": ""
} |
q14323 | Set | train | func (b *BitSet) Set(i uint) *BitSet {
b.extendSetMaybe(i)
b.set[i>>log2WordSize] |= 1 << (i & (wordSize - 1))
return b
} | go | {
"resource": ""
} |
q14324 | Clear | train | func (b *BitSet) Clear(i uint) *BitSet {
if i >= b.length {
return b
}
b.set[i>>log2WordSize] &^= 1 << (i & (wordSize - 1))
return b
} | go | {
"resource": ""
} |
q14325 | SetTo | train | func (b *BitSet) SetTo(i uint, value bool) *BitSet {
if value {
return b.Set(i)
}
return b.Clear(i)
} | go | {
"resource": ""
} |
q14326 | Flip | train | func (b *BitSet) Flip(i uint) *BitSet {
if i >= b.length {
return b.Set(i)
}
b.set[i>>log2WordSize] ^= 1 << (i & (wordSize - 1))
return b
} | go | {
"resource": ""
} |
q14327 | Shrink | train | func (b *BitSet) Shrink(length uint) *BitSet {
idx := wordsNeeded(length + 1)
if idx > len(b.set) {
return b
}
shrunk := make([]uint64, idx)
copy(shrunk, b.set[:idx])
b.set = shrunk
b.length = length + 1
b.set[idx-1] &= (allBits >> (uint64(64) - uint64(length&(wordSize-1)) - 1))
return b
} | go | {
"resource": ""
} |
q14328 | InsertAt | train | func (b *BitSet) InsertAt(idx uint) *BitSet {
insertAtElement := (idx >> log2WordSize)
// if length of set is a multiple of wordSize we need to allocate more space first
if b.isLenExactMultiple() {
b.set = append(b.set, uint64(0))
}
var i uint
for i = uint(len(b.set) - 1); i > insertAtElement; i-- {
// all elements above the position where we want to insert can simply by shifted
b.set[i] <<= 1
// we take the most significant bit of the previous element and set it as
// the least significant bit of the current element
b.set[i] |= (b.set[i-1] & 0x8000000000000000) >> 63
}
// generate a mask to extract the data that we need to shift left
// within the element where we insert a bit
dataMask := ^(uint64(1)<<uint64(idx&(wordSize-1)) - 1)
// extract that data that we'll shift
data := b.set[i] & dataMask
// set the positions of the data mask to 0 in the element where we insert
b.set[i] &= ^dataMask
// shift data mask to the left and insert its data to the slice element
b.set[i] |= data << 1
// add 1 to length of BitSet
b.length++
return b
} | go | {
"resource": ""
} |
q14329 | ClearAll | train | func (b *BitSet) ClearAll() *BitSet {
if b != nil && b.set != nil {
for i := range b.set {
b.set[i] = 0
}
}
return b
} | go | {
"resource": ""
} |
q14330 | Clone | train | func (b *BitSet) Clone() *BitSet {
c := New(b.length)
if b.set != nil { // Clone should not modify current object
copy(c.set, b.set)
}
return c
} | go | {
"resource": ""
} |
q14331 | Copy | train | func (b *BitSet) Copy(c *BitSet) (count uint) {
if c == nil {
return
}
if b.set != nil { // Copy should not modify current object
copy(c.set, b.set)
}
count = c.length
if b.length < c.length {
count = b.length
}
return
} | go | {
"resource": ""
} |
q14332 | Equal | train | func (b *BitSet) Equal(c *BitSet) bool {
if c == nil {
return false
}
if b.length != c.length {
return false
}
if b.length == 0 { // if they have both length == 0, then could have nil set
return true
}
// testing for equality shoud not transform the bitset (no call to safeSet)
for p, v := range b.set {
if c.set[p] != v {
return false
}
}
return true
} | go | {
"resource": ""
} |
q14333 | DifferenceCardinality | train | func (b *BitSet) DifferenceCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
l := int(compare.wordCount())
if l > int(b.wordCount()) {
l = int(b.wordCount())
}
cnt := uint64(0)
cnt += popcntMaskSlice(b.set[:l], compare.set[:l])
cnt += popcntSlice(b.set[l:])
return uint(cnt)
} | go | {
"resource": ""
} |
q14334 | IntersectionCardinality | train | func (b *BitSet) IntersectionCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
b, compare = sortByLength(b, compare)
cnt := popcntAndSlice(b.set, compare.set)
return uint(cnt)
} | go | {
"resource": ""
} |
q14335 | UnionCardinality | train | func (b *BitSet) UnionCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
b, compare = sortByLength(b, compare)
cnt := popcntOrSlice(b.set, compare.set)
if len(compare.set) > len(b.set) {
cnt += popcntSlice(compare.set[len(b.set):])
}
return uint(cnt)
} | go | {
"resource": ""
} |
q14336 | SymmetricDifferenceCardinality | train | func (b *BitSet) SymmetricDifferenceCardinality(compare *BitSet) uint {
panicIfNull(b)
panicIfNull(compare)
b, compare = sortByLength(b, compare)
cnt := popcntXorSlice(b.set, compare.set)
if len(compare.set) > len(b.set) {
cnt += popcntSlice(compare.set[len(b.set):])
}
return uint(cnt)
} | go | {
"resource": ""
} |
q14337 | cleanLastWord | train | func (b *BitSet) cleanLastWord() {
if !b.isLenExactMultiple() {
b.set[len(b.set)-1] &= allBits >> (wordSize - b.length%wordSize)
}
} | go | {
"resource": ""
} |
q14338 | All | train | func (b *BitSet) All() bool {
panicIfNull(b)
return b.Count() == b.length
} | go | {
"resource": ""
} |
q14339 | None | train | func (b *BitSet) None() bool {
panicIfNull(b)
if b != nil && b.set != nil {
for _, word := range b.set {
if word > 0 {
return false
}
}
return true
}
return true
} | go | {
"resource": ""
} |
q14340 | IsSuperSet | train | func (b *BitSet) IsSuperSet(other *BitSet) bool {
for i, e := other.NextSet(0); e; i, e = other.NextSet(i + 1) {
if !b.Test(i) {
return false
}
}
return true
} | go | {
"resource": ""
} |
q14341 | IsStrictSuperSet | train | func (b *BitSet) IsStrictSuperSet(other *BitSet) bool {
return b.Count() > other.Count() && b.IsSuperSet(other)
} | go | {
"resource": ""
} |
q14342 | DumpAsBits | train | func (b *BitSet) DumpAsBits() string {
if b.set == nil {
return "."
}
buffer := bytes.NewBufferString("")
i := len(b.set) - 1
for ; i >= 0; i-- {
fmt.Fprintf(buffer, "%064b.", b.set[i])
}
return buffer.String()
} | go | {
"resource": ""
} |
q14343 | BinaryStorageSize | train | func (b *BitSet) BinaryStorageSize() int {
return binary.Size(uint64(0)) + binary.Size(b.set)
} | go | {
"resource": ""
} |
q14344 | WriteTo | train | func (b *BitSet) WriteTo(stream io.Writer) (int64, error) {
length := uint64(b.length)
// Write length
err := binary.Write(stream, binaryOrder, length)
if err != nil {
return 0, err
}
// Write set
err = binary.Write(stream, binaryOrder, b.set)
return int64(b.BinaryStorageSize()), err
} | go | {
"resource": ""
} |
q14345 | ReadFrom | train | func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) {
var length uint64
// Read length first
err := binary.Read(stream, binaryOrder, &length)
if err != nil {
return 0, err
}
newset := New(uint(length))
if uint64(newset.length) != length {
return 0, errors.New("Unmarshalling error: type mismatch")
}
// Read remaining bytes as set
err = binary.Read(stream, binaryOrder, newset.set)
if err != nil {
return 0, err
}
*b = *newset
return int64(b.BinaryStorageSize()), nil
} | go | {
"resource": ""
} |
q14346 | MarshalBinary | train | func (b *BitSet) MarshalBinary() ([]byte, error) {
var buf bytes.Buffer
writer := bufio.NewWriter(&buf)
_, err := b.WriteTo(writer)
if err != nil {
return []byte{}, err
}
err = writer.Flush()
return buf.Bytes(), err
} | go | {
"resource": ""
} |
q14347 | UnmarshalBinary | train | func (b *BitSet) UnmarshalBinary(data []byte) error {
buf := bytes.NewReader(data)
reader := bufio.NewReader(buf)
_, err := b.ReadFrom(reader)
return err
} | go | {
"resource": ""
} |
q14348 | MarshalJSON | train | func (b *BitSet) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize()))
_, err := b.WriteTo(buffer)
if err != nil {
return nil, err
}
// URLEncode all bytes
return json.Marshal(base64Encoding.EncodeToString(buffer.Bytes()))
} | go | {
"resource": ""
} |
q14349 | UnmarshalJSON | train | func (b *BitSet) UnmarshalJSON(data []byte) error {
// Unmarshal as string
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
// URLDecode string
buf, err := base64Encoding.DecodeString(s)
if err != nil {
return err
}
_, err = b.ReadFrom(bytes.NewReader(buf))
return err
} | go | {
"resource": ""
} |
q14350 | Get | train | func (p *Pool) Get() *ByteBuffer {
v := p.pool.Get()
if v != nil {
return v.(*ByteBuffer)
}
return &ByteBuffer{
B: make([]byte, 0, atomic.LoadUint64(&p.defaultSize)),
}
} | go | {
"resource": ""
} |
q14351 | Put | train | func (p *Pool) Put(b *ByteBuffer) {
idx := index(len(b.B))
if atomic.AddUint64(&p.calls[idx], 1) > calibrateCallsThreshold {
p.calibrate()
}
maxSize := int(atomic.LoadUint64(&p.maxSize))
if maxSize == 0 || cap(b.B) <= maxSize {
b.Reset()
p.pool.Put(b)
}
} | go | {
"resource": ""
} |
q14352 | ReadFrom | train | func (b *ByteBuffer) ReadFrom(r io.Reader) (int64, error) {
p := b.B
nStart := int64(len(p))
nMax := int64(cap(p))
n := nStart
if nMax == 0 {
nMax = 64
p = make([]byte, nMax)
} else {
p = p[:nMax]
}
for {
if n == nMax {
nMax *= 2
bNew := make([]byte, nMax)
copy(bNew, p)
p = bNew
}
nn, err := r.Read(p[n:])
n += int64(nn)
if err != nil {
b.B = p[:n]
n -= nStart
if err == io.EOF {
return n, nil
}
return n, err
}
}
} | go | {
"resource": ""
} |
q14353 | WriteTo | train | func (b *ByteBuffer) WriteTo(w io.Writer) (int64, error) {
n, err := w.Write(b.B)
return int64(n), err
} | go | {
"resource": ""
} |
q14354 | Write | train | func (b *ByteBuffer) Write(p []byte) (int, error) {
b.B = append(b.B, p...)
return len(p), nil
} | go | {
"resource": ""
} |
q14355 | WriteByte | train | func (b *ByteBuffer) WriteByte(c byte) error {
b.B = append(b.B, c)
return nil
} | go | {
"resource": ""
} |
q14356 | WriteString | train | func (b *ByteBuffer) WriteString(s string) (int, error) {
b.B = append(b.B, s...)
return len(s), nil
} | go | {
"resource": ""
} |
q14357 | Set | train | func (b *ByteBuffer) Set(p []byte) {
b.B = append(b.B[:0], p...)
} | go | {
"resource": ""
} |
q14358 | SetString | train | func (b *ByteBuffer) SetString(s string) {
b.B = append(b.B[:0], s...)
} | go | {
"resource": ""
} |
q14359 | Print | train | func Print(a ...interface{}) (int, error) {
return fmt.Print(compile(fmt.Sprint(a...)))
} | go | {
"resource": ""
} |
q14360 | Println | train | func Println(a ...interface{}) (int, error) {
return fmt.Println(compile(fmt.Sprint(a...)))
} | go | {
"resource": ""
} |
q14361 | Fprint | train | func Fprint(w io.Writer, a ...interface{}) (int, error) {
return fmt.Fprint(w, compile(fmt.Sprint(a...)))
} | go | {
"resource": ""
} |
q14362 | Fprintf | train | func Fprintf(w io.Writer, format string, a ...interface{}) (int, error) {
return fmt.Fprint(w, compile(fmt.Sprintf(format, a...)))
} | go | {
"resource": ""
} |
q14363 | Sprintf | train | func Sprintf(format string, a ...interface{}) string {
return compile(fmt.Sprintf(format, a...))
} | go | {
"resource": ""
} |
q14364 | Errorf | train | func Errorf(format string, a ...interface{}) error {
return errors.New(compile(Sprintf(format, a...)))
} | go | {
"resource": ""
} |
q14365 | InitConfigLinuxResourcesCPU | train | func (g *Generator) InitConfigLinuxResourcesCPU() {
g.initConfigLinuxResources()
if g.Config.Linux.Resources.CPU == nil {
g.Config.Linux.Resources.CPU = &rspec.LinuxCPU{}
}
} | go | {
"resource": ""
} |
q14366 | GetPidsData | train | func (cg *CgroupV1) GetPidsData(pid int, cgPath string) (*rspec.LinuxPids, error) {
if filepath.IsAbs(cgPath) {
path := filepath.Join(cg.MountPath, "pids", cgPath)
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return nil, specerror.NewError(specerror.CgroupsAbsPathRelToMount, fmt.Errorf("In the case of an absolute path, the runtime MUST take the path to be relative to the cgroups mount point"), rspec.Version)
}
return nil, err
}
}
lp := &rspec.LinuxPids{}
fileName := strings.Join([]string{"pids", "max"}, ".")
filePath := filepath.Join(cg.MountPath, "pids", cgPath, fileName)
if !filepath.IsAbs(cgPath) {
subPath, err := GetSubsystemPath(pid, "pids")
if err != nil {
return nil, err
}
if !strings.Contains(subPath, cgPath) {
return nil, fmt.Errorf("cgroup subsystem %s is not mounted as expected", "pids")
}
filePath = filepath.Join(cg.MountPath, "pids", subPath, fileName)
}
contents, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
res, err := strconv.ParseInt(strings.TrimSpace(string(contents)), 10, 64)
if err != nil {
if os.IsNotExist(err) {
return nil, specerror.NewError(specerror.CgroupsPathAttach, fmt.Errorf("The runtime MUST consistently attach to the same place in the cgroups hierarchy given the same value of `cgroupsPath`"), rspec.Version)
}
return nil, err
}
lp.Limit = res
return lp, nil
} | go | {
"resource": ""
} |
q14367 | decideCourseOfAction | train | func decideCourseOfAction(newSyscall *rspec.LinuxSyscall, syscalls []rspec.LinuxSyscall) (string, error) {
ruleForSyscallAlreadyExists := false
var sliceOfDeterminedActions []string
for i, syscall := range syscalls {
if sameName(&syscall, newSyscall) {
ruleForSyscallAlreadyExists = true
if identical(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, nothing)
}
if sameAction(newSyscall, &syscall) {
if bothHaveArgs(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend)
}
if onlyOneHasArgs(newSyscall, &syscall) {
if firstParamOnlyHasArgs(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i))
} else {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, nothing)
}
}
}
if !sameAction(newSyscall, &syscall) {
if bothHaveArgs(newSyscall, &syscall) {
if sameArgs(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i))
}
if !sameArgs(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend)
}
}
if onlyOneHasArgs(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend)
}
if neitherHasArgs(newSyscall, &syscall) {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i))
}
}
}
}
if !ruleForSyscallAlreadyExists {
sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend)
}
// Nothing has highest priority
for _, determinedAction := range sliceOfDeterminedActions {
if determinedAction == nothing {
return determinedAction, nil
}
}
// Overwrite has second highest priority
for _, determinedAction := range sliceOfDeterminedActions {
if strings.Contains(determinedAction, seccompOverwrite) {
return determinedAction, nil
}
}
// Append has the lowest priority
for _, determinedAction := range sliceOfDeterminedActions {
if determinedAction == seccompAppend {
return determinedAction, nil
}
}
return "", fmt.Errorf("Trouble determining action: %s", sliceOfDeterminedActions)
} | go | {
"resource": ""
} |
q14368 | GetPidsData | train | func GetPidsData(pid int, cgPath string) (*rspec.LinuxPids, error) {
return nil, fmt.Errorf("unimplemented yet")
} | go | {
"resource": ""
} |
q14369 | LastCap | train | func LastCap() capability.Cap {
last := capability.CAP_LAST_CAP
// hack for RHEL6 which has no /proc/sys/kernel/cap_last_cap
if last == capability.Cap(63) {
last = capability.CAP_BLOCK_SUSPEND
}
return last
} | go | {
"resource": ""
} |
q14370 | RemoveAllSeccompRules | train | func RemoveAllSeccompRules(config *rspec.LinuxSeccomp) error {
if config == nil {
return fmt.Errorf("Cannot remove action from nil Seccomp pointer")
}
newSyscallSlice := []rspec.LinuxSyscall{}
config.Syscalls = newSyscallSlice
return nil
} | go | {
"resource": ""
} |
q14371 | RemoveAllMatchingRules | train | func RemoveAllMatchingRules(config *rspec.LinuxSeccomp, seccompAction rspec.LinuxSeccompAction) error {
if config == nil {
return fmt.Errorf("Cannot remove action from nil Seccomp pointer")
}
for _, syscall := range config.Syscalls {
if reflect.DeepEqual(syscall.Action, seccompAction) {
RemoveAction(strings.Join(syscall.Names, ","), config)
}
}
return nil
} | go | {
"resource": ""
} |
q14372 | FindCgroup | train | func FindCgroup() (Cgroup, error) {
f, err := os.Open("/proc/self/mountinfo")
if err != nil {
return nil, err
}
defer f.Close()
cgroupv2 := false
scanner := bufio.NewScanner(f)
for scanner.Scan() {
text := scanner.Text()
fields := strings.Split(text, " ")
// Safe as mountinfo encodes mountpoints with spaces as \040.
index := strings.Index(text, " - ")
postSeparatorFields := strings.Split(text[index+3:], " ")
numPostFields := len(postSeparatorFields)
// This is an error as we can't detect if the mount is for "cgroup"
if numPostFields == 0 {
return nil, fmt.Errorf("Found no fields post '-' in %q", text)
}
if postSeparatorFields[0] == "cgroup" {
// No need to parse the rest of the postSeparatorFields
cg := &CgroupV1{
MountPath: filepath.Dir(fields[4]),
}
return cg, nil
} else if postSeparatorFields[0] == "cgroup2" {
cgroupv2 = true
continue
//TODO cgroupv2 unimplemented
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
if cgroupv2 {
return nil, fmt.Errorf("cgroupv2 is not supported yet")
}
return nil, fmt.Errorf("cgroup is not found")
} | go | {
"resource": ""
} |
q14373 | GetSubsystemPath | train | func GetSubsystemPath(pid int, subsystem string) (string, error) {
contents, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
if err != nil {
return "", err
}
parts := strings.Split(strings.TrimSpace(string(contents)), "\n")
for _, part := range parts {
elem := strings.SplitN(part, ":", 3)
if len(elem) < 3 {
continue
}
subelems := strings.Split(elem[1], ",")
for _, subelem := range subelems {
if subelem == subsystem {
return elem[2], nil
}
}
}
return "", fmt.Errorf("subsystem %s not found", subsystem)
} | go | {
"resource": ""
} |
q14374 | NewFromFile | train | func NewFromFile(path string) (Generator, error) {
cf, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return Generator{}, fmt.Errorf("template configuration at %s not found", path)
}
return Generator{}, err
}
defer cf.Close()
return NewFromTemplate(cf)
} | go | {
"resource": ""
} |
q14375 | NewFromTemplate | train | func NewFromTemplate(r io.Reader) (Generator, error) {
var config rspec.Spec
if err := json.NewDecoder(r).Decode(&config); err != nil {
return Generator{}, err
}
envCache := map[string]int{}
if config.Process != nil {
envCache = createEnvCacheMap(config.Process.Env)
}
return Generator{
Config: &config,
envMap: envCache,
}, nil
} | go | {
"resource": ""
} |
q14376 | createEnvCacheMap | train | func createEnvCacheMap(env []string) map[string]int {
envMap := make(map[string]int, len(env))
for i, val := range env {
envMap[val] = i
}
return envMap
} | go | {
"resource": ""
} |
q14377 | Save | train | func (g *Generator) Save(w io.Writer, exportOpts ExportOptions) (err error) {
var data []byte
if g.Config.Linux != nil {
buf, err := json.Marshal(g.Config.Linux)
if err != nil {
return err
}
if string(buf) == "{}" {
g.Config.Linux = nil
}
}
if exportOpts.Seccomp {
data, err = json.MarshalIndent(g.Config.Linux.Seccomp, "", "\t")
} else {
data, err = json.MarshalIndent(g.Config, "", "\t")
}
if err != nil {
return err
}
_, err = w.Write(data)
if err != nil {
return err
}
return nil
} | go | {
"resource": ""
} |
q14378 | SaveToFile | train | func (g *Generator) SaveToFile(path string, exportOpts ExportOptions) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
return g.Save(f, exportOpts)
} | go | {
"resource": ""
} |
q14379 | SetVersion | train | func (g *Generator) SetVersion(version string) {
g.initConfig()
g.Config.Version = version
} | go | {
"resource": ""
} |
q14380 | SetRootPath | train | func (g *Generator) SetRootPath(path string) {
g.initConfigRoot()
g.Config.Root.Path = path
} | go | {
"resource": ""
} |
q14381 | SetRootReadonly | train | func (g *Generator) SetRootReadonly(b bool) {
g.initConfigRoot()
g.Config.Root.Readonly = b
} | go | {
"resource": ""
} |
q14382 | SetHostname | train | func (g *Generator) SetHostname(s string) {
g.initConfig()
g.Config.Hostname = s
} | go | {
"resource": ""
} |
q14383 | SetOCIVersion | train | func (g *Generator) SetOCIVersion(s string) {
g.initConfig()
g.Config.Version = s
} | go | {
"resource": ""
} |
q14384 | ClearAnnotations | train | func (g *Generator) ClearAnnotations() {
if g.Config == nil {
return
}
g.Config.Annotations = make(map[string]string)
} | go | {
"resource": ""
} |
q14385 | AddAnnotation | train | func (g *Generator) AddAnnotation(key, value string) {
g.initConfigAnnotations()
g.Config.Annotations[key] = value
} | go | {
"resource": ""
} |
q14386 | RemoveAnnotation | train | func (g *Generator) RemoveAnnotation(key string) {
if g.Config == nil || g.Config.Annotations == nil {
return
}
delete(g.Config.Annotations, key)
} | go | {
"resource": ""
} |
q14387 | SetProcessConsoleSize | train | func (g *Generator) SetProcessConsoleSize(width, height uint) {
g.initConfigProcessConsoleSize()
g.Config.Process.ConsoleSize.Width = width
g.Config.Process.ConsoleSize.Height = height
} | go | {
"resource": ""
} |
q14388 | SetProcessUID | train | func (g *Generator) SetProcessUID(uid uint32) {
g.initConfigProcess()
g.Config.Process.User.UID = uid
} | go | {
"resource": ""
} |
q14389 | SetProcessUsername | train | func (g *Generator) SetProcessUsername(username string) {
g.initConfigProcess()
g.Config.Process.User.Username = username
} | go | {
"resource": ""
} |
q14390 | SetProcessGID | train | func (g *Generator) SetProcessGID(gid uint32) {
g.initConfigProcess()
g.Config.Process.User.GID = gid
} | go | {
"resource": ""
} |
q14391 | SetProcessCwd | train | func (g *Generator) SetProcessCwd(cwd string) {
g.initConfigProcess()
g.Config.Process.Cwd = cwd
} | go | {
"resource": ""
} |
q14392 | SetProcessNoNewPrivileges | train | func (g *Generator) SetProcessNoNewPrivileges(b bool) {
g.initConfigProcess()
g.Config.Process.NoNewPrivileges = b
} | go | {
"resource": ""
} |
q14393 | SetProcessTerminal | train | func (g *Generator) SetProcessTerminal(b bool) {
g.initConfigProcess()
g.Config.Process.Terminal = b
} | go | {
"resource": ""
} |
q14394 | SetProcessApparmorProfile | train | func (g *Generator) SetProcessApparmorProfile(prof string) {
g.initConfigProcess()
g.Config.Process.ApparmorProfile = prof
} | go | {
"resource": ""
} |
q14395 | SetProcessArgs | train | func (g *Generator) SetProcessArgs(args []string) {
g.initConfigProcess()
g.Config.Process.Args = args
} | go | {
"resource": ""
} |
q14396 | ClearProcessEnv | train | func (g *Generator) ClearProcessEnv() {
if g.Config == nil || g.Config.Process == nil {
return
}
g.Config.Process.Env = []string{}
// Clear out the env cache map as well
g.envMap = map[string]int{}
} | go | {
"resource": ""
} |
q14397 | AddProcessEnv | train | func (g *Generator) AddProcessEnv(name, value string) {
if name == "" {
return
}
g.initConfigProcess()
g.addEnv(fmt.Sprintf("%s=%s", name, value), name)
} | go | {
"resource": ""
} |
q14398 | AddMultipleProcessEnv | train | func (g *Generator) AddMultipleProcessEnv(envs []string) {
g.initConfigProcess()
for _, val := range envs {
split := strings.SplitN(val, "=", 2)
g.addEnv(val, split[0])
}
} | go | {
"resource": ""
} |
q14399 | addEnv | train | func (g *Generator) addEnv(env, key string) {
if idx, ok := g.envMap[key]; ok {
// The ENV exists in the cache, so change its value in g.Config.Process.Env
g.Config.Process.Env[idx] = env
} else {
// else the env doesn't exist, so add it and add it's index to g.envMap
g.Config.Process.Env = append(g.Config.Process.Env, env)
g.envMap[key] = len(g.Config.Process.Env) - 1
}
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.