Convert event hash to packet

 === Parameters
 event(Hash):: Event to be converted

 === Return
 (Push|Request):: Packet
173370
def event_to_packet(event)
      packet = nil
      case event[:type]
      when "Push"
        packet = RightScale::Push.new(event[:path], event[:data], {:from => event[:from], :token => event[:uuid]})
        packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at)
        packet.skewed_by = event[:skewed_by].to_i if event.has_key?(:skewed_by)
      when "Request"
        options = {:from => event[:from], :token => event[:uuid], :reply_to => event[:reply_to], :tries => event[:tries]}
        packet = RightScale::Request.new(event[:path], event[:data], options)
        packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at)
        packet.skewed_by = event[:skewed_by].to_i if event.has_key?(:skewed_by)
      end
      packet
    end
1103663
def connection_event(event, *args)
    return unless @connection_event_handlers.keys.include?(event)
    @connection_event_handlers[event].each { |h| h.call(self, *args) }
  end
40278
def packet_in_handler(self, evt):
        """"""
        req_pkt = packet.Packet(evt.msg.data)
        if slow.lacp in req_pkt:
            (req_lacp, ) = req_pkt.get_protocols(slow.lacp)
            (req_eth, ) = req_pkt.get_protocols(ethernet.ethernet)
            self._do_lacp(req_lacp, req_eth.src, evt.msg)
        else:
            self.send_event_to_observers(EventPacketIn(evt.msg))
1311171
function onHashChange(event) {
    // https://github.com/devote/HTML5-History-API/issues/46
    var fireNow = lastURL;
    // new value to lastURL
    lastURL = windowLocation.href;
    // if not empty fireNow, otherwise skipped the current handler event
    if (fireNow) {
      // if checkUrlForPopState equal current url, this means that the event was raised popstate browser
      if (checkUrlForPopState !== windowLocation.href) {
        // otherwise,
        // the browser does not support popstate event or just does not run the event by changing the hash.
        firePopState();
      }
      // current event object
      event = event || global.event;

      var oldURLObject = parseURL(fireNow, true);
      var newURLObject = parseURL();
      // HTML4 browser not support properties oldURL/newURL
      if (!event.oldURL) {
        event.oldURL = oldURLObject._href;
        event.newURL = newURLObject._href;
      }
      if (oldURLObject._hash !== newURLObject._hash) {
        // if current hash not equal previous hash
        dispatchEvent(event);
      }
    }
  }
1078176
def post_events(self, events):

        

        url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
                                                   self.project_id)
        headers = utilities.headers(self.write_key)
        payload = json.dumps(events)
        response = self.fulfill(HTTPMethods.POST, url, data=payload, headers=headers, timeout=self.post_timeout)
        self._error_handling(response)
        return self._get_response_json(response)
1061526
def PushEvent(self, event):
    
    event_string = event.GetAttributeValuesString()
    heap_values = (event.timestamp, event.timestamp_desc, event_string, event)
    heapq.heappush(self._heap, heap_values)
557032
def to_hash
      h = super
      h['timed_stats'] = @timed_stats.to_hash
      h['value_stats'] = @value_stats.to_hash( Stats::STATS - %w[ rate ] )
      h['rate'] = self.rate
      h['unit_count'] = self.unit_count
      return h
    end
1276297
def process(self, event):
        
        uid = str(uuid.uuid4())
        hostname = os.environ.get('VENT_HOST')
        if not hostname:
            hostname = ''

        try:
            # TODO should directories be treated as bulk paths to send to a
            #      plugin?
            if not event.is_directory:
                spath = event.src_path
                # wait for long copies to finish
                historicalSize = -1
                while (historicalSize != os.path.getsize(spath)):
                    historicalSize = os.path.getsize(spath)
                    time.sleep(0.1)

                if os.path.getsize(spath) == 0:
                    spath = str(spath)
                    print('file drop ignoring empty file: {0}'.format(spath))
                    if spath.startswith('/files/trace_'):
                        key = spath.split('_')[1]
                        # Rabbit settings
                        exchange = 'topic-poseidon-internal'
                        exchange_type = 'topic'
                        routing_key = 'poseidon.algos.decider'

                        message = {}
                        message[key] = {'valid': False, 'source': 'file_drop'}
                        message = json.dumps(message)

                        # Send Rabbit message
                        try:
                            connection = pika.BlockingConnection(
                                pika.ConnectionParameters(host='rabbit')
                            )

                            channel = connection.channel()
                            channel.exchange_declare(
                                exchange=exchange, exchange_type=exchange_type
                            )
                            channel.basic_publish(exchange=exchange,
                                                  routing_key=routing_key,
                                                  body=message)
                            connection.close()
                        except Exception as e:
                            print('failed to send rabbit message because: ' +
                                  str(e))

                    return

                # check if the file was already queued and ignore
                exists = False
                print(uid + ' started ' + spath)
                jobs = self.r.keys(pattern='rq:job*')
                for job in jobs:
                    print(uid + ' ***')
                    description = self.r.hget(
                        job, 'description').decode('utf-8')
                    print(uid + ' ' + description)
                    if description.startswith("watch.file_queue('"):
                        print(uid + ' ' +
                              description.split("watch.file_queue('" +
                                                hostname + '_')[1][:-2])
                        print(uid + ' ' + spath)
                        if description.split("watch.file_queue('" +
                                             hostname +
                                             '_')[1][:-2] == spath:
                            print(uid + ' true')
                            exists = True
                    elif description.startswith("watch.gpu_queue('"):
                        print(uid + ' ' +
                              description.split('"file": "')[1].split('"')[0])
                        print(uid + ' ' + spath)
                        if description.split('"file": "')[1].split('"')[0] == spath:
                            print(uid + ' true')
                            exists = True
                    print(uid + ' ***')

                if not exists:
                    # !! TODO this should be a configuration option in the
                    #         vent.template
                    print(uid + " let's queue it " + spath)
                    # let jobs be queued for up to 30 days
                    self.q.enqueue('watch.file_queue',
                                   hostname + '_' + spath,
                                   ttl=2592000)
                print(uid + ' end ' + spath)
        except Exception as e:  # pragma: no cover
            print('file drop error: ' + str(e))
