Parse EVENT chunks
323182
def eventChunk(key, lines):
    
    ## NOTE: RADAR file format not supported currently.
    ## TODO: Add Support for RADAR file format type values

    # Contants
    KEYWORDS = ('EVENT',
                'NRPDS',
                'NRGAG',
                'COORD',
                'GAGES',
                'ACCUM',
                'RATES',
                'RADAR')

    NUM_CARDS = ('NRPDS',
                 'NRGAG')

    VALUE_CARDS = ('GAGES',
                   'ACCUM',
                   'RATES',
                   'RADAR')

    # Define result object
    result = {'description': None,
              'nrgag': None,
              'nrpds': None,
              'coords':[],
              'valLines':[]}

    chunks = pt.chunk(KEYWORDS, lines)

    # Parse chunks associated with each key
    for card, chunkList in iteritems(chunks):
        # Parse each chunk in the chunk list
        for chunk in chunkList:
            schunk = chunk[0].strip().split()

            # Cases
            if card == 'EVENT':
                # EVENT handler
                schunk = pt.splitLine(chunk[0])
                result['description'] = schunk[1]

            elif card in NUM_CARDS:
                # Num cards handler
                result[card.lower()] = schunk[1]

            elif card == 'COORD':
                # COORD handler
                schunk = pt.splitLine(chunk[0])

                try:
                    # Extract the event description
                    desc = schunk[3]
                except:
                    # Handle case where the event description is blank
                    desc = ""

                coord = {'x': schunk[1],
                         'y': schunk[2],
                         'description': desc}

                result['coords'].append(coord)

            elif card in VALUE_CARDS:
                # Value cards handler
                # Extract DateTime
                dateTime = datetime(year=int(schunk[1]),
                                    month=int(schunk[2]),
                                    day=int(schunk[3]),
                                    hour=int(schunk[4]),
                                    minute=int(schunk[5]))

                # Compile values into a list
                values = []
                for index in range(6, len(schunk)):
                    values.append(schunk[index])

                valueLine = {'type': schunk[0],
                             'dateTime': dateTime,
                             'values': values}

                result['valLines'].append(valueLine)

    return result
1102476
function normalizeEvents(events)
{
  // start with converting falsy events into catch-all placeholder
  events = events || entryPoint;

  if (!Array.isArray(events))
  {
    events = [events];
  }

  // return shallow copy
  return events.concat();
}
1314471
def read_event(self, check_result):
        '''
        
        '''
        try:
            event = json.loads(check_result)
            event['occurrences'] = event.get('occurrences', 1)
            event['check'] = event.get('check', {})
            event['client'] = event.get('client', {})
            return event
        except Exception:
            raise ValueError('error reading event: ' + check_result)
1247168
def _parse_one_event(self):
        """"""
        # WVA includes \r\n between messages which the parser doesn't like, so we
        # throw away any data before a opening brace
        try:
            open_brace_idx = self._buf.index('{')
        except ValueError:
            self._buf = six.u('')  # no brace found
        else:
            if open_brace_idx > 0:
                self._buf = self._buf[open_brace_idx:]

        try:
            event, idx = self._decoder.raw_decode(self._buf)
            self._buf = self._buf[idx:]
            return event
        except ValueError:
            return None
797725
function parse(str, options, callback) {
	if (typeof options === 'function') {
		callback = options
		options = {}
	}
	process.nextTick(() => {
		const output = parseSync(str, options)
		callback(output)
	})
}
905401
def parse_timedelta(ev):
    

    chunks = ev['event-duration'].split()
    tdargs = {}
    for c in chunks:
        try:
            m = TIME_MULTIPLIERS[c[-1]]
            val = int(c[:-1])
            tdargs[m] = val
        except KeyError:
            log.error("""Unknown time multiplier '%s' value in the \
'event-duration' field in the '%s' event. Supported multipliers \
are: '%s'.""" % (c, ev['title'], ' '.join(TIME_MULTIPLIERS)))
            raise RuntimeError("Unknown time multiplier '%s'" % c)
        except ValueError:
            log.error("""Unable to parse '%s' value in the 'event-duration' \
field in the '%s' event.""" % (c, ev['title']))
            raise ValueError("Unable to parse '%s'" % c)


    return timedelta(**tdargs)
