The Jquery fullcalendar app requires a JSON news feed, so this function
    creates the feed from upcoming PrivateEvent objects
483429
def json_event_feed(request,location_id=None,room_id=None):
    '''
    
    '''

    if not getConstant('calendar__privateCalendarFeedEnabled') or not request.user.is_staff:
        return JsonResponse({})
    this_user = request.user

    startDate = request.GET.get('start','')
    endDate = request.GET.get('end','')
    timeZone = request.GET.get('timezone',getattr(settings,'TIME_ZONE','UTC'))

    time_filter_dict_events = {}
    if startDate:
        time_filter_dict_events['startTime__gte'] = ensure_timezone(datetime.strptime(startDate,'%Y-%m-%d'))
    if endDate:
        time_filter_dict_events['endTime__lte'] = ensure_timezone(datetime.strptime(endDate,'%Y-%m-%d')) + timedelta(days=1)

    instructor_groups = list(this_user.groups.all().values_list('id',flat=True))

    filters = Q(event__privateevent__isnull=False) & (
        Q(event__privateevent__displayToGroup__in=instructor_groups) |
        Q(event__privateevent__displayToUsers=this_user) |
        (Q(event__privateevent__displayToGroup__isnull=True) & Q(event__privateevent__displayToUsers__isnull=True))
    )

    if location_id:
        filters = filters & Q(event__location__id=location_id)
    if room_id:
        filters = filters & Q(event__room_id=room_id)

    occurrences = EventOccurrence.objects.filter(filters).filter(**time_filter_dict_events).order_by('-startTime')

    eventlist = [EventFeedItem(x,timeZone=timeZone).__dict__ for x in occurrences]

    return JsonResponse(eventlist,safe=False)
958911
function requestJson(method, url, successCallback, failureCallback) {
    successCallback = successCallback || console.log;
    failureCallback = failureCallback || console.error || console.warn || console.log;
    var xhr = (typeof XDomainRequest !== 'undefined') ?
      (new XDomainRequest()) :
      (new XMLHttpRequest());
    xhr.onreadystatechange = function (event) {
      if (event.target.readyState === 4) {
        /* parse response as JSON */
        var responseJson;
        try { responseJson = window.JSON.parse(event.target.response); }
        catch (exception) { return failureCallback(event.target.response, exception); }
        /* perform callback according to HTTP status code */
        if (xhr.status > 0 && xhr.status < 400) {
          return successCallback(responseJson);
        } else {
          return failureCallback(responseJson);
        }
      }
    };
    xhr.open(method, url, true);
    xhr.send();
  }
861741
public String createEventJson(HttpServletRequest request,
                                  HttpServletResponse response,
                                  String tenant,
                                  String userLogin,
                                  String userKey) {
        try {
            String requestBody = getRequestContent(request);
            String responseBody = getResponseContent(response);

            Instant startDate = Instant.ofEpochMilli(System.currentTimeMillis() - MdcUtils.getExecTimeMs());

            Map<String, Object> data = new LinkedHashMap<>();
            data.put("rid", MdcUtils.getRid());
            data.put("login", userLogin);
            data.put("userKey", userKey);
            data.put("tenant", tenant);
            data.put("msName", appName);
            data.put("operationName", getResourceName(request.getRequestURI())
                + " " + getOperation(request.getMethod()));
            data.put("operationUrl", request.getRequestURI());
            data.put("operationQueryString", request.getQueryString());
            data.put("startDate", startDate.toString());
            data.put("httpMethod", request.getMethod());
            data.put("requestBody", maskContent(requestBody, request.getRequestURI(), true, request.getMethod()));
            data.put("requestLength", requestBody.length());
            data.put("responseBody", maskContent(responseBody, request.getRequestURI(), false, request.getMethod()));
            data.put("responseLength", responseBody.length());
            data.put("requestHeaders", getRequestHeaders(request));
            data.put("responseHeaders", getResponseHeaders(response));
            data.put("httpStatusCode", response.getStatus());
            data.put("channelType", "HTTP");
            data.put("entityId", getEntityField(responseBody, "id"));
            data.put("entityKey", getEntityField(responseBody, "key"));
            data.put("entityTypeKey", getEntityField(responseBody, "typeKey"));
            data.put("execTime", MdcUtils.getExecTimeMs());

            return mapper.writeValueAsString(data);
        } catch (Exception e) {
            log.warn("Error creating timeline event", e);
        }
        return null;
    }