57841
def to_protocol(params)
      pcl = CaTissue::CollectionProtocol.new(params)
      unless pcl.find then
        raise ScatError.new("Protocol not found: #{pcl.title}")
      end
      pcl
    end
695187
def save_event(event)
      method = event.new_event? ? :post : :put
      body = event.use_quickadd? ? nil : event.to_json
      notifications = "sendNotifications=#{event.send_notifications?}"
      query_string =  if event.use_quickadd?
                        "/quickAdd?#{notifications}&text=#{event.title}"
                      elsif event.new_event?
                        "?#{notifications}"
                      else # update existing event.
                        "/#{event.id}?#{notifications}"
                      end

      send_events_request(query_string, method, body)
    end
29706
def serialize_me(self, arn, event_time, tech, item=None):
        
        payload = {
            'arn': arn,
            'event_time': event_time,
            'tech': tech
        }

        if item:
            payload['item'] = item

        else:
            payload['event_too_big'] = True

        return self.dumps(payload).data.replace('<empty>', '')
62602
def convert_to_type(data, return_type)
      return nil if data.nil?
      case return_type
      when 'String'
        data.to_s
      when 'Integer'
        data.to_i
      when 'Float'
        data.to_f
      when 'BOOLEAN'
        data == true
      when 'DateTime'
        # parse date time (expecting ISO 8601 format)
        DateTime.parse data
      when 'Date'
        # parse date time (expecting ISO 8601 format)
        Date.parse data
      when 'Object'
        # generic object (usually a Hash), return directly
        data
      when /\AArray<(.+)>\z/
        # e.g. Array<Pet>
        sub_type = $1
        data.map {|item| convert_to_type(item, sub_type) }
      when /\AHash\<String, (.+)\>\z/
        # e.g. Hash<String, Integer>
        sub_type = $1
        {}.tap do |hash|
          data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
        end
      when 'EventsResponse'
        Clever.const_get(return_type).new.tap do |model|
          resp = model.build_from_hash data
          resps = []
          data[:data].each do |eventResponse|
            singleResp = parse_event_response(eventResponse[:data])
            resps.push(singleResp)
          end
          resp.data = resps
          return resp
        end
      when 'EventResponse'
        parse_event_response data[:data]
      else
        # models, e.g. Pet
        Clever.const_get(return_type).new.tap do |model|
          model.build_from_hash data
        end
      end
    end
824323
function (event) {

	// check if connection object exists
	if (typeof event.conn === 'undefined') {
		LOG.error('no connection records, cannot respond to request', l_name);
		return false;
	}

	// if no mechanism to store (such as from a bot), just ignore
	// TODO: cleaner approach?
	if (event.conn.type !== 'socket' ||
    	event.conn.connector.queuedEvents === undefined) {
		return true;
	}

	var socket = event.conn.connector;

	// check if id exist
	if (socket.queuedEvents.hasOwnProperty(event.id) === false) {
		LOG.error('event not found. id = ' + event.id, l_name);
		LOG.stack();
		return false;
	}

	// remove current event from the socket's event queues
	delete socket.queuedEvents[event.id];

	return true;
}
1280869
def get_events(self):
        
        res = self.con.get('_events', wait=False)
        logger.debug("Got events from %s: %s", self.name, res)
        return unserialize(res, True)
945465
def emit(event, data = {}, channel = nil)
      message = { event: event, data: MultiJson.dump(data) }
      message[:channel] = channel if channel

      PusherFake.log("SEND #{id}: #{message}")

      socket.send(MultiJson.dump(message))
    end
593254
def send_event(properties)
      response = nil
      options = { use_ssl: true }
      Net::HTTP.start(@uri.host, @uri.port, options) do |http|
        request = Net::HTTP::Post.new(@uri, @header)
        request.body = { properties: properties }.to_json
        response = http.request request # Net::HTTPResponse object
      end
      response
    end
486583
def to_json(self):
        
        event_as_dict = copy.deepcopy(self.event_body)
        if self.timestamp:
            if "keen" in event_as_dict:
                event_as_dict["keen"]["timestamp"] = self.timestamp.isoformat()
            else:
                event_as_dict["keen"] = {"timestamp": self.timestamp.isoformat()}
        return json.dumps(event_as_dict)