759916
def get_events(self):
        
        with open(self._path, 'r') as file_:
            file_lines = file_.read().splitlines()
            event_lines = [line for line in file_lines if line]
        events = []
        for event_line in event_lines:
            for event_cls in (AddEvent, SetReadingEvent, ReadEvent,
                              SetFinishedEvent):
                try:
                    event = event_cls.from_str(event_line)
                except EventParseError:
                    pass
                else:
                    events.append(event)
        return events
718692
function eventMessageChunker(buffer) {
    /** @type Buffer[] */
    var messages = [];
    var offset = 0;

    while (offset < buffer.length) {
        var totalLength = buffer.readInt32BE(offset);

        // create new buffer for individual message (shares memory with original)
        var message = buffer.slice(offset, totalLength + offset);
        // increment offset to it starts at the next message
        offset += totalLength;

        messages.push(message);
    }

    return messages;
}
1153964
function buildSegments(events) {
		var segments = [];
		for (var i=0; i<events.length; i++) {
			var eventSegments = buildSegmentsForEvent(events[i]);
			segments.push.apply(segments, eventSegments); // append an array to an array
		}
		return segments;
	}
895558
private static List<TraceEvent> getEvents(List<String> data) throws Exception
   {
      List<TraceEvent> result = new ArrayList<TraceEvent>();

      for (String s : data)
      {
         result.add(TraceEvent.parse(s));
      }

      return result;
   }
626217
private List<Event> parseEvent(Elements trs, Organization organization) throws ParseException {
        List<Event> events = new ArrayList<>();

        if (trs.size() > 0) {
            trs.remove(0);


            SherdogBaseObject sOrg = new SherdogBaseObject();
            sOrg.setName(organization.getName());
            sOrg.setSherdogUrl(organization.getSherdogUrl());


            trs.forEach(tr -> {

                Event event = new Event();
                boolean addEvent = true;
                Elements tds = tr.select("td");

                event.setOrganization(sOrg);

                event.setName(getEventName(tds.get(NAME_COLUMN)));
                event.setSherdogUrl(getEventUrl(tds.get(NAME_COLUMN)));
                event.setLocation(getElementLocation(tds.get(LOCATION_COLUMN)));

                try {
                    event.setDate(getEventDate(tds.get(DATE_COLUMN)));
                } catch (DateTimeParseException e) {
                    logger.error("Couldn't fornat date, we shouldn't add the event", e);
                    addEvent = false;
                }

                if (addEvent) {
                    events.add(event);
                }
            });
        }

        return events;
    }
823999
function() {
      if (this.allObjectEvents_.length === 0)
        return;

      function processEvent(objectEventState) {
        var event = objectEventState.event;
        var thread = objectEventState.thread;
        if (event.name === undefined) {
          this.model_.importWarning({
            type: 'object_parse_error',
            message: 'While processing ' + JSON.stringify(event) + ': ' +
                'Object events require an name parameter.'
          });
        }

        if (event.id === undefined) {
          this.model_.importWarning({
            type: 'object_parse_error',
            message: 'While processing ' + JSON.stringify(event) + ': ' +
                'Object events require an id parameter.'
          });
        }
        var process = thread.parent;
        var ts = timestampFromUs(event.ts);
        var instance;
        if (event.ph === 'N') {
          try {
            instance = process.objects.idWasCreated(
                event.id, event.cat, event.name, ts);
          } catch (e) {
            this.model_.importWarning({
              type: 'object_parse_error',
              message: 'While processing create of ' +
                  event.id + ' at ts=' + ts + ': ' + e
            });
            return;
          }
        } else if (event.ph === 'O') {
          if (event.args.snapshot === undefined) {
            this.model_.importWarning({
              type: 'object_parse_error',
              message: 'While processing ' + event.id + ' at ts=' + ts + ': ' +
                  'Snapshots must have args: {snapshot: ...}'
            });
            return;
          }
          var snapshot;
          try {
            var args = this.deepCopyIfNeeded_(event.args.snapshot);
            var cat;
            if (args.cat) {
              cat = args.cat;
              delete args.cat;
            } else {
              cat = event.cat;
            }

            var baseTypename;
            if (args.base_type) {
              baseTypename = args.base_type;
              delete args.base_type;
            } else {
              baseTypename = undefined;
            }
            snapshot = process.objects.addSnapshot(
                event.id, cat, event.name, ts,
                args, baseTypename);
            snapshot.snapshottedOnThread = thread;
          } catch (e) {
            this.model_.importWarning({
              type: 'object_parse_error',
              message: 'While processing snapshot of ' +
                  event.id + ' at ts=' + ts + ': ' + e
            });
            return;
          }
          instance = snapshot.objectInstance;
        } else if (event.ph === 'D') {
          try {
            process.objects.idWasDeleted(event.id, event.cat, event.name, ts);
            var instanceMap = process.objects.getOrCreateInstanceMap_(event.id);
            instance = instanceMap.lastInstance;
          } catch (e) {
            this.model_.importWarning({
              type: 'object_parse_error',
              message: 'While processing delete of ' +
                  event.id + ' at ts=' + ts + ': ' + e
            });
            return;
          }
        }

        if (instance)
          instance.colorId = getEventColor(event, instance.typeName);
      }

      this.allObjectEvents_.sort(function(x, y) {
        var d = x.event.ts - y.event.ts;
        if (d != 0)
          return d;
        return x.sequenceNumber - y.sequenceNumber;
      });

      var allObjectEvents = this.allObjectEvents_;
      for (var i = 0; i < allObjectEvents.length; i++) {
        var objectEventState = allObjectEvents[i];
        try {
          processEvent.call(this, objectEventState);
        } catch (e) {
          this.model_.importWarning({
            type: 'object_parse_error',
            message: e.message
          });
        }
      }
    }
