_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q12700
RunIteration
train
func RunIteration() { runtime.LockOSThread() defer runtime.UnlockOSThread() select { case drawEvent <- struct{}{}: for { select { case <-worker.WorkAvailable(): worker.DoWork() case <-drawDone: return } } case <-time.After(500 * time.Millisecond): return } }
go
{ "resource": "" }
q12701
mobileDraw
train
func mobileDraw(defaultScene Scene) { if !initalized { var ctx mgl.Context ctx, worker = mgl.NewContext() Gl = gl.NewContext(ctx) } <-drawEvent defer func() { drawDone <- struct{}{} }() if !initalized { RunPreparation(defaultScene) ticker = time.NewTicker(time.Duration(int(time.Second) / opts.FPSLimi...
go
{ "resource": "" }
q12702
NewAnimationComponent
train
func NewAnimationComponent(drawables []Drawable, rate float32) AnimationComponent { return AnimationComponent{ Animations: make(map[string]*Animation), Drawables: drawables, Rate: rate, } }
go
{ "resource": "" }
q12703
SelectAnimationByName
train
func (ac *AnimationComponent) SelectAnimationByName(name string) { ac.CurrentAnimation = ac.Animations[name] ac.index = 0 }
go
{ "resource": "" }
q12704
SelectAnimationByAction
train
func (ac *AnimationComponent) SelectAnimationByAction(action *Animation) { ac.CurrentAnimation = action ac.index = 0 }
go
{ "resource": "" }
q12705
AddDefaultAnimation
train
func (ac *AnimationComponent) AddDefaultAnimation(action *Animation) { ac.AddAnimation(action) ac.def = action }
go
{ "resource": "" }
q12706
AddAnimation
train
func (ac *AnimationComponent) AddAnimation(action *Animation) { ac.Animations[action.Name] = action }
go
{ "resource": "" }
q12707
AddAnimations
train
func (ac *AnimationComponent) AddAnimations(actions []*Animation) { for _, action := range actions { ac.AddAnimation(action) } }
go
{ "resource": "" }
q12708
Cell
train
func (ac *AnimationComponent) Cell() Drawable { if len(ac.CurrentAnimation.Frames) == 0 { log.Println("No frame data for this animation. Selecting zeroth drawable. If this is incorrect, add an action to the animation.") return ac.Drawables[0] } idx := ac.CurrentAnimation.Frames[ac.index] return ac.Drawables[id...
go
{ "resource": "" }
q12709
NextFrame
train
func (ac *AnimationComponent) NextFrame() { if len(ac.CurrentAnimation.Frames) == 0 { log.Println("No frame data for this animation") return } ac.index++ ac.change = 0 if ac.index >= len(ac.CurrentAnimation.Frames) { ac.index = 0 if !ac.CurrentAnimation.Loop { ac.CurrentAnimation = nil return } ...
go
{ "resource": "" }
q12710
Add
train
func (a *AnimationSystem) Add(basic *ecs.BasicEntity, anim *AnimationComponent, render *RenderComponent) { if a.entities == nil { a.entities = make(map[uint64]animationEntity) } a.entities[basic.ID()] = animationEntity{anim, render} }
go
{ "resource": "" }
q12711
AddByInterface
train
func (a *AnimationSystem) AddByInterface(i ecs.Identifier) { o, _ := i.(Animationable) a.Add(o.GetBasicEntity(), o.GetAnimationComponent(), o.GetRenderComponent()) }
go
{ "resource": "" }
q12712
Remove
train
func (a *AnimationSystem) Remove(basic ecs.BasicEntity) { if a.entities != nil { delete(a.entities, basic.ID()) } }
go
{ "resource": "" }
q12713
Update
train
func (a *AnimationSystem) Update(dt float32) { for _, e := range a.entities { if e.AnimationComponent.CurrentAnimation == nil { if e.AnimationComponent.def == nil { continue } e.AnimationComponent.SelectAnimationByAction(e.AnimationComponent.def) } e.AnimationComponent.change += dt if e.Animation...
go
{ "resource": "" }
q12714
SetTitle
train
func SetTitle(title string) { if opts.HeadlessMode { log.Println("Title set to:", title) } else { Window.SetTitle(title) } }
go
{ "resource": "" }
q12715
NewQuadtree
train
func NewQuadtree(bounds AABB, usePool bool, maxObjects int) *Quadtree { qt := &Quadtree{MaxObjects: maxObjects, usePool: usePool} qt.root = qt.newNode(bounds, 0) qt.MaxLevels = calcMaxLevel(aabbWidth(bounds), aabbHeight(bounds)) return qt }
go
{ "resource": "" }
q12716
Destroy
train
func (qt *Quadtree) Destroy() { qt.freeQuadtreeNode(qt.root) qt.root = nil }
go
{ "resource": "" }
q12717
split
train
func (qt *quadtreeNode) split() { if qt.hasNodes { return } qt.hasNodes = true nextLevel := qt.Level + 1 subWidth := aabbWidth(qt.Bounds) / 2 subHeight := aabbHeight(qt.Bounds) / 2 x := qt.Bounds.Min.X y := qt.Bounds.Min.Y //top right node (0) qt.Nodes[0] = qt.Tree.newNode(aabbRect(x+subWidth, y, subWidth...
go
{ "resource": "" }
q12718
Insert
train
func (qt *Quadtree) Insert(item AABBer) { qt.Total++ pRect := item.AABB() qt.root.Insert(qt.newQuadtreeNodeData(item, pRect)) }
go
{ "resource": "" }
q12719
Remove
train
func (qt *Quadtree) Remove(item AABBer) { bounds := item.AABB() qt.root.Remove(item, bounds) }
go
{ "resource": "" }
q12720
Retrieve
train
func (qt *quadtreeNode) Retrieve(pRect AABB) []AABBer { index := qt.getIndex(pRect) // Array with all detected objects result := make([]AABBer, len(qt.Objects)) for i, o := range qt.Objects { result[i] = o.Value } //if we have subnodes ... if qt.hasNodes { //if pRect fits into a subnode .. if index != -1...
go
{ "resource": "" }
q12721
Retrieve
train
func (qt *Quadtree) Retrieve(find AABB, filter func(aabb AABBer) bool) []AABBer { var foundIntersections []AABBer potentials := qt.root.Retrieve(find) for _, p := range potentials { if aabbOverlaps(find, p.AABB()) && (filter == nil || filter(p)) { foundIntersections = append(foundIntersections, p) } } ret...
go
{ "resource": "" }
q12722
Clear
train
func (qt *Quadtree) Clear() { bounds := qt.root.Bounds qt.freeQuadtreeNode(qt.root) qt.root = qt.newNode(bounds, 0) qt.Total = 0 }
go
{ "resource": "" }
q12723
New
train
func (f *FPSSystem) New(w *ecs.World) { if f.Display { if err := engo.Files.LoadReaderData("gomonobold_fps.ttf", bytes.NewReader(gomonobold.TTF)); err != nil { panic("unable to load gomonobold.ttf for the fps system! Error was: " + err.Error()) } f.fnt = &Font{ URL: "gomonobold_fps.ttf", FG: color.Wh...
go
{ "resource": "" }
q12724
Update
train
func (f *FPSSystem) Update(dt float32) { f.elapsed += dt f.frames += 1 text := "FPS: " + strconv.FormatFloat(float64(f.frames/f.elapsed), 'G', 5, 32) if f.elapsed >= 1 { if f.Display { f.entity.Drawable = Text{ Font: f.fnt, Text: text, } } if f.Terminal { log.Println(text) } f.frames = 0 ...
go
{ "resource": "" }
q12725
Load
train
func (t *tmxLoader) Load(url string, data io.Reader) error { lvl, err := createLevelFromTmx(data, url) if err != nil { return err } t.levels[url] = TMXResource{Level: lvl, url: url} return nil }
go
{ "resource": "" }
q12726
Unload
train
func (t *tmxLoader) Unload(url string) error { delete(t.levels, url) return nil }
go
{ "resource": "" }
q12727
Resource
train
func (t *tmxLoader) Resource(url string) (engo.Resource, error) { tmx, ok := t.levels[url] if !ok { return nil, fmt.Errorf("resource not loaded by `FileLoader`: %q", url) } return tmx, nil }
go
{ "resource": "" }
q12728
Bounds
train
func (l *Level) Bounds() engo.AABB { switch l.Orientation { case orth: return engo.AABB{ Min: l.screenPoint(engo.Point{X: 0, Y: 0}), Max: l.screenPoint(engo.Point{X: float32(l.width), Y: float32(l.height)}), } case iso: xMin := l.screenPoint(engo.Point{X: 0, Y: float32(l.height)}).X + float32(l.TileWidth...
go
{ "resource": "" }
q12729
mapPoint
train
func (l *Level) mapPoint(screenPt engo.Point) engo.Point { switch l.Orientation { case orth: screenPt.Multiply(engo.Point{X: 1 / float32(l.TileWidth), Y: 1 / float32(l.TileHeight)}) return screenPt case iso: return engo.Point{ X: (screenPt.X / float32(l.TileWidth)) + (screenPt.Y / float32(l.TileHeight)), ...
go
{ "resource": "" }
q12730
screenPoint
train
func (l *Level) screenPoint(mapPt engo.Point) engo.Point { switch l.Orientation { case orth: mapPt.Multiply(engo.Point{X: float32(l.TileWidth), Y: float32(l.TileHeight)}) return mapPt case iso: return engo.Point{ X: (mapPt.X - mapPt.Y) * float32(l.TileWidth) / 2, Y: (mapPt.X + mapPt.Y) * float32(l.TileHe...
go
{ "resource": "" }
q12731
View
train
func (t *Tile) View() (float32, float32, float32, float32) { return t.Image.View() }
go
{ "resource": "" }
q12732
Load
train
func (i *fontLoader) Load(url string, data io.Reader) error { ttfBytes, err := ioutil.ReadAll(data) if err != nil { return err } ttf, err := freetype.ParseFont(ttfBytes) if err != nil { return err } i.fonts[url] = FontResource{Font: ttf, url: url} return nil }
go
{ "resource": "" }
q12733
Unload
train
func (i *fontLoader) Unload(url string) error { delete(i.fonts, url) return nil }
go
{ "resource": "" }
q12734
Resource
train
func (i *fontLoader) Resource(url string) (engo.Resource, error) { texture, ok := i.fonts[url] if !ok { return nil, fmt.Errorf("resource not loaded by `FileLoader`: %q", url) } return texture, nil }
go
{ "resource": "" }
q12735
Close
train
func (p *Player) Close() error { runtime.SetFinalizer(p, nil) p.isPlaying = false select { case p.closeCh <- struct{}{}: <-p.closedCh return nil case <-p.readLoopEndedCh: return fmt.Errorf("audio: the player is already closed") } }
go
{ "resource": "" }
q12736
Seek
train
func (p *Player) Seek(offset time.Duration) error { o := int64(offset) * bytesPerSample * channelNum * int64(p.sampleRate) / int64(time.Second) o &= mask select { case p.seekCh <- seekArgs{o, io.SeekStart}: return <-p.seekedCh case <-p.readLoopEndedCh: return fmt.Errorf("audio: the player is already closed") ...
go
{ "resource": "" }
q12737
Current
train
func (p *Player) Current() time.Duration { sample := int64(0) p.sync(func() { sample = p.pos / bytesPerSample / channelNum }) return time.Duration(sample) * time.Second / time.Duration(p.sampleRate) }
go
{ "resource": "" }
q12738
GetVolume
train
func (p *Player) GetVolume() float64 { v := 0.0 p.sync(func() { v = p.volume }) return v }
go
{ "resource": "" }
q12739
SetVolume
train
func (p *Player) SetVolume(volume float64) { // The condition must be true when volume is NaN. if volume < 0 || volume > 1 { log.Println("Volume can only be set between zero and one. Volume was not set.") return } p.sync(func() { p.volume = volume * masterVolume }) }
go
{ "resource": "" }
q12740
Nextafter
train
func Nextafter(x, y int) (r int) { return engoimath.Nextafter(x, y) }
go
{ "resource": "" }
q12741
Dispatch
train
func (mm *MessageManager) Dispatch(message Message) { mm.RLock() mm.clearRemovedHandlers() handlers := make([]MessageHandler, len(mm.listeners[message.Type()])) pairs := mm.listeners[message.Type()] for i := range pairs { handlers[i] = pairs[i].MessageHandler } mm.RUnlock() for _, handler := range handlers {...
go
{ "resource": "" }
q12742
Listen
train
func (mm *MessageManager) Listen(messageType string, handler MessageHandler) MessageHandlerId { mm.Lock() defer mm.Unlock() if mm.listeners == nil { mm.listeners = make(map[string][]HandlerIDPair) } handlerID := getNewHandlerID() newHandlerIDPair := HandlerIDPair{MessageHandlerId: handlerID, MessageHandler: han...
go
{ "resource": "" }
q12743
StopListen
train
func (mm *MessageManager) StopListen(messageType string, handlerID MessageHandlerId) { if mm.handlersToRemove == nil { mm.handlersToRemove = make(map[string][]MessageHandlerId) } mm.handlersToRemove[messageType] = append(mm.handlersToRemove[messageType], handlerID) }
go
{ "resource": "" }
q12744
removeHandler
train
func (mm *MessageManager) removeHandler(messageType string, handlerID MessageHandlerId) { indexOfHandler := -1 for i, activeHandler := range mm.listeners[messageType] { if activeHandler.MessageHandlerId == handlerID { indexOfHandler = i break } } // A handler might have already been removed during a previ...
go
{ "resource": "" }
q12745
SetScene
train
func SetScene(s Scene, forceNewWorld bool) { // Break down currentScene if currentScene != nil { if hider, ok := currentScene.(Hider); ok { hider.Hide() } } // Register Scene if needed sceneMutex.RLock() wrapper, registered := scenes[s.Type()] sceneMutex.RUnlock() if !registered { RegisterScene(s) ...
go
{ "resource": "" }
q12746
RegisterScene
train
func RegisterScene(s Scene) { sceneMutex.RLock() _, ok := scenes[s.Type()] sceneMutex.RUnlock() if !ok { sceneMutex.Lock() scenes[s.Type()] = &sceneWrapper{scene: s} sceneMutex.Unlock() } }
go
{ "resource": "" }
q12747
NewKeyManager
train
func NewKeyManager() *KeyManager { return &KeyManager{ dirtmap: make(map[Key]Key), mapper: make(map[Key]KeyState), } }
go
{ "resource": "" }
q12748
Set
train
func (km *KeyManager) Set(k Key, state bool) { km.mutex.Lock() ks := km.mapper[k] ks.set(state) km.mapper[k] = ks km.dirtmap[k] = k km.mutex.Unlock() }
go
{ "resource": "" }
q12749
Get
train
func (km *KeyManager) Get(k Key) KeyState { km.mutex.RLock() ks := km.mapper[k] km.mutex.RUnlock() return ks }
go
{ "resource": "" }
q12750
State
train
func (key *KeyState) State() int { if key.lastState { if key.currentState { return KeyStateDown } return KeyStateJustUp } if key.currentState { return KeyStateJustDown } return KeyStateUp }
go
{ "resource": "" }
q12751
Down
train
func (b Button) Down() bool { for _, trigger := range b.Triggers { v := Input.keys.Get(trigger).Down() if v { return v } } return false }
go
{ "resource": "" }
q12752
Run
train
func Run(o RunOptions, defaultScene Scene) { // Setting defaults if o.FPSLimit == 0 { o.FPSLimit = 60 } if o.MSAA < 0 { panic("MSAA has to be greater or equal to 0") } if o.MSAA == 0 { o.MSAA = 1 } if len(o.AssetsRoot) == 0 { o.AssetsRoot = "assets" } if o.Update == nil { o.Update = &ecs.World{}...
go
{ "resource": "" }
q12753
SetFPSLimit
train
func SetFPSLimit(limit int) error { if limit <= 0 { return fmt.Errorf("FPS Limit out of bounds. Requires > 0") } opts.FPSLimit = limit resetLoopTicker <- true return nil }
go
{ "resource": "" }
q12754
TouchEvent
train
func TouchEvent(x, y, id, action int) { Input.Mouse.X = float32(x) / opts.GlobalScale.X Input.Mouse.Y = float32(y) / opts.GlobalScale.Y switch action { case C.UITouchPhaseBegan, C.UITouchPhaseStationary: Input.Mouse.Action = Press Input.Touches[id] = Point{ X: float32(x) / opts.GlobalScale.X, Y: float32(y...
go
{ "resource": "" }
q12755
SetTitle
train
func SetTitle(title string) { if opts.HeadlessMode { log.Println("Title set to:", title) } else { document.Set("title", title) } }
go
{ "resource": "" }
q12756
WindowSize
train
func WindowSize() (w, h int) { w = int(WindowWidth()) h = int(WindowHeight()) return }
go
{ "resource": "" }
q12757
jsPollKeys
train
func jsPollKeys() { pollLock.Lock() defer pollLock.Unlock() for key, state := range poll { Input.keys.Set(Key(key), state) delete(poll, key) } }
go
{ "resource": "" }
q12758
RunPreparation
train
func RunPreparation() { Time = NewClock() if !opts.HeadlessMode { window.Call("addEventListener", "onbeforeunload", js.NewEventCallback(js.PreventDefault, func(event js.Value) { window.Call("alert", "You're closing") })) } }
go
{ "resource": "" }
q12759
SetCursor
train
func SetCursor(c Cursor) { switch c { case CursorNone: document.Get("body").Get("style").Set("cursor", "default") case CursorHand: document.Get("body").Get("style").Set("cursor", "hand") } }
go
{ "resource": "" }
q12760
CreateWindow
train
func CreateWindow(title string, width, height int, fullscreen bool, msaa int) { CurrentBackEnd = BackEndSDL err := sdl.Init(sdl.INIT_EVERYTHING) fatalErr(err) if !opts.HeadlessMode { cursorNone = sdl.CreateSystemCursor(sdl.SYSTEM_CURSOR_NO) cursorArrow = sdl.CreateSystemCursor(sdl.SYSTEM_CURSOR_ARROW) curso...
go
{ "resource": "" }
q12761
WindowSize
train
func WindowSize() (w, h int) { width, height := Window.GetSize() return int(width), int(height) }
go
{ "resource": "" }
q12762
TouchEvent
train
func TouchEvent(x, y, id, action int) { Input.Mouse.X = float32(x) / opts.GlobalScale.X Input.Mouse.Y = float32(y) / opts.GlobalScale.Y switch action { case 0, 5: Input.Mouse.Action = Press Input.Touches[id] = Point{ X: float32(x) / opts.GlobalScale.X, Y: float32(y) / opts.GlobalScale.Y, } case 1, 6: ...
go
{ "resource": "" }
q12763
New
train
func (cam *CameraSystem) New(w *ecs.World) { num := 0 for _, sys := range w.Systems() { switch sys.(type) { case *CameraSystem: num++ } } if num > 0 { //initalizer is called before added to w.systems warning("More than one CameraSystem was added to the World. The RenderSystem adds a CameraSystem if none ...
go
{ "resource": "" }
q12764
Update
train
func (cam *CameraSystem) Update(dt float32) { for axis, longTask := range cam.longTasks { if !longTask.Incremental { longTask.Incremental = true switch axis { case XAxis: longTask.Value -= cam.x case YAxis: longTask.Value -= cam.y case ZAxis: longTask.Value -= cam.z case Angle: lon...
go
{ "resource": "" }
q12765
FollowEntity
train
func (cam *CameraSystem) FollowEntity(basic *ecs.BasicEntity, space *SpaceComponent, trackRotation bool) { cam.tracking = cameraEntity{basic, space} cam.trackRotation = trackRotation }
go
{ "resource": "" }
q12766
Update
train
func (c *KeyboardScroller) Update(dt float32) { c.keysMu.RLock() defer c.keysMu.RUnlock() m := engo.Point{ X: engo.Input.Axis(c.horizontalAxis).Value(), Y: engo.Input.Axis(c.verticalAxis).Value(), } n, _ := m.Normalize() engo.Mailbox.Dispatch(CameraMessage{Axis: XAxis, Value: n.X * c.ScrollSpeed * dt, Increm...
go
{ "resource": "" }
q12767
BindKeyboard
train
func (c *KeyboardScroller) BindKeyboard(hori, vert string) { c.keysMu.Lock() c.verticalAxis = vert c.horizontalAxis = hori defer c.keysMu.Unlock() }
go
{ "resource": "" }
q12768
NewKeyboardScroller
train
func NewKeyboardScroller(scrollSpeed float32, hori, vert string) *KeyboardScroller { kbs := &KeyboardScroller{ ScrollSpeed: scrollSpeed, } kbs.BindKeyboard(hori, vert) return kbs }
go
{ "resource": "" }
q12769
New
train
func (c *EntityScroller) New(*ecs.World) { offsetX, offsetY := engo.GameWidth()/2, engo.GameHeight()/2 CameraBounds.Min.X = c.TrackingBounds.Min.X + (offsetX / engo.GetGlobalScale().X) CameraBounds.Min.Y = c.TrackingBounds.Min.Y + (offsetY / engo.GetGlobalScale().Y) CameraBounds.Max.X = c.TrackingBounds.Max.X - (...
go
{ "resource": "" }
q12770
Update
train
func (c *EntityScroller) Update(dt float32) { if c.SpaceComponent == nil { return } width, height := c.SpaceComponent.Width, c.SpaceComponent.Height pos := c.SpaceComponent.Position trackToX := pos.X + width/2 trackToY := pos.Y + height/2 engo.Mailbox.Dispatch(CameraMessage{Axis: XAxis, Value: trackToX, Inc...
go
{ "resource": "" }
q12771
Update
train
func (c *MouseZoomer) Update(float32) { if engo.Input.Mouse.ScrollY != 0 { engo.Mailbox.Dispatch(CameraMessage{Axis: ZAxis, Value: engo.Input.Mouse.ScrollY * c.ZoomSpeed, Incremental: true}) } }
go
{ "resource": "" }
q12772
Update
train
func (c *MouseRotator) Update(float32) { if engo.Input.Mouse.Button == engo.MouseButtonMiddle && engo.Input.Mouse.Action == engo.Press { c.pressed = true } if engo.Input.Mouse.Action == engo.Release { c.pressed = false } if c.pressed { engo.Mailbox.Dispatch(CameraMessage{Axis: Angle, Value: (c.oldX - engo....
go
{ "resource": "" }
q12773
Corners
train
func (sc SpaceComponent) Corners() (points [4]engo.Point) { points[0].X = sc.Position.X points[0].Y = sc.Position.Y sin, cos := math.Sincos(sc.Rotation * math.Pi / 180) points[1].X = points[0].X + sc.Width*cos points[1].Y = points[0].Y + sc.Width*sin points[2].X = points[0].X - sc.Height*sin points[2].Y = poi...
go
{ "resource": "" }
q12774
triangleArea
train
func triangleArea(p1, p2, p3 engo.Point) float32 { // Law of cosines states: (note a2 = math.Pow(a, 2)) // a2 = b2 + c2 - 2bc*cos(alpha) // This ends in: alpha = arccos ((-a2 + b2 + c2)/(2bc)) a := p1.PointDistance(p3) b := p1.PointDistance(p2) c := p2.PointDistance(p3) alpha := math.Acos((-math.Pow(a, 2) + math...
go
{ "resource": "" }
q12775
Add
train
func (c *CollisionSystem) Add(basic *ecs.BasicEntity, collision *CollisionComponent, space *SpaceComponent) { c.entities = append(c.entities, collisionEntity{basic, collision, space}) }
go
{ "resource": "" }
q12776
AddByInterface
train
func (c *CollisionSystem) AddByInterface(i ecs.Identifier) { o, _ := i.(Collisionable) c.Add(o.GetBasicEntity(), o.GetCollisionComponent(), o.GetSpaceComponent()) }
go
{ "resource": "" }
q12777
IsIntersecting
train
func IsIntersecting(rect1 engo.AABB, rect2 engo.AABB) bool { if rect1.Max.X > rect2.Min.X && rect1.Min.X < rect2.Max.X && rect1.Max.Y > rect2.Min.Y && rect1.Min.Y < rect2.Max.Y { return true } return false }
go
{ "resource": "" }
q12778
MinimumTranslation
train
func MinimumTranslation(rect1 engo.AABB, rect2 engo.AABB) engo.Point { mtd := engo.Point{} left := rect2.Min.X - rect1.Max.X right := rect2.Max.X - rect1.Min.X top := rect2.Min.Y - rect1.Max.Y bottom := rect2.Max.Y - rect1.Min.Y if left > 0 || right < 0 { log.Println("Box aint intercepting") return mtd //...
go
{ "resource": "" }
q12779
NewMDBStoreWithSize
train
func NewMDBStoreWithSize(base string, maxSize uint64) (*MDBStore, error) { // Get the paths path := filepath.Join(base, mdbPath) if err := os.MkdirAll(path, 0755); err != nil { return nil, err } // Set the maxSize if not given if maxSize == 0 { maxSize = dbMaxMapSize } // Create the env env, err := mdb.N...
go
{ "resource": "" }
q12780
initialize
train
func (m *MDBStore) initialize() error { // Allow up to 2 sub-dbs if err := m.env.SetMaxDBs(mdb.DBI(2)); err != nil { return err } // Increase the maximum map size if err := m.env.SetMapSize(m.maxSize); err != nil { return err } // Open the DB if err := m.env.Open(m.path, mdb.NOTLS, 0755); err != nil { r...
go
{ "resource": "" }
q12781
startTxn
train
func (m *MDBStore) startTxn(readonly bool, open ...string) (*mdb.Txn, []mdb.DBI, error) { var txFlags uint = 0 var dbFlags uint = 0 if readonly { txFlags |= mdb.RDONLY } else { dbFlags |= mdb.CREATE } tx, err := m.env.BeginTxn(nil, txFlags) if err != nil { return nil, nil, err } var dbs []mdb.DBI for ...
go
{ "resource": "" }
q12782
GetLog
train
func (m *MDBStore) GetLog(index uint64, logOut *raft.Log) error { key := uint64ToBytes(index) tx, dbis, err := m.startTxn(true, dbLogs) if err != nil { return err } defer tx.Abort() val, err := tx.Get(dbis[0], key) if err == mdb.NotFound { return raft.ErrLogNotFound } else if err != nil { return err } ...
go
{ "resource": "" }
q12783
StoreLog
train
func (m *MDBStore) StoreLog(log *raft.Log) error { return m.StoreLogs([]*raft.Log{log}) }
go
{ "resource": "" }
q12784
StoreLogs
train
func (m *MDBStore) StoreLogs(logs []*raft.Log) error { // Start write txn tx, dbis, err := m.startTxn(false, dbLogs) if err != nil { return err } for _, log := range logs { // Convert to an on-disk format key := uint64ToBytes(log.Index) val, err := encodeMsgPack(log) if err != nil { tx.Abort() ret...
go
{ "resource": "" }
q12785
DeleteRange
train
func (m *MDBStore) DeleteRange(minIdx, maxIdx uint64) error { // Start write txn tx, dbis, err := m.startTxn(false, dbLogs) if err != nil { return err } defer tx.Abort() // Hack around an LMDB bug by running the delete multiple // times until there are no further rows. var num int DELETE: num, err = m.inner...
go
{ "resource": "" }
q12786
NewWatcher
train
func NewWatcher() (*Watcher, error) { listener, err := createListener() if err != nil { return nil, err } w := &Watcher{ listener: listener, watches: make(map[int]*watch), watchesMutex: &sync.Mutex{}, Fork: make(chan *ProcEventFork), Exec: make(chan *ProcEventExec), Exit: ...
go
{ "resource": "" }
q12787
finish
train
func (w *Watcher) finish() { close(w.Fork) close(w.Exec) close(w.Exit) close(w.Error) }
go
{ "resource": "" }
q12788
Close
train
func (w *Watcher) Close() error { w.closedMutex.Lock() defer w.closedMutex.Unlock() if w.isClosed { return nil } w.isClosed = true w.watchesMutex.Lock() for pid := range w.watches { delete(w.watches, pid) w.unregister(pid) } w.watchesMutex.Unlock() w.done <- true w.listener.close() return nil }
go
{ "resource": "" }
q12789
RemoveWatch
train
func (w *Watcher) RemoveWatch(pid int) error { w.watchesMutex.Lock() defer w.watchesMutex.Unlock() _, ok := w.watches[pid] if !ok { msg := fmt.Sprintf("watch for pid=%d does not exist", pid) return errors.New(msg) } delete(w.watches, pid) return w.unregister(pid) }
go
{ "resource": "" }
q12790
LookupPrivilegeName
train
func LookupPrivilegeName(systemName string, luid int64) (string, error) { buf := make([]uint16, 256) bufSize := uint32(len(buf)) err := _LookupPrivilegeName(systemName, &luid, &buf[0], &bufSize) if err != nil { return "", errors.Wrapf(err, "LookupPrivilegeName failed for luid=%v", luid) } return syscall.UTF16T...
go
{ "resource": "" }
q12791
mapPrivileges
train
func mapPrivileges(names []string) ([]int64, error) { var privileges []int64 privNameMutex.Lock() defer privNameMutex.Unlock() for _, name := range names { p, ok := privNames[name] if !ok { err := _LookupPrivilegeValue("", name, &p) if err != nil { return nil, errors.Wrapf(err, "LookupPrivilegeValue f...
go
{ "resource": "" }
q12792
EnableTokenPrivileges
train
func EnableTokenPrivileges(token syscall.Token, privileges ...string) error { privValues, err := mapPrivileges(privileges) if err != nil { return err } var b bytes.Buffer binary.Write(&b, binary.LittleEndian, uint32(len(privValues))) for _, p := range privValues { binary.Write(&b, binary.LittleEndian, p) b...
go
{ "resource": "" }
q12793
GetTokenUser
train
func GetTokenUser(token syscall.Token) (User, error) { tokenUser, err := token.GetTokenUser() if err != nil { return User{}, errors.Wrap(err, "GetTokenUser failed") } var user User user.SID, err = tokenUser.User.Sid.String() if err != nil { return user, errors.Wrap(err, "ConvertSidToStringSid failed") } u...
go
{ "resource": "" }
q12794
GetDebugInfo
train
func GetDebugInfo() (*DebugInfo, error) { h, err := windows.GetCurrentProcess() if err != nil { return nil, err } var token syscall.Token err = syscall.OpenProcessToken(syscall.Handle(h), syscall.TOKEN_QUERY, &token) if err != nil { return nil, err } privs, err := GetTokenPrivileges(token) if err != nil ...
go
{ "resource": "" }
q12795
createListener
train
func createListener() (eventListener, error) { listener := &kqueueListener{} kq, err := syscall.Kqueue() listener.kq = kq return listener, err }
go
{ "resource": "" }
q12796
kevent
train
func (w *Watcher) kevent(pid int, fflags uint32, flags int) error { listener, _ := w.listener.(*kqueueListener) event := &listener.buf[0] syscall.SetKevent(event, pid, syscall.EVFILT_PROC, flags) event.Fflags = fflags _, err := syscall.Kevent(listener.kq, listener.buf[:], nil, nil) return err }
go
{ "resource": "" }
q12797
unregister
train
func (w *Watcher) unregister(pid int) error { return w.kevent(pid, 0, syscall.EV_DELETE) }
go
{ "resource": "" }
q12798
register
train
func (w *Watcher) register(pid int, flags uint32) error { return w.kevent(pid, flags, syscall.EV_ADD|syscall.EV_ENABLE) }
go
{ "resource": "" }
q12799
readEvents
train
func (w *Watcher) readEvents() { listener, _ := w.listener.(*kqueueListener) events := make([]syscall.Kevent_t, 10) for { if w.isDone() { return } n, err := syscall.Kevent(listener.kq, nil, events, nil) if err != nil { w.Error <- err continue } for _, ev := range events[:n] { pid := int(ev...
go
{ "resource": "" }