1184980
function() {

        var me = this,
            strEvent = "Event",
            CE = YAHOO.util.CustomEvent;

        /**
        * Proxy subscriber to subscribe to the CalendarGroup's child Calendars' CustomEvents
        * @method sub
        * @private
        * @param {Function} fn The function to subscribe to this CustomEvent
        * @param {Object} obj The CustomEvent's scope object
        * @param {Boolean} bOverride Whether or not to apply scope correction
        */
        var sub = function(fn, obj, bOverride) {
            for (var p=0;p<me.pages.length;++p) {
                var cal = me.pages[p];
                cal[this.type + strEvent].subscribe(fn, obj, bOverride);
            }
        };

        /**
        * Proxy unsubscriber to unsubscribe from the CalendarGroup's child Calendars' CustomEvents
        * @method unsub
        * @private
        * @param {Function} fn The function to subscribe to this CustomEvent
        * @param {Object} obj The CustomEvent's scope object
        */
        var unsub = function(fn, obj) {
            for (var p=0;p<me.pages.length;++p) {
                var cal = me.pages[p];
                cal[this.type + strEvent].unsubscribe(fn, obj);
            }
        };

        var defEvents = Calendar._EVENT_TYPES;

        /**
        * Fired before a date selection is made
        * @event beforeSelectEvent
        */
        me.beforeSelectEvent = new CE(defEvents.BEFORE_SELECT);
        me.beforeSelectEvent.subscribe = sub; me.beforeSelectEvent.unsubscribe = unsub;

        /**
        * Fired when a date selection is made
        * @event selectEvent
        * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD].
        */
        me.selectEvent = new CE(defEvents.SELECT); 
        me.selectEvent.subscribe = sub; me.selectEvent.unsubscribe = unsub;

        /**
        * Fired before a date or set of dates is deselected
        * @event beforeDeselectEvent
        */
        me.beforeDeselectEvent = new CE(defEvents.BEFORE_DESELECT); 
        me.beforeDeselectEvent.subscribe = sub; me.beforeDeselectEvent.unsubscribe = unsub;

        /**
        * Fired when a date or set of dates has been deselected
        * @event deselectEvent
        * @param {Array} Array of Date field arrays in the format [YYYY, MM, DD].
        */
        me.deselectEvent = new CE(defEvents.DESELECT); 
        me.deselectEvent.subscribe = sub; me.deselectEvent.unsubscribe = unsub;
        
        /**
        * Fired when the Calendar page is changed
        * @event changePageEvent
        */
        me.changePageEvent = new CE(defEvents.CHANGE_PAGE); 
        me.changePageEvent.subscribe = sub; me.changePageEvent.unsubscribe = unsub;

        /**
        * Fired before the Calendar is rendered
        * @event beforeRenderEvent
        */
        me.beforeRenderEvent = new CE(defEvents.BEFORE_RENDER);
        me.beforeRenderEvent.subscribe = sub; me.beforeRenderEvent.unsubscribe = unsub;
    
        /**
        * Fired when the Calendar is rendered
        * @event renderEvent
        */
        me.renderEvent = new CE(defEvents.RENDER);
        me.renderEvent.subscribe = sub; me.renderEvent.unsubscribe = unsub;
    
        /**
        * Fired when the Calendar is reset
        * @event resetEvent
        */
        me.resetEvent = new CE(defEvents.RESET); 
        me.resetEvent.subscribe = sub; me.resetEvent.unsubscribe = unsub;
    
        /**
        * Fired when the Calendar is cleared
        * @event clearEvent
        */
        me.clearEvent = new CE(defEvents.CLEAR);
        me.clearEvent.subscribe = sub; me.clearEvent.unsubscribe = unsub;

        /**
        * Fired just before the CalendarGroup is to be shown
        * @event beforeShowEvent
        */
        me.beforeShowEvent = new CE(defEvents.BEFORE_SHOW);
    
        /**
        * Fired after the CalendarGroup is shown
        * @event showEvent
        */
        me.showEvent = new CE(defEvents.SHOW);
    
        /**
        * Fired just before the CalendarGroup is to be hidden
        * @event beforeHideEvent
        */
        me.beforeHideEvent = new CE(defEvents.BEFORE_HIDE);
    
        /**
        * Fired after the CalendarGroup is hidden
        * @event hideEvent
        */
        me.hideEvent = new CE(defEvents.HIDE);

        /**
        * Fired just before the CalendarNavigator is to be shown
        * @event beforeShowNavEvent
        */
        me.beforeShowNavEvent = new CE(defEvents.BEFORE_SHOW_NAV);
    
        /**
        * Fired after the CalendarNavigator is shown
        * @event showNavEvent
        */
        me.showNavEvent = new CE(defEvents.SHOW_NAV);
    
        /**
        * Fired just before the CalendarNavigator is to be hidden
        * @event beforeHideNavEvent
        */
        me.beforeHideNavEvent = new CE(defEvents.BEFORE_HIDE_NAV);

        /**
        * Fired after the CalendarNavigator is hidden
        * @event hideNavEvent
        */
        me.hideNavEvent = new CE(defEvents.HIDE_NAV);

        /**
        * Fired just before the CalendarNavigator is to be rendered
        * @event beforeRenderNavEvent
        */
        me.beforeRenderNavEvent = new CE(defEvents.BEFORE_RENDER_NAV);

        /**
        * Fired after the CalendarNavigator is rendered
        * @event renderNavEvent
        */
        me.renderNavEvent = new CE(defEvents.RENDER_NAV);

        /**
        * Fired just before the CalendarGroup is to be destroyed
        * @event beforeDestroyEvent
        */
        me.beforeDestroyEvent = new CE(defEvents.BEFORE_DESTROY);

        /**
        * Fired after the CalendarGroup is destroyed. This event should be used
        * for notification only. When this event is fired, important CalendarGroup instance
        * properties, dom references and event listeners have already been 
        * removed/dereferenced, and hence the CalendarGroup instance is not in a usable 
        * state.
        *
        * @event destroyEvent
        */
        me.destroyEvent = new CE(defEvents.DESTROY);
    }
1361848
function createEventSource(webhook, options)
{
  var self = this

  var eventSource = new EventSource(webhook, options)

  eventSource.addEventListener('open', this.emit.bind(this, 'open', webhook))
  eventSource.addEventListener('message', function(message)
  {
    self.push(message.data)
  })

  return eventSource
}
689275
function parseCreateAlertRequest(req){

  var reqObj = {};
  reqObj.originalUrl = req.originalUrl;
  reqObj.alertName = req.body.alertName;
  reqObj.emails = req.body.emails;
  reqObj.eventCategories = req.body.eventCategories.split(',');
  reqObj.eventNames = req.body.eventNames.split(',');
  reqObj.eventSeverities = req.body.eventSeverities.split(',');
  reqObj.uid = req.body.uid;
  reqObj.env = req.body.env;
  reqObj.alertEnabled = req.body.enabled;
  reqObj._id = new Mongoose.Types.ObjectId();
  reqObj.domain = req.params.domain;
  return reqObj;
}
1295370
function watchedEvents(obj) {
  var listeners = meta(obj, false).listeners, ret = [];

  if (listeners) {
    for(var eventName in listeners) {
      if (!SKIP_PROPERTIES[eventName] && listeners[eventName]) {
        ret.push(eventName);
      }
    }
  }
  return ret;
}
5138
function CalendarMonthCtrl($element, $scope, $animate, $q,
    $$mdDateUtil, $mdDateLocale) {

    /** @final {!angular.JQLite} */
    this.$element = $element;

    /** @final {!angular.Scope} */
    this.$scope = $scope;

    /** @final {!angular.$animate} */
    this.$animate = $animate;

    /** @final {!angular.$q} */
    this.$q = $q;

    /** @final */
    this.dateUtil = $$mdDateUtil;

    /** @final */
    this.dateLocale = $mdDateLocale;

    /** @final {HTMLElement} */
    this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');

    /** @type {boolean} */
    this.isInitialized = false;

    /** @type {boolean} */
    this.isMonthTransitionInProgress = false;

    var self = this;

    /**
     * Handles a click event on a date cell.
     * Created here so that every cell can use the same function instance.
     * @this {HTMLTableCellElement} The cell that was clicked.
     */
    this.cellClickHandler = function() {
      var timestamp = $$mdDateUtil.getTimestampFromNode(this);
      self.$scope.$apply(function() {
        self.calendarCtrl.setNgModelValue(timestamp);
      });
    };

    /**
     * Handles click events on the month headers. Switches
     * the calendar to the year view.
     * @this {HTMLTableCellElement} The cell that was clicked.
     */
    this.headerClickHandler = function() {
      self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this));
    };
  }
1006866
function() {

			// Remove any existing calendar (only one instance per node is allowed)
			var existing = this.el.one('.calendar')
			if (existing._node) {
				existing.remove()
			}

			this.calendarEl = n.node.create('<div class="calendar"></div>')

			var content = []

			for (var i=0;i<this.panes;i++) {
				var prevLink = ''
					, nextLink = ''

				if (i==0) {
					prevLink = '<span class="prev-month"><a href="#">&lt;</a></span>'
				}
				
				if (i+1 == this.panes) {
					nextLink = '<span class="next-month"><a href="#">&gt;</a></span>'
				}

				content = content.concat([
					'<div class="pane" data-month="', this.getOffsetMonth(i) ,'" data-year="', this.getOffsetYear(i), '">',
						'<div class="months">',
							prevLink,
							'<span class="current-month">' + this.renderMonth(i) + ' ' + this.renderYear(i) + '</span>',
							nextLink,
						'</div>',
						'<div class="days">',
							'<table><thead><tr class="weekdays">' + this.weekdayHeaderMarkup() + '</tr></thead>',
								'<tbody>' + this.calendarMarkup(i) + '</tbody>',
							'</table>',
						'</div>',
					'</div>'
				])
			}

			this.calendarEl.setHtml(content.join(''))

			// Position the calendar
			this.calendarEl.appendTo(this.el)

			this.doSelection()

			this.calendarEl.one('.prev-month').on('click', function(e){
				this.month--
				this.loadMonth()
				e.stop()
			}.bind(this))
	
			this.calendarEl.one('.next-month').on('click', function(e){
				this.month++
				this.loadMonth()
				e.stop()
			}.bind(this))
	
			this.calendarEl.on('click', function(e) {
				var dayNumber = parseInt(e.target.getHtml(), 10)
	
				if (isNaN(dayNumber)) {
					return
				}

				var paneEl = e.target.ancestor('.pane')

					, month = parseInt(paneEl.data('month'), 10)
					, year = parseInt(paneEl.data('year'), 10)

					, dateObj = new Date(year, month, dayNumber).getTime()
					, self = this

				function getdPickedDayEl() {
					return self.el.one('.pane[data-month="' + month + '"]').one('td[data-day="' + dayNumber + '"]')
				}

				// Handle single selection
				if (this.mode == 'single') {
					this.selected = [{year:year, month:month, day:dayNumber}]
					this.doSelection()
				}

				// Handle multiple selections
				if (this.mode == 'multiple') {

					if (this.selected.length > 1) {
						// Reset all nodes
						this.selected = [{year:year, month:month, day:dayNumber}]

					} else if (this.selected.length == 1 && this.selected[0].month == month && this.selected[0].year == year && this.selected[0].day == dayNumber ){
						// If the clicked square is the one in the selection, just clear the selection
						this.selected = []
						this.el.fire('pickClear')

					} else if (this.selected.length == 1){

						// Populate the selected array
						var dayI = this.selected[0].day+1,
							monthI = this.selected[0].month,
							yearI = this.selected[0].year

						// Swap values if the clicked day is before the start date
						if (dayI-1 > dayNumber || (monthI > month || yearI > year)) {
							var temp = {year:year, month:month, day:dayNumber}

							dayNumber = dayI-1
							month = monthI
							year = yearI
							
							this.selected = [temp]
							dayI = temp.day
							monthI = temp.month
							yearI = temp.year
						}


						while(true) {

							this.selected.push({year:yearI, month:monthI, day:dayI})

							if (dayI >= dayNumber && monthI >= month && yearI >= year) { break }

							if (dayI >= this.daysInMonth[monthI]) {
								dayI=0
								monthI++
							}
							if (monthI==11) {
								monthI=0
								yearI++
							}
							dayI++
						}

						this.el.fire('rangePick', {
							from: this.selected[0],
							to: {
								year: year,
								month: month,
								day: dayNumber
							}
						})

					} else {
						// First selection, so push something onto the selection stack
						this.selected.push({year:year, month:month, day:dayNumber})
					}

					this.doSelection()
				}

				this.el.fire('pick', {
					year: year,
					month: month,
					day: dayNumber,
					formatted: this.format(dateObj),
					date: dateObj
				})
				e.stop()
			}.bind(this))
		}
773706
function () {
                this.$assert(859, this._listenersStopped === true);
                this._listenersStopped = false;
                var bindings = this._bindings;
                if (bindings) {
                    for (var index = 0, bind; bind = bindings[index]; index++) {
                        this.__json.addListener(bind.inside, bind.to, bind.callback, true, bind.recursive);
                    }
                }
            }
1301660
function getJSONP(url, options) {
  return new Promise(function (resolve, reject) {
    if (!url) {
      reject(new Error('No request url'));
    }

    var _ref = options || {};

    var _ref$params = _ref.params;
    var params = _ref$params === undefined ? {} : _ref$params;
    var _ref$timeout = _ref.timeout;
    var timeout = _ref$timeout === undefined ? 15000 : _ref$timeout;
    // the funtion name of callback function

    var name = void 0;
    var timer = void 0;
    var requestUrl = parseUrl(url, params);
    // check whether the callbacl name has been defined
    var match = /callback=(\w+)/.exec(requestUrl);

    if (match && match[1]) {
      name = match[1];
    } else {
      // generate a random function name if no callback name was defined
      // return a function name generated by timestamp and random number
      // eg: jsonp_1355750852040_8260732076596469
      name = 'jsonp_' + getNow() + '_' + getRandomNumber();
      requestUrl += '&callback=' + name;
    }

    // create a script element
    var script = document.createElement('script');
    script.type = 'text/javascript';
    // set the request url
    script.src = requestUrl;
    // set the id of dom node which can be used to find this node
    script.id = 'id_' + name;

    var cleanUp = function cleanUp() {
      // exec callback and remove the callback
      window[name] = undefined;
      // get the script node
      var elem = document.getElementById('id_' + name);
      // remove added script node
      removeElement(elem);

      if (timer) {
        clearTimeout(timer);
      }
    };

    if (timeout) {
      timer = setTimeout(function () {
        cleanUp();
        reject(new Error('Timeout'));
      }, timeout);
    }

    // the callback when request finish
    window[name] = function (json) {
      cleanUp();
      // exec callback
      resolve(json);
    };

    // add script node in head
    var head = document.getElementsByTagName('head');

    if (head && head[0]) {
      head[0].appendChild(script);
    }
  });
}
1330355
function (evt, callback) {
    if (!evt || !_.isObject(evt)) {
      var err = new Error('Please pass a valid event!');
      debug(err);
      throw err;
    }

    if (!callback || !_.isFunction(callback)) {
      var err = new Error('Please pass a valid callback!');
      debug(err);
      throw err;
    }

    var target = this.getTargetInformation(evt);

    var viewBuilders = this.tree.getViewBuilders(target);

    var errs = [];
    var notifications = [];

    var foundPrioSet = _.find(viewBuilders, function (vb) {
      return vb.priority < Infinity;
    });

    var eachMethod = 'each';
    if (foundPrioSet) {
      eachMethod = 'eachSeries';
    }

    async[eachMethod].call(async, viewBuilders, function (viewBuilder, callback) {
      viewBuilder.denormalize(evt, function (err, notis) {
        if (err) {
          debug(err);
          if (!errs.push) {
            var warn = new Error('ATTENTION! Already called back!');
            debug(warn);
            console.log(warn.stack);
            return;
          }
          errs.push(err);
        }

        if (notis && notis.length > 0) {
          notifications = notifications.concat(notis);
        }
        callback(null);
      });
    }, function () {
      if (errs.length === 0) {
        errs = null;
      }
      callback(errs, _.filter(notifications, function (n) { return !!n; }));
    });
  }
1373026
function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
		var callbackContext = origSettings && origSettings.context || requestSettings;
		var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);

		// Replace the =? sequence both in the query string and the data
		if ( requestSettings.data ) {
			requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
		}

		requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");


		// Handle JSONP-style loading
		window[ jsonp ] = window[ jsonp ] || function( tmp ) {
			data = tmp;
			jsonpSuccess( requestSettings, callbackContext, mockHandler );
			jsonpComplete( requestSettings, callbackContext, mockHandler );
			// Garbage collect
			window[ jsonp ] = undefined;

			try {
				delete window[ jsonp ];
			} catch(e) {}

			if ( head ) {
				head.removeChild( script );
			}
		};
	}