662581
def _parse_line(self, line):
        
        # first isolate the timestamp and the event type
        try:
            self._line_parsed = self._line_parsed + 1

            m = RE_LINE_REG.match(line)
            if m is None:
                m = RE_LINE_EXT.match(line)
            if m is None:
                return False
            self.log.debug("Matching line found %s" % line)
            (tstamp, event_type, remainder) = m.groups()
            tstamp = int(tstamp)

            # skip passive checks reports by default for spamminess
            if event_type == 'PASSIVE SERVICE CHECK' and not self.passive_checks:
                return False
            # then retrieve the event format for each specific event type
            fields = EVENT_FIELDS.get(event_type, None)
            if fields is None:
                self.log.warning("Ignoring unknown nagios event for line: %s" % (line[:-1]))
                return False
            elif fields is False:
                # Ignore and skip
                self.log.debug("Ignoring Nagios event for line: %s" % (line[:-1]))
                return False

            # and parse the rest of the line
            parts = [p.strip() for p in remainder.split(';')]
            # Chop parts we don't recognize
            parts = parts[: len(fields._fields)]

            event = self.create_event(tstamp, event_type, self.hostname, fields._make(parts), tags=self.tags)

            self._event(event)
            self.log.debug("Nagios event: %s" % (event))

            return True
        except Exception:
            self.log.exception("Unable to create a nagios event from line: [%s]" % (line))
            return False
738367
function decode(events) {
  let indexList = [];
  let eventsByte = parseInt(events, 16);

  if(eventsByte & APPEARANCE_MASK) {
    indexList.push(APPEARANCE);
  }
  if(eventsByte & DISPLACEMENT_MASK) {
    indexList.push(DISPLACEMENT);
  }
  if(eventsByte & PACKETS_MASK) {
    indexList.push(PACKETS);
  }
  if(eventsByte & KEEPALIVE_MASK) {
    indexList.push(KEEPALIVE);
  }
  if(eventsByte & DISAPPEARANCE_MASK) {
    indexList.push(DISAPPEARANCE);
  }

  return indexList;
}
294372
def _gather_buffers(self, event: Message):
        
        if isinstance(event, BytesMessage):
            buf = self._byte_buffer
        else:
            buf = self._string_buffer

        # yay for code shortening
        buf.write(event.data)
        buf.seek(0)
        data = buf.read()
        buf.seek(0)
        buf.truncate()
        return data
451178
def extract_chunks(blob):
    """"""
    chunks = []
    stream = BytesIO(blob.bytes)
    current_pos = stream.tell()
    stream.seek(0, 2)
    length = stream.tell()
    stream.seek(current_pos, 0)
    while stream.tell() < length:
        chunks.append(read_chunk(stream))

    return chunks
130008
function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var events = EventPluginHub_1.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
    runEventQueueInBatch(events);
  }