Skip to content

Instantly share code, notes, and snippets.

@carande
Created May 25, 2016 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carande/beec390e639274035b7c510bf3261397 to your computer and use it in GitHub Desktop.
Save carande/beec390e639274035b7c510bf3261397 to your computer and use it in GitHub Desktop.
from socketIO_client import SocketIO
import json
SOCKET_HOST = 'https://brand.nioinstances.com'
class RunningAverage:
"""
Keeps a running average of some grocery type (eg, fruit)
"""
def __init__(self):
self.cart_count = 0
self.fruit_average = 0
print "initialized a new running average counter"
def add_cart(self, message, *args):
# create a cart, and count its total number of fruits
cart_fruits = Cart(message).getByType('fruit')
self.cart_count += 1
# update running total of fruits
self.fruit_average = (1./self.cart_count)*((self.fruit_average * (self.cart_count-1))+cart_fruits)
print "current fruit average: ", self.fruit_average
class Cart:
"""A cart that knows how to count its own objects"""
def __init__(self, message):
self.json = json.loads(message)
def getByType(self, type):
# count all of the given type in the cart
subtotal = 0
for item in self.json['cart']:
if item['type']==type:
subtotal += item['quantity']
return subtotal
ra = RunningAverage()
with SocketIO(SOCKET_HOST) as sock:
# Set up our message handler
sock.on('recvData', ra.add_cart)
# Join the "fruits" room
sock.emit('ready', 'groceries')
# Wait for messages to come through! Ctrl-C to quit
sock.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment