// PeepEvents checks the event queue for messages and optionally return them.
// (https://wiki.libsdl.org/SDL_PeepEvents)
975789
func PeepEvents(events []Event, action EventAction, minType, maxType uint32) (storedEvents int, err error) {
	if events == nil {
		return 0, nil
	}

	var _events []CEvent = make([]CEvent, len(events))

	if action == ADDEVENT { // the contents of _events matter if they are to be added
		for i := 0; i < len(events); i++ {
			_events[i] = *cEvent(events[i])
		}
	}

	_pevents := (*C.SDL_Event)(unsafe.Pointer(&_events[0]))
	storedEvents = int(C.SDL_PeepEvents(_pevents, C.int(len(events)), action.c(), C.Uint32(minType), C.Uint32(maxType)))

	if action != ADDEVENT { // put events into slice, events unchanged if action = ADDEVENT
		for i := 0; i < storedEvents; i++ {
			events[i] = goEvent(&_events[i])
		}
	}

	if storedEvents < 0 {
		err = GetError()
	}

	return
}
411699
func (s *Simulator) peekEvent() *event {
	if len(s.events) == 0 {
		return nil
	}
	return &s.events[0]
}
1315200
func (mg *MailgunImpl) ListEvents(opts *ListEventOptions) *EventIterator {
	req := newHTTPRequest(generateApiUrl(mg, eventsEndpoint))
	if opts != nil {
		if opts.Limit > 0 {
			req.addParameter("limit", fmt.Sprintf("%d", opts.Limit))
		}
		if opts.Compact {
			req.addParameter("pretty", "no")
		}
		if opts.ForceAscending {
			req.addParameter("ascending", "yes")
		} else if opts.ForceDescending {
			req.addParameter("ascending", "no")
		}
		if !opts.Begin.IsZero() {
			req.addParameter("begin", formatMailgunTime(opts.Begin))
		}
		if !opts.End.IsZero() {
			req.addParameter("end", formatMailgunTime(opts.End))
		}
		if opts.Filter != nil {
			for k, v := range opts.Filter {
				req.addParameter(k, v)
			}
		}
	}
	url, err := req.generateUrlWithParameters()
	return &EventIterator{
		mg:       mg,
		Response: events.Response{Paging: events.Paging{Next: url, First: url}},
		err:      err,
	}
}
345257
func WaitEvent() Event {
	var cevent CEvent
	_event := (*C.SDL_Event)(unsafe.Pointer(&cevent))
	ok := int(C.SDL_WaitEvent(_event))
	if ok == 0 {
		return nil
	}
	return goEvent(&cevent)
}
59235
func (m *MonitorFormatter) debugEvents(prefix string, data []byte) {
	dm := monitor.DebugMsg{}

	if err := binary.Read(bytes.NewReader(data), byteorder.Native, &dm); err != nil {
		fmt.Printf("Error while parsing debug message: %s\n", err)
	}
	if m.match(monitorAPI.MessageTypeDebug, dm.Source, 0) {
		switch m.Verbosity {
		case INFO:
			dm.DumpInfo(data)
		case JSON:
			dm.DumpJSON(prefix)
		default:
			dm.Dump(prefix)
		}
	}
}
1349683
func (s *EventService) ListEvents(p *ListEventsParams) (*ListEventsResponse, error) {
	resp, err := s.cs.newRequest("listEvents", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListEventsResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
1059790
func (g *GRPCServer) WatchEvents(watch *proto.Watch, stream proto.AuthService_WatchEventsServer) error {
	auth, err := g.authenticate(stream.Context())
	if err != nil {
		return trail.ToGRPC(err)
	}
	servicesWatch := services.Watch{
		Name: auth.User.GetName(),
	}
	for _, kind := range watch.Kinds {
		servicesWatch.Kinds = append(servicesWatch.Kinds, services.WatchKind{
			Name:        kind.Name,
			Kind:        kind.Kind,
			LoadSecrets: kind.LoadSecrets,
		})
	}
	watcher, err := auth.NewWatcher(stream.Context(), servicesWatch)
	if err != nil {
		return trail.ToGRPC(err)
	}
	defer watcher.Close()

	for {
		select {
		case <-stream.Context().Done():
			return nil
		case <-watcher.Done():
			return trail.ToGRPC(watcher.Error())
		case event := <-watcher.Events():
			out, err := eventToGRPC(event)
			if err != nil {
				return trail.ToGRPC(err)
			}
			if err := stream.Send(out); err != nil {
				return trail.ToGRPC(err)
			}
		}
	}
}
1245074
func ParseEvent(rawEvent json.RawMessage, opts ...Option) (EventsAPIEvent, error) {
	e, err := parseOuterEvent(rawEvent)
	if err != nil {
		return EventsAPIEvent{}, err
	}

	cfg := &Config{}
	cfg.VerificationToken = e.Token
	for _, opt := range opts {
		opt(cfg)
	}

	if !cfg.TokenVerified {
		return EventsAPIEvent{}, errors.New("Invalid verification token")
	}

	if e.Type == CallbackEvent {
		cbEvent := e.Data.(*EventsAPICallbackEvent)
		innerEvent, err := parseInnerEvent(cbEvent)
		if err != nil {
			err := fmt.Errorf("EventsAPI Error parsing inner event: %s, %s", innerEvent.Type, err)
			return EventsAPIEvent{
				"",
				"",
				"unmarshalling_error",
				&slack.UnmarshallingErrorEvent{ErrorObj: err},
				EventsAPIInnerEvent{},
			}, err
		}
		return innerEvent, nil
	}
	urlVerificationEvent := &EventsAPIURLVerificationEvent{}
	err = json.Unmarshal(rawEvent, urlVerificationEvent)
	if err != nil {
		return EventsAPIEvent{
			"",
			"",
			"unmarshalling_error",
			&slack.UnmarshallingErrorEvent{ErrorObj: err},
			EventsAPIInnerEvent{},
		}, err
	}
	return EventsAPIEvent{
		e.Token,
		e.TeamID,
		e.Type,
		urlVerificationEvent,
		EventsAPIInnerEvent{},
	}, nil
}
1036631
func (ew *EventsWriter) GetPastEvents(request *Request) ([]*Event, error) {
	if ew.H != nil {
		return ew.H.GetEvents(request)
	}
	return nil, nil
}
1093428
func (m *MonitorFormatter) dropEvents(prefix string, data []byte) {
	dn := monitor.DropNotify{}

	if err := binary.Read(bytes.NewReader(data), byteorder.Native, &dn); err != nil {
		fmt.Printf("Error while parsing drop notification message: %s\n", err)
	}
	if m.match(monitorAPI.MessageTypeDrop, dn.Source, uint16(dn.DstID)) {
		switch m.Verbosity {
		case INFO:
			dn.DumpInfo(data)
		case JSON:
			dn.DumpJSON(data, prefix)
		default:
			fmt.Println(msgSeparator)
			dn.DumpVerbose(!m.Hex, data, prefix)
		}
	}
}
378282
func (c *DefaultClient) SubscribeAppEvents(appID string, eventType types.EventType, handler AppEventHandler) Token {
	topic := ApplicationTopic{appID, AppEvents, string(eventType)}
	return c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {
		topic, err := ParseApplicationTopic(msg.Topic())
		if err != nil {
			c.ctx.Warnf("mqtt: received message on invalid events topic: %s", msg.Topic())
			return
		}
		handler(c, topic.AppID, types.EventType(topic.Field), msg.Payload())
	})
}
180047
func (c *Chunk) Events() (cgem chan *GoEvtxMap) {
	// Unbuffered Event channel
	cgem = make(chan *GoEvtxMap, len(c.EventOffsets))
	go func() {
		defer close(cgem)
		for _, eo := range c.EventOffsets {
			// for every event offset, we parsed the event at that position
			event := c.ParseEvent(int64(eo))
			gem, err := event.GoEvtxMap(c)
			if err == nil {
				cgem <- gem
			}
		}
	}()
	return
}
803279
func (api *PrivateAdminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription, error) {
	// Make sure the server is running, fail otherwise
	server := api.node.Server()
	if server == nil {
		return nil, ErrNodeStopped
	}

	// Create the subscription
	notifier, supported := rpc.NotifierFromContext(ctx)
	if !supported {
		return nil, rpc.ErrNotificationsUnsupported
	}
	rpcSub := notifier.CreateSubscription()

	go func() {
		events := make(chan *p2p.PeerEvent)
		sub := server.SubscribeEvents(events)
		defer sub.Unsubscribe()

		for {
			select {
			case event := <-events:
				notifier.Notify(rpcSub.ID, event)
			case <-sub.Err():
				return
			case <-rpcSub.Err():
				return
			case <-notifier.Closed():
				return
			}
		}
	}()

	return rpcSub, nil
}
1245898
func pollEvents() {
	defer context.wg.Done()
	for {
		errCode := C.memif_poll_event(C.int(-1))
		err := getMemifError(int(errCode))
		if err == ErrPollCanceled {
			return
		}
	}
}
457055
func (w *Watcher) readEvents() {
	buf := make([]byte, syscall.Getpagesize())

	listener, _ := w.listener.(*netlinkListener)

	for {
		if w.isDone() {
			return
		}

		nr, _, err := syscall.Recvfrom(listener.sock, buf, 0)

		if err != nil {
			w.Error <- err
			continue
		}
		if nr < syscall.NLMSG_HDRLEN {
			w.Error <- syscall.EINVAL
			continue
		}

		msgs, _ := syscall.ParseNetlinkMessage(buf[:nr])

		for _, m := range msgs {
			if m.Header.Type == syscall.NLMSG_DONE {
				w.handleEvent(m.Data)
			}
		}
	}
}
1185593
func ParseEvent(data []byte) Event {
	// Not supported
	return Event{Type: EventError, Err: errors.New("no raw events")}
}
613790
func ParseEvent(raw []byte) (Event, error) {
	// Try to recognize the event first.
	var e events.EventName
	if err := easyjson.Unmarshal(raw, &e); err != nil {
		return nil, fmt.Errorf("failed to recognize event: %v", err)
	}

	// Get the event "constructor" from the map.
	newEvent, ok := EventNames[e.Name]
	if !ok {
		return nil, fmt.Errorf("unsupported event: '%s'", e.Name)
	}
	event := newEvent()

	// Parse the known event.
	if err := easyjson.Unmarshal(raw, event); err != nil {
		return nil, fmt.Errorf("failed to parse event '%s': %v", e.Name, err)
	}

	return event, nil
}