72220
function registerCurrentItemEvents (params) {
          // Destructuring:
          var item = params.item;
          var $ul = params.$ul;
          var $li = params.$li;
          var $scope = params.$scope;
          var modelValue = params.modelValue;
          var level = params.level;
          var event = params.event;
          var text = params.text;
          var nestedMenu = params.nestedMenu;
          var enabled = params.enabled;
          var orientation = String(params.orientation).toLowerCase();
          var customClass = params.customClass;

          if (enabled) {
            var openNestedMenu = function ($event) {
              removeContextMenus(level + 1);
              /*
               * The object here needs to be constructed and filled with data
               * on an "as needed" basis. Copying the data from event directly
               * or cloning the event results in unpredictable behavior.
               */
              /// adding the original event in the object to use the attributes of the mouse over event in the promises
              var ev = {
                pageX: orientation === 'left' ? event.pageX - $ul[0].offsetWidth + 1 : event.pageX + $ul[0].offsetWidth - 1,
                pageY: $ul[0].offsetTop + $li[0].offsetTop - 3,
                // eslint-disable-next-line angular/window-service
                view: event.view || window,
                target: event.target,
                event: $event
              };

              /*
               * At this point, nestedMenu can only either be an Array or a promise.
               * Regardless, passing them to `when` makes the implementation singular.
               */
              $q.when(nestedMenu).then(function(promisedNestedMenu) {
                if (angular.isFunction(promisedNestedMenu)) {
                  //  support for dynamic subitems
                  promisedNestedMenu = promisedNestedMenu.call($scope, $scope, event, modelValue, text, $li);
                }
                var nestedParam = {
                  $scope : $scope,
                  event : ev,
                  options : promisedNestedMenu,
                  modelValue : modelValue,
                  level : level + 1,
                  orientation: orientation,
                  customClass: customClass
                };
                renderContextMenu(nestedParam);
              });
            };

            $li.on('click', function ($event) {
              if($event.which == 1) {
                $event.preventDefault();
                $scope.$apply(function () {

                  var cleanupFunction = function () {
                    $(event.currentTarget).removeClass('context');
                    removeAllContextMenus();
                  };
                  var clickFunction = angular.isFunction(item.click)
                    ? item.click
                    : (angular.isFunction(item[1])
                      ? item[1]
                      : null);

                  if (clickFunction) {
                    var res = clickFunction.call($scope, $scope, event, modelValue, text, $li);
                    if(res === undefined || res) {
                      cleanupFunction();
                    }
                  } else {
                    cleanupFunction();
                  }
                });
              }
            });

            $li.on('mouseover', function ($event) {
              $scope.$apply(function () {
                if (nestedMenu) {
                  openNestedMenu($event);
                } else {
                  removeContextMenus(level + 1);
                }
              });
            });
          } else {
            setElementDisabled($li);
          }
        }
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
          });
        }
      }
    }
883038
function Event(type) {
      var event = this;
      if (type instanceof Event) {
        return type;
      }
      return (event instanceof Event)
        ? _.assign(event, { 'timeStamp': _.now() }, typeof type == 'string' ? { 'type': type } : type)
        : new Event(type);
    }
320502
function eventSpyBefore(eventType) {
                    /* jshint validthis: true */
                    var path = phantomas.getDOMPath(this);
                    //phantomas.log('DOM event: "' + eventType + '" bound to "' + path + '"');

                    phantomas.incrMetric('eventsBound');
                    phantomas.addOffender('eventsBound', '"%s" bound to "%s"', eventType, path);
                    phantomas.log('event ' + eventType + ' bound');

                    phantomas.enterContext({
                        type: 'addEventListener',
                        callDetails: {
                            context: {
                                length: 1,
                                elements: [path]
                            },
                            arguments: [eventType]
                        },
                        backtrace: phantomas.getBacktrace()
                    });

                    // count window.addEventListener('scroll', ...) - issue #508
                    if (eventType === 'scroll' && (path === 'window' || path === '#document')) {
                        phantomas.incrMetric('eventsScrollBound');
                        phantomas.addOffender('eventsScrollBound', 'bound by %s on %s', phantomas.getBacktrace(), path);
                    }
                }