예제 #1
0
파일: scrape.py 프로젝트: AlJohri/nulaundry
def save_statuses():
    while True:

        timestamp = int(time.time() * 1000)

        for machine_id, machine in scrape_machines().iteritems():

            last = firebase.get(url="/machines/%s/statuses" % machine_id, name=None) # params={"limitToLast": 1}
            last_array = sorted(last.values(), key=lambda x: x[0]) if last else []
            last_timestamp, last_status = last_array[-1] if last else ("", "")

            status = machine.pop('status')
            if status == "Out of service": continue

            if last_status != status:
                firebase.put(url='/machines/%s/statuses' % machine_id, name=timestamp, data=(timestamp, status), headers={'print': 'pretty'})
                firebase.put(url='/machines/%s' % machine_id, name='timestamp', data=timestamp, headers={'print': 'pretty'})
                firebase.put(url='/machines/%s' % machine_id, name='status', data=status, headers={'print': 'pretty'})
                print machine_id, t.red(last_status), "=>", t.green(status)

                if status == "Avail":

                    all_avails = [tm for tm,st in last_array[:-1] if st == "Avail" and tm < timestamp] if last else None

                    last_avail_timestamp = all_avails[-1] if all_avails else None
                    last_avail_timestamp_index = last_array.index([last_avail_timestamp, "Avail"]) if last_avail_timestamp else None
                    timestamp_after_last_avail = last_array[last_avail_timestamp_index + 1][0] if last_avail_timestamp_index else None

                    if timestamp_after_last_avail:
                        prev_num_runs = firebase.get(url='/machines/%s' % machine_id, name='num_runs', headers={'print': 'pretty'}) or 0
                        firebase.put(url='/machines/%s' % machine_id, name='num_runs', data=prev_num_runs+1, headers={'print': 'pretty'})
                        firebase.post(url='/machines/%s/runs' % machine_id, data=(timestamp_after_last_avail, timestamp), headers={'print': 'pretty'})
                        print machine_id, "Run Complete:", timestamp_after_last_avail, timestamp

        print "\nSleeping 10 seconds ...\n"
예제 #2
0
파일: app.py 프로젝트: hack101/lesson4
def submit_message():
  message = {
    'body': request.form['message'],
    'who': request.form['who']
  }
  firebase.post('/messages', message)
  return redirect(url_for('messages'))
예제 #3
0
파일: scrape.py 프로젝트: shoekla/PythC
def addVidHelp(link):
	links = eval(getResp("helpVids"))
	if link in links:
		return "Already in List"
	links.append(link)
	firebase.delete('helpVids',None)
	firebase.post("helpVids",str(links))
	return "Added"
예제 #4
0
파일: firePyth.py 프로젝트: shoekla/PythC
def addToRand(phrase):
	arr = eval(getResp('randomR'))
	if phrase not in arr:
		arr.append(phrase)
		firebase.delete('randomR',None)
		firebase.post('randomR',str(arr))
		return 'green'
	return 'red'
def regAttendee():
	form = forms.AttendeeRegistrationForm(request.form)
	if request.method == 'POST' and form.validate():
		firebase.post('/attendees', {'ClientId':form.clientId.data, 'Name':form.name.data, 'Email':form.email.data})
		flash('SUCCESSFUL: Thank you for registering.')
		return redirect('/attendees')
	return render_template("regAttendee.html",
		title = "Attendee Registration",
		type="Attendee", form=form)
def regClient():
	form = forms.ClientRegistrationForm(request.form)
	if request.method == 'POST' and form.validate():
		firebase.post('/clients', {'Id': getNewClientId(), 'Name':form.name.data, 'Email':form.email.data, 'Phone':form.phone.data,
		 'Street':form.street.data,'City':form.city.data,'State':form.state.data,'ZipCode':form.zipCode.data})
		flash('SUCCESSFUL: Thank you for registering.')
		return redirect('/clients')
	return render_template("regClient.html",
		title = "Client Registration",
		type="Client", form=form)
예제 #7
0
def removeComic(email,comic):
	print "Logging In"
	users = eval(getResp("Users"))
	b = eval(getResp("Comics"))
	for i in range(0,len(users)):
		if users[i] == email:
			if comic in b[i]:
				b[i].remove(comic)
	firebase.delete('Comics',None)
	firebase.post("Comics",str(b))
예제 #8
0
def compareTo(user_id, image_json):
	result = firebase.get('/user', user_id)

	for x in range(0, number_of_tries):
		if result['description'] == image_json['responses']['labelAnnotations']['description']:
			difference = abs(float(result['score']) - float(image_json['responses']['labelAnnotations']['score']))
			if difference < math.pow(10, -6):
				average_score = (float(result['score']) + float(image_json['responses']['labelAnnotations']['score']))/2
				firebase.post('/users', user_id, {'score': average_score}, result['description'])
				return True
	return False
예제 #9
0
def log():
  prevValue = 0
  while True:
    currentValue = GPIO.input(4)
    #aravind did this
    if (currentValue != prevValue):
      # get time and send to db
      status = "LOCKED" if currentValue else "UNLOCKED"
      now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
      firebase.post('/updates', {".value":status,".priority": now})
      prevValue = currentValue
예제 #10
0
def makeNote(typeF,contents):
  nNote=note(typeF,contents)
  #thoughtspace.firebase.io
  #make call to firebase
  note_id=1
  place={'x':0,'y':0,'z':0}
  contentDict={'type':typeF, 'content':contents, 'loc':place}
  firebase.post("/notes",contentDict )
  return render_template("newNote.html",
                          typef=nNote.getType(),
                          content=nNote.getContent())
예제 #11
0
파일: firePyth.py 프로젝트: shoekla/PythC
def putInFirebase(phrase,response):
	phrase = phrase.strip()
	if getResp(phrase) == None:
		firebase.post(phrase,response)
		keys = eval(getResp("Keys"))
		keys.append(phrase)
		firebase.delete("Keys",None)
		firebase.post("Keys",str(keys))
		incrementN()
		return 1
	else:
		print "Already In system"
		return 0
예제 #12
0
파일: firePyth.py 프로젝트: shoekla/PythC
def addUser(userName,password):
	userName = userName.strip()
	if getResp(userName) == None:
		firstArray = [userName,password,0,[]]
		firebase.post(userName,str(firstArray))
		users = eval(getResp("Users"))
		users.append(userName)
		firebase.delete("Users",None)
		firebase.post("Users",str(users))
		incrementN()
		return 1
	else:
		print "Already In system"
		return 0
예제 #13
0
파일: scrape.py 프로젝트: shoekla/PythC
def completeLess(lessonName,email):
	try:
		users = eval(getResp("Users"))
		userData = eval(getResp("UserData"))
		for i in range(0,len(users)):
			if users[i] == email:
				if lessonName in userData[i][0]:
					return "You already completed this lesson!"
				userData[i][0].append(lessonName)
				firebase.delete("UserData",None)
				firebase.post("UserData",str(userData))
				return "You have been awarded 10 points!"

	except:
		return "An Error Has Occured :("	
예제 #14
0
def upload_quiz(quiz_name):
    """Upload a quiz to the firebase repository."""
    try:
        quiz = open("quizzes/" + quiz_name + ".json", "r").read()
    except FileNotFoundError:
        print("Error: Quiz not found.")
        return

    try:
        url = '/quizzapp-299a2/Quizzes'
        firebase.post(url, json.loads(quiz))
    except requests.exceptions.ConnectionError:
        print("Quiz upload unsuccessful. Connection Error.")
        return
    print("Quiz uploaded successfully.")
예제 #15
0
파일: firePyth.py 프로젝트: shoekla/PythC
def incrementN():
	a = firebase.get("NumOfPhrases",None)
	print a
	keys = []
	count = 0
	for key in a:
		"""
		print "key: %s , value: %s" % (key, a[key])
		"""
		keys.append(key)
		count = count +1
	i = int(a[keys[count-1]])
	i = i+1
	firebase.delete('NumOfPhrases',None)
	firebase.post("NumOfPhrases",str(i))
예제 #16
0
파일: homeiot.py 프로젝트: furqanmk/Homeiot
def sync_lock_history():
    #try:
        global username
        history_path = username + '/lock' + '/history'
        with open('user/lock/history.json') as json_file:
            history_local = json.load(json_file)
            print username
            history_remote = firebase.get(history_path, None)
            print json.dumps(history_remote)
            
            if history_local != history_remote:
                for key in history_remote:
                    print json.dumps(history_remote[key])
            #test_unlock = {'username': '******', 'time': get_utc_time()}
            firebase.post(history_path, { get_time() : 'badar' })  
        return;
예제 #17
0
def createUser(robot_data, firebase_url):
	from firebase import firebase
	firebase = firebase.FirebaseApplication(firebase_url, None)
	users = firebase.get('/users', None)

	username_has_been_created = False
	if users is not None and len(users) > 0:
		for user in users.values():
			if user['username'] == robot_data['username']:
				username_has_been_created = True
				break

	# create a robot user if has not been created yet. 
	if username_has_been_created == False:
		print "creating robot user:", robot_data['username']
		usr_data = {
			'age': robot_data['age'],
			'gender': robot_data['gender'],
			'interest': robot_data['interest'], 
			'myAttendanceNumber': robot_data['myAttendanceNumber'],
			'myPostsNumber': robot_data['myPostsNumber'],
			'nickname': robot_data['nickname'],
			'password': robot_data['password'],
			'username': robot_data['username'],
			'usrProfileImage': robot_data['usrProfileImage'],
			'whatsup': robot_data['whatsup']
		}
		post_user = firebase.post('/users', usr_data)
		print post_user
	return robot_data
예제 #18
0
def WriteProgram(Program):
	try:
		r = firebase.delete('/','Program', params=Params)
		for P in Program:
			r = firebase.post('/Program', P, params=Params)
	except:
		logger.info('Error writing Program to Firebase')
예제 #19
0
파일: scrape.py 프로젝트: shoekla/PythC
def editUserData(name,nick,summary,pic,email,contact):
	try:
		users = eval(getResp("Users"))
		userData = eval(getResp("UserData"))
		for i in range(0,len(users)):
			if users[i] == email:
				print userData
				print "Change"	
				userData[i][1]=[str(name),str(nick),str(summary),str(pic),str(contact)]
				print userData
				firebase.delete("UserData",None)
				firebase.post("UserData",str(userData))
				return

	except:
		return
예제 #20
0
파일: views.py 프로젝트: jmb2547/5CHack
def save():
    try:
        beer_id = request.form.get("id")
        beer_rs = requests.get(BASE_URL + "beer/" + beer_id + "/?key=" + API_key)
        data = json.loads(beer_rs.content)
        
        result_attr = {
            "image": data['data']['labels']['large'],
            "name": data['data']['name'],
            "description": data['data']["description"],
            "ibu": data['data']['ibu'],
            "abv": data['data']['abv'],
            "id": data['data']['id'],
            "srmId": data['data']['srmId'],
            "styleId": data['data']['styleId'],
            "og": data['data']['originalGravity']
        }
        
        result = firebase.post('/Beers/', result_attr)
        
    
#        business_id = request.form.get("id")
#        business_rs = yelp_api.business_query(id=business_id)
#        result = firebase.post('/Beers', {
#            "image_url": business_rs["image_url"][:-6] + "ls.jpg",
#            "name": business_rs["name"],
#            "description": business_rs["snippet_text"],
#            "rating": business_rs["rating_img_url"],
#            "id": business_rs["id"]
#        })
        return redirect(url_for("favorites"))
    except:
        return "Error!"
예제 #21
0
def main():
    url = 'http://data.ntpc.gov.tw/od/data/api/28AB4122-60E1-4065-98E5-ABCCB69AACA6?$format=json'

    response = requests.get(url)
    response.encoding = 'UTF-8'
    items = response.json()

    # STG
    firebase.delete(stgTable, None)

    print('count = ' + str(len(items)))

    for item in items:
        addr = item['location']
        g = geocoder.google(addr)

        if g.ok:
            data = {'lineid': item['lineid'], 'car': item['car'], 'address': addr,
                    'time': item['time'], 'lat': g.lat, 'lng': g.lng}
            result = firebase.post(stgTable, data)
        else:
            print(g.json)
        time.sleep(0.5)

    # Copy to PROD
    print('Copy to PROD')
    firebase.delete('/PROD', None)
    stgResults = firebase.get(stgTable, None)
    firebase.patch('/PROD', stgResults)
    print('Done')
예제 #22
0
def addCalories():
    global userId
    date = raw_input("Enter Date in mm/dd/yyyy: ")
    intake = raw_input("Enter Calories: ")
    newFood = {"date":date,"CaloricIntake":intake, "UserID":userId}
    res = firebase.post("/DayFoodLog", newFood)
    print("Food Log Recorded")
예제 #23
0
파일: hello.py 프로젝트: furqanmk/Homeiot
def new_unlock(unlocker_name):
    lockhistory_url = 'lock/history'
    current_time = time.strftime('%Y%m%d%H%M%S')
    data = { 'person': unlocker_name, 'time': current_time }
    result = firebase.post(lockhistory_url, data)
    print "Record inserted: " + str(result)
    time.sleep(security_delay)
    return;
예제 #24
0
파일: db.py 프로젝트: johnanukem/squirtle
def update_times(ident, time):
    result = firebase.get('/line', None, connection=None,
            params={'print': 'pretty', 
                'auth': token,
                'orderBy': '"ident"',
                'equalTo': str('"' + ident + '"')})
    key = result.keys()[0]
    data = result[key]

    total_time = time - parse(data['timestamp'])
    new_entry = {'ident': ident, 'timeIn': data['timestamp'], 'timeOut': time, 
                'total': str(total_time)}
    firebase.post('/data', new_entry, connection=None, 
                    params={'print': 'pretty', 'auth': token})
    firebase.delete('/line', key, connection=None, 
                    params={'print': 'pretty', 'auth': token})
    return str(total_time)
예제 #25
0
def putIntoFirebaseQuestion(Question):
    #result = firebase.post('/users', new_user, {'print': 'silent'}, {'X_FANCY_HEADER': 'VERY FANCY'})
    print(Question)
    res = firebase.post('/Question',str(Question))
    #res = str(res[1])
    uniqID = res.get('name')
    #print("hi" + res)

    return uniqID
def send_data(response):
    query = {}
    query["coordinate_1"] = response.coordinates['coordinates'][0]
    query["coordinate_2"] = response.coordinates['coordinates'][1]
    query["created_at"] = str(response.created_at)
    query["id"] = response.id
    query["text"] = response.text
    result = firebase.post('/twitter_data', query)
    print result
예제 #27
0
def putAppleWatch(beacon,user):
    userPostStr = '/'+ beacon + '/' + user
    a = calendar.timegm(time.gmtime())
    b = random.randint(80,100)
    data = {str(a):str(b)}
    result = firebase.post(userPostStr,data)
    x = []
    y = []
    trace = go.Scatter(x.append(int(a)), y.append(b), mode = 'lines+markers')      
예제 #28
0
def manualInput():
    global userId
    global usernamew
    name = raw_input("Enter Lift Name: ")
    reps = raw_input("Enter Reps: ")
    sets = raw_input("Enter Sets: ")
    weight = raw_input("Enter Weight: ")
    date = raw_input("Enter Date in mm/dd/yyyy: ")
    newLif = {"name":name,"reps":reps,"weight":weight,"sets":sets,"date":date, "UserID":userId}
    res = firebase.post("/Lifts", newLif)
    print("Lift Recorded")
예제 #29
0
def createNewUser():
    global userId
    global username
    name = raw_input("Enter Name: ")
    email = raw_input("Enter Email: ")
    weight = raw_input("Enter Weight: ")
    age = raw_input("Enter Age: ")
    newUser = {"name":name,"email":email,"weight":weight,"age":age}
    username = name;
    res = firebase.post("/Users", newUser)
    userId = res
예제 #30
0
def signUp():
	_name = request.form['inputName']
	_email = request.form['inputEmail']
	_password = request.form['inputPassword']

	new_user = _name + ' ' + _email + ' ' + _password

	print 'signing up'

	if _name and _email and _password:
		result = firebase.post('/users', new_user, {'print': 'pretty'}, {'X_FANCY_HEADER' : 'VERY FANCY'})
		print 'hi'#return json.dumps({'html':'<span>All fields good !!</span>'})
예제 #31
0
def lineBot(op):
    try:
        if op.type == 0:
            return
        if op.type == 5:
            RfuProtect = firebase.get("/setting", '')
            if RfuProtect["autoAdd"] == True:
                line.blockContact(op.param1)
        if op.type in [25, 26]:
            msg = op.message
            text = msg.text
            msg_id = msg.id
            receiver = msg.to
            sender = msg._from
            if msg.toType == 0 or msg.toType == 1 or msg.toType == 2:
                if msg.toType == 0:
                    if sender != line.profile.mid:
                        to = sender
                    else:
                        to = receiver
                elif msg.toType == 1:
                    to = receiver
                elif msg.toType == 2:
                    to = receiver
            if msg.contentType == 0:
                RfuProtect = firebase.get("/setting", '')
                if text is None:
                    return
                elif msg.text in ["เช็ค"]:
                    try:
                        ret_ = "สถานะที่เปิดอยู่"
                        if RfuProtect["autoAdd"] == True:
                            ret_ += "\nออโต้บล็อค✔"
                        else:
                            ret_ += "\nออโต้บล็อค ✘ "
                        if RfuProtect["Wc"] == True:
                            ret_ += "\nเปิดข้อความต้อนรับสมาชิก ✔"
                        else:
                            ret_ += "\nเปิดข้อความต้อนรับสมาชิก    ✘ "
                        if RfuProtect["inviteprotect"] == True:
                            ret_ += "\nป้องกันเชิญเข้ากลุ่ม ✔"
                        else:
                            ret_ += "\nป้องกันเชิญเข้ากลุ่ม ✘ "
                        if RfuProtect["cancelprotect"] == True:
                            ret_ += "\nป้องกันยกเลิกค้างเชิญ ✔"
                        else:
                            ret_ += "\nป้องกันยกเลิกค้างเชิญ ✘ "
                        if RfuProtect["protect"] == True:
                            ret_ += "\nป้องกันลบสมาชิก ✔"
                        else:
                            ret_ += "\nป้องกันลบสมาชิก ✘ "
                        if RfuProtect["linkprotect"] == True:
                            ret_ += "\nป้องกันเปิดลิ้ง ✔"
                        else:
                            ret_ += "\nป้องกันเปิดลิ้ง ✘ "
                        if RfuProtect["Protectjoin"] == True:
                            ret_ += "\nป้องกันเข้ากลุ่ม ✔"
                        else:
                            ret_ += "\nป้องกันเข้ากลุ่ม ✘ "
                        line.sendMessage(to, str(ret_))
                        sendMessageWithMention(to, lineMID)
                        line.sendMessage(
                            to, "" + datetime.today().strftime('%H:%M:%S'))
                    except Exception as e:
                        line.sendMessage(msg.to, str(e))
                elif msg.text in ["คำสั่ง", "help"]:
                    myHelp = myhelp()
                    line.sendMessage(to, str(myHelp))
                    sendMessageWithMention(to, lineMID)
                    line.sendMessage(
                        to, "" + datetime.today().strftime('%H:%M:%S') + "")
                elif msg.text in ["คำสั่ง1", "help1"]:
                    helpSet = helpset()
                    line.sendMessage(to, str(helpSet))
                    sendMessageWithMention(to, lineMID)
                    line.sendMessage(
                        to, "" + datetime.today().strftime('%H:%M:%S') + "")
                elif msg.text in ["คำสั่ง2", "help2"]:
                    listGrup = listgrup()
                    line.sendMessage(to, str(listGrup))
                    sendMessageWithMention(to, lineMID)
                    line.sendMessage(
                        to, "" + datetime.today().strftime('%H:%M:%S') + "")
                elif msg.text.lower().startswith("ไอดี "):
                    if 'MENTION' in list(msg.contentMetadata.keys()) != None:
                        names = re.findall(r'@(\w+)', text)
                        mention = ast.literal_eval(
                            msg.contentMetadata['MENTION'])
                        mentionees = mention['MENTIONEES']
                        lists = []
                        for mention in mentionees:
                            if mention["M"] not in lists:
                                lists.append(mention["M"])
                        ret_ = ""
                        for ls in lists:
                            ret_ += "" + ls
                        line.sendMessage(msg.to, str(ret_))
                elif msg.text.lower() == "เปิดระบบป้องกัน":
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["protect"] = True
                    RfuProtect["cancelprotect"] = True
                    RfuProtect["inviteprotect"] = True
                    RfuProtect["linkprotect"] = True
                    RfuProtect["Protectjoin"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(
                        to, "_เปิดระบบป้องกันทั้งหมด\n" +
                        datetime.today().strftime('%H:%M:%S'))
                elif msg.text in ["ปิดระบบป้องกัน"]:
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["protect"] = False
                    RfuProtect["cancelprotect"] = False
                    RfuProtect["inviteprotect"] = False
                    RfuProtect["linkprotect"] = False
                    RfuProtect["Protectjoin"] = False
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(
                        to, "_ปิดระบบป้องกันทั้งหมด\n" +
                        datetime.today().strftime('%H:%M:%S'))

                elif msg.text.lower() in [
                        'เปิดป้องกันลิ้ง', 'เปิดป้องกันลิงค์'
                ]:
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["linkprotect"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_เปิดป้องกันลิ้งแล้ว")

                elif msg.text.lower() in ['ปิดป้องกันลิ้ง', 'ปิดป้องกันลิงค์']:
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["linkprotect"] = False
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_ปิดป้องกันลิ้งแล้ว")

                elif msg.text.lower() == 'เปิดกันเข้า':
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["Protectjoin"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_เปิดกันเข้ากลุ่ม")

                elif msg.text.lower() == 'ปิดกันเข้า':
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["Protectjoin"] = False
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_ปิดกันเข้ากลุ่ม")

                elif msg.text.lower() == 'เปิดกันเชิญ':
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["inviteprotect"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_เปิดป้องกันเชิญเข้ากลุ่ม")

                elif msg.text.lower() == 'ปิดกันเชิญ':
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["inviteprotect"] = False
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_ปิดป้องกันเชิญเข้ากลุ่ม")

                elif msg.text.lower() == 'เปิดกันยกเลิกเชิญ':
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["cancelprotect"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_เปิดป้องกันยกเลิกเชิญ")

                elif msg.text.lower() == 'ปิดกันยกเลิกเชิญ':
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["cancelprotect"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(msg.to, "_เปิดป้องกันยกเลิกเชิญ")

                elif msg.text in ["เปิดข้อความ"]:
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["Wc"] = True
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(to, "_เปิดข้อความตอนรับ")

                elif msg.text in ["ปิดข้อความ"]:
                    RfuProtect = firebase.get("/setting", '')
                    RfuProtect["Wc"] = False
                    result = firebase.put('', "/setting", RfuProtect)
                    line.sendMessage(to, "_ปิดข้อความตอนรับ")

                elif msg.text in ["ล้างดำ"]:
                    try:
                        result = firebase.delete("/banlist", '')
                        datapass = {'id': 'dummy'}
                        result = firebase.post("/banlist", datapass)
                    except:
                        pass
                    line.sendMessage(msg.to, "_ล้างบัญชีดำเรียบร้อย")
                    print("Clear Ban")
                elif msg.text in ["เช็คดำ", "บัญชีดำ"]:
                    result = firebase.get("/banlist", '')
                    banlist = {'id': {}}
                    try:
                        for data in result:
                            banlist["id"][result[data]["id"]] = True
                    except:
                        pass
                    if banlist["id"] == {}:
                        line.sendMessage(msg.to, "ไม่มีลิสในบัญชีดำ")
                    else:
                        line.sendMessage(
                            msg.to, "รายชื่อบัญชีดำ " +
                            datetime.today().strftime('%H:%M:%S'))
                        mc = "<Blacklist>\n"
                        for mi_d in banlist["id"]:
                            mc += "[" + line.getContact(
                                mi_d).displayName + "] \n"
                        line.sendMessage(msg.to, mc + "")
                elif 'ยัดดำ' in text.lower():
                    targets = []
                    key = eval(msg.contentMetadata["MENTION"])
                    key["MENTIONEES"][0]["M"]
                    for x in key["MENTIONEES"]:
                        targets.append(x["M"])
                    for target in targets:
                        try:
                            datapass = {'id': str(target)}
                            result = firebase.post("/banlist", datapass)
                            line.sendMessage(msg.to, "ยัดดำเรียบร้อยแล้ว")
                            print("Banned User")
                        except:
                            line.sendMessage(msg.to, "ไม่สามารถยัดดำได้")

        if op.type == 19:
            adminlist = {'id': {}}

            result = firebase.get("/adminlist", '')
            for data in result:
                adminlist["id"][result[data]["id"]] = True
            if op.param3 in adminlist["id"]:
                random.choice(Rfu).inviteIntoGroup(op.param1, [op.param3])
                print("adminkick")
            if op.param2 in adminlist["id"]:
                pass
            elif RfuProtect["protect"] == True:
                datapost = {'id': str(op.param2)}
                result = firebase.post("/banlist", datapost)
                random.choice(Rfu).kickoutFromGroup(op.param1, [op.param2])
                random.choice(Rfu).inviteIntoGroup(op.param1, [op.param3])
        if op.type == 11:
            adminlist = {'id': {}}

            result = firebase.get("/adminlist", '')
            for data in result:
                adminlist["id"][result[data]["id"]] = True
            if RfuProtect["linkprotect"] == True:
                if op.param2 in adminlist["id"]:
                    pass
                    print("admin open link")
                else:
                    datapost = {'id': str(op.param2)}
                    try:
                        result = firebase.post("/banlist", datapost)
                    except Exception as error:
                        logError(error)
                    G = line.getGroup(op.param1)
                    G.preventedJoinByTicket = True
                    random.choice(Rfu).updateGroup(G)
                    random.choice(Rfu).kickoutFromGroup(op.param1, [op.param2])
        if op.type == 17:
            RfuProtect = firebase.get("/setting", '')
            if RfuProtect["Wc"] == True:
                if op.param2 in lineMID:
                    return
            dan = line.getContact(op.param2)
            tgb = line.getGroup(op.param1)
            line.sendMessage(
                op.param1, "ยินดีต้อนรับ" + "\n" +
                "\n{}\n{}".format(str(dan.displayName), str(tgb.name)))
        if op.type == 13:
            adminlist = {'id': {}}
            result = firebase.get("/adminlist", '')
            for data in result:
                adminlist["id"][result[data]["id"]] = True
            if op.param2 in adminlist["id"]:
                group = line.getGroup(op.param1)
                line.acceptGroupInvitation(op.param1)
        if op.type == 17:
            adminlist = {'id': {}}

            result = firebase.get("/adminlist", '')
            for data in result:
                adminlist["id"][result[data]["id"]] = True
            if op.param2 in adminlist["id"]:
                pass
            if RfuProtect["protect"] == True:
                if settings["blacklist"][op.param2] == True:
                    try:
                        line.kickoutFromGroup(op.param1, [op.param2])
                        G = line.getGroup(op.param1)
                        G.preventedJoinByTicket = True
                        line.updateGroup(G)
                    except:
                        try:
                            line.kickoutFromGroup(op.param1, [op.param2])
                            G = line.getGroup(op.param1)
                            G.preventedJoinByTicket = True
                            line.updateGroup(G)
                        except:
                            pass

    except Exception as error:
        logError(error)
예제 #32
0
                    break
        medCount.append(FreqDist(ngrams(medStr[i], 1)))
        d = dict(medCount[i])
        medDict = dict((key[0], value) for (key, value) in d.items())
        sortedMedDict.append(sorted(medDict.items(), key=operator.itemgetter(1), reverse = True))

        for a in range(0,int(len(sortedMedDict[i])/3)):
            for b in range(a+1,int(len(sortedMedDict[i])/3)):
                if(edit_distance(sortedMedDict[i][a][0], sortedMedDict[i][b][0]) <= 1):
                    sortedMedDict[i][a] = (sortedMedDict[i][a][0], (sortedMedDict[i][a][1] + sortedMedDict[i][b][1]))
                    sortedMedDict[i][b] = (sortedMedDict[i][b][0], 0)

        sortedMedDict[i] = sorted(sortedMedDict[i], key=operator.itemgetter(1), reverse = True)

        print(sortedMedDict[i][0:6])    
        print(orgComments[medIndices[i][0]])
    answerFire = []
    for a in range(0, 3):
        vector_temp = []
        for b in range(0, 3):
            vector_temp.append({"word":sortedMedDict[a][b+1][0], "freq":str(sortedMedDict[a][b+1][1])})
        answerFire.append({"word":str(sortedMedDict[a][0][0]),"freq":str(sortedMedDict[a][0][1]),"related":vector_temp, "comment":orgComments[medIndices[a][0]]})

    result = {"name":""}
    print(firebase.delete('/topico', result["name"]))
    result = firebase.post('/topico', data={"data":answerFire})
    print (result)
    


예제 #33
0
import datetime

ser = serial.Serial('/dev/ttyACM0', 9600)
firebase = firebase.FirebaseApplication('https://uws-egat.firebaseio.com/',
                                        None)

while True:
    data_serial = ser.readline()
    #    data_serial = '1,2,3,4,5,6,7,8,9,10,11,12,13'
    if len(data_serial) > 10:
        data = data_serial.replace("\r\n", "").split(",")
        st = datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d %H:%M:%S')
        dataobj = {
            "timestamp": st,
            "temperature": data[0],
            "humidity": data[1],
            "temperature2": data[2],
            "wind_direction": data[3],
            "wind_speed": data[4],
            "rain": data[5],
            "pm10": data[6],
            "pm25": data[7],
            "light": data[8],
            "volt": data[9]
            #            "uv": data[10],
            #            "db": data[11]
        }

        firebase.post('/data', dataobj)
        print st, dataobj
예제 #34
0
def __requests__(value, folderName):
    request = firebase.post('/' + folderName, {'Name': value})
    return value
arquivo = open(directFile, 'r')
unica_string = arquivo.read()
arquivo.close()

# transformando em OBJETO
x = json.loads(unica_string,
               object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

id_consult = []
# atribuindo valres
for place in x.Hospital.data:
    id_consult.append(str(place.id))

result_all_feeds = []

for event in id_consult:
    feeds = graph.get_connections(event,
                                  connection_name="feed",
                                  fields="message,name,comments,created_time")
    result_all_feeds.append(feeds['data'])

directFile_result = 'pesquisas/result_all_feeds' + pergunta + '.json'
directDB = pergunta + 'result_all'

with open(directFile_result, 'w') as fp:
    json.dump(result_all_feeds, fp)

# Firebase
firebase.post(directDB, result_all_feeds)

print('ok...')
예제 #36
0
firebase = firebase.FirebaseApplication('https://trial-fc3c2.firebaseio.com/',
                                        None)

#firebase.delete('/', None)
#delete everything
#firebase.delete('/parent', None)
#delete everything under this node
#firebase.delete('/parent', 'child_name')
#delete this specific child
firebase.delete('/Number', None)
#firebase.delete('/', None)

#firebase.post('/parent_name',data)
#create a random variable which is a child to parent and hold value of data
data = 7
firebase.post('/Number', data)
data = 6
firebase.post('/Number', {'one': data, 'Two': data + 1})

#firebase.put('/parent_name','child_name',data)
#create a child with specific name which is a child to parent and hold value of data
# it overwrites previous values for the same child_name
x = 1
if x == 1:
    data = 5
    firebase.put('/IP_1', 'Three', data)
    data = 4
    firebase.put('/IP_1', 'Four', {'Four_child': data})
    firebase.put('/IP_1', strftime("%Y-%m-%d %H:%M:%S", gmtime()), data - 1)
    data = 3
    firebase.put('/IP_2', 'Two', {'one': data - 1, 'Two': data + 2})
예제 #37
0
            pb.buzzer.fail()

        # write data to csv
        writeTempToCSV(tempDifference)

        # attatches names to the data
        data = {
            "TempDifference": tempDifference,
            "LocalTemp": localTempReading,
            "OutsideTemp": outsideTempDownload,
            "TimeStamp": timeNow,
            "DateStamp": dateNow
        }

        #POSTS  to the database (POST means create an entry, does generate a nasty long node name)
        firebase.post('/R' + str(roomNumber), data)

        pb.output.e.write(0)

        # wait: uses output leds as countdown lights
        for x in range(50):  # 3600 is 1 hour, 900 is 15 nubs
            pb.output.f.write(1)
            sleep(0.33)
            pb.output.g.write(1)
            sleep(0.33)
            pb.output.h.write(1)
            sleep(0.33)
            pb.outputs.off()

            # Abort program button check if pressed
            if pb.button.read() == 1:
예제 #38
0
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_f

weather = client.getCurrentWeather(q='22304')

data_time = calendar.timegm(time.gmtime())
measured_temp = read_temp()
temp_f = weather['current']['temp_f']  # show temprature in f

auth=os.getenv('TEMP_EXPLICIT_AUTH')
uid=os.getenv('TEMP_UID')
url=os.getenv('TEMP_FIREBASE_URL')

auth = firebase.FirebaseAuthentication(auth, 'Ignore', extra={'explicitAuth': auth, 'uid':uid })
print auth.extra

firebase = firebase.FirebaseApplication(url, auth)

print temp_f
print measured_temp
print data_time
results = firebase.post('readings', data={'current_temp': temp_f, 'measured_temp':measured_temp, 'time':data_time}, params={'print': 'pretty'} )
print results
예제 #39
0
for e in sortedList:
    fw.write(e[0])
    fw.write(',')
    fw.write(str(e[1]))
    fw.write('\n')
fw.close()
'''

listForNew = set([])

upper = 100
cnt = 0
num = 1
f = open('sort-average')
for line in f.readlines():
    bookId = line.split(',')[0]
    print num, bookId
    num += 1
    if firebase.get('/books_location/' + bookId, None) != None:
        listForNew.add(bookId)
        cnt += 1
        print cnt
    if cnt >= upper:
        break
f.close()

#print listForNew

initList = ','.join(str(x).strip() for x in listForNew)
firebase.post('/list_for_new', initList)
예제 #40
0
def listen_and_publish():
	"""
	Multi channel RAK831 process
	Create the thread to listen via UDP socket
	"""
	global cli_addr
	# global serv_sock
	print("Create new thread")

	while True:
		#receive data from multichannel process
		data, cli_addr = serv_sock.recvfrom(BUFFER)
		threadLock.acquire()
		print(data)
		try:
			#Parse json data
			data_dict = json.loads(data)
		except RuntimeError:
			print("Receive data fail!")

		# Check type of uplink packet
		if data_dict['type'] == "DATA":
			#Get current time
			now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
			#Save data into local database ==> MySQL
			save_to_database(str(data_dict['device_id']),
							 str(data_dict['sensor_temp']),
							 str(data_dict['sensor_humidity']),
							 str(data_dict['sensor_bright']))
			#Save data into cloud database ==> Firebase
			firebase.post('End_device/deviceID_' + str(data_dict['device_id']),
						 	{'time': now, 
						 	'temp': int(round(data_dict['sensor_temp'])),
						 	'humidity': int(round(data_dict['sensor_humidity'])),
						 	'bright': int(round(data_dict['sensor_bright']))} )

			json_obj = convert_data_to_json("device/data",
											data_dict['device_id'], 
											now,
											int(round(data_dict['sensor_temp'])),
											int(round(data_dict['sensor_humidity'])),
											int(round(data_dict['sensor_bright'])))

			mqttclient.publish("device/data", str(json_obj))

			if(int(round(data_dict['sensor_temp'])) >= 50):
				send_push_notification_fcm("Temparature device ID_" + str(data_dict['device_id']) + " too high --> " + str(int(round(data_dict['sensor_temp']))))		
			# if(int(round(data_dict['sensor_humidity'])) >= 50):
			# 	send_push_notification_fcm("Humidity too high --> " + str(int(round(data_dict['sensor_temp']))))		
			# if(int(round(data_dict['sensor_bright'])) >= 50):
			# 	send_push_notification_fcm("Bright too high --> " + str(int(round(data_dict['sensor_temp']))))		

		elif data_dict['type'] == "GPS":
			json_obj = convert_gps_to_json("gw/gps", data_dict['gps_lat'], data_dict['gps_long'])
			mqttclient.publish("gw/gps", str(json_obj), retain = True)

		elif data_dict['type'] == "ACK":
			json_obj = convert_ack_to_json("device/sw_ack/id_" + str(data_dict['device_id']), data_dict['device_id'], data_dict['sw_state'])
			mqttclient.publish("device/sw_ack/id_" + + str(data_dict['device_id']), str(json_obj), retain = True)

		threadLock.release()
from firebase import firebase
import json
firebase = firebase.FirebaseApplication(
    'https://customer-database-b3374.firebaseio.com/', None)

name = input("Please enter fullname :")
email = input("Please enter email address: ")
plate = input("Please enter license plate number: ")

data = {'License Plate': plate, 'email': email, 'name': name}

result = firebase.post('/License Plates', data)
예제 #42
0
def detect_face():
    # global vs, outputFrame, lock
    global outputFrame, lock, face_sum

    while True:
        frame = vs.read()
        frame = imutils.resize(frame, width=600)
        (h, w) = frame.shape[:2]
    
        imageBlob = cv2.dnn.blobFromImage(
            cv2.resize(frame, (300, 300)), 1.0, (300, 300),
            (104.0, 177.0, 123.0), swapRB=False, crop=False)
    
        detector.setInput(imageBlob)
        detections = detector.forward()

        for i in range(0, detections.shape[2]):

            confidence = detections[0, 0, i, 2]
    
            if confidence > 0.5:
                
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")
    
                face = frame[startY:endY, startX:endX]
                (fH, fW) = face.shape[:2]
    
                if fW < 20 or fH < 20:
                    continue
                    
                faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255,
                    (96, 96), (0, 0, 0), swapRB=True, crop=False)
                embedder.setInput(faceBlob)
                vec = embedder.forward()
    
                preds = recognizer.predict_proba(vec)[0]
                j = np.argmax(preds)
                proba = preds[j]
                name = le.classes_[j]

                if name == 'dhruv':
                    face_sum.append(1)
                else:
                    face_sum.append(0)
                
                if len(face_sum) >= 120:
                    total = sum(face_sum)
                    if (total / 120 > 0.5):
                        # its dhruv
                        print('posting dhruv')
                        res = firebase.post(
                            '/people',
                            {
                                'person': 'dhruv',
                                'time': datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
                            }
                        )
                    else:
                        # its unknown
                        print('posting unknown')
                        res = firebase.post(
                            '/people',
                            {
                                'person': 'unknown',
                                'time': datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
                            }
                        )
                    face_sum = []
                    time.sleep(0.5)
    
                text = "{}: {:.2f}%".format(name, proba * 100)
                y = startY - 10 if startY - 10 > 10 else startY + 10
                cv2.rectangle(frame, (startX, startY), (endX, endY),
                    (0, 0, 255), 2)
                cv2.putText(frame, text, (startX, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
    
        fps.update()

        # show the output frame
        # cv2.imshow("Frame", frame)
        key = cv2.waitKey(1) & 0xFF
    
        # if the `q` key was pressed, break from the loop
        if key == ord("q"):
            break

        with lock:
            outputFrame = frame.copy()
예제 #43
0
from firebase import firebase
import json as simplejson

firebase = firebase.FirebaseApplication(
    'https://brilliant-fire-6276.firebaseio.com', None)
result = firebase.get('', None)
print result

name = {'Edison': 10, 'Pi': 2016}
#data = json.dumps(name)

post = firebase.post('', name)

print post
예제 #44
0
파일: measure.py 프로젝트: suzu6/acerola

# FIFO
que = []
stock_num = 10

try:
    firebase.put('', '/devices/'+target+'/isError', False)
    while True:
        now = datetime.now() + timedelta(hours=9)
        key = now.strftime('%Y-%m-%d %H:%M:%S')
        # only temp
        value = readData()[0]['value']
        data = {'t': key, 'y': value}

        result = firebase.post(url, data)
        print 'post ', data

        que.append(result['name'])
        if len(que) > stock_num:
            # stock数以下のデータを削除
            key = que.pop(0)
            result = firebase.delete(url, key)
            print 'delete ', result

        sampling_interval = firebase.get(
            '/devices/'+target+'/sampling_interval', None)
        print 'sampling_interval', sampling_interval
        time.sleep(sampling_interval)

except:
예제 #45
0
from firebase import firebase

firebase = firebase.FirebaseApplication('https://hidro-f66a7.firebaseio.com/')

result = firebase.post('/user', {'Three': 'Bye'})
print(result)
예제 #46
0
def handle_query(call):

    if (call.data.startswith("us_cipot")):
        index = int(call.data[-1])
        cid = call.message.chat.id
        result = firebase.get('/Topics/' + topics[index], '')
        if not result:
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  text='Sorry!' + sadIcon +
                                  'Quiz Not Yet Created ',
                                  message_id=call.message.message_id)
        else:
            l2_expl = []
            qn = 1
            for d1 in result:
                opt = {}
                ind = 0
                temp = result[d1]
                for d2 in temp:
                    if d2 == 'Explanation':
                        l2_expl.append(temp[d2])
                        top_expl[str(cid)] = l2_expl
                        print(top_expl)
                    elif d2 == 'Question':
                        print(qn)
                        participant = firebase.get(
                            '/Participants/' + str(cid) + '/' +
                            str(call.message.chat.first_name) + '/' + today +
                            '/old_qn', '')
                        if not participant:
                            firebase.post(
                                '/Participants/' + str(cid) + '/' +
                                str(call.message.chat.first_name) + '/' +
                                today + '/old_qn', sd)
                        else:
                            for x in participant:
                                upd = x
                            firebase.put(
                                '/Participants/' + str(call.message.chat.id) +
                                '/' + str(call.message.chat.first_name) + '/' +
                                today + '/old_qn/' + upd, 'Score', 0)
                            firebase.put(
                                '/Participants/' + str(call.message.chat.id) +
                                '/' + str(call.message.chat.first_name) + '/' +
                                today + '/old_qn/' + upd, 'Correct', 0)
                            firebase.put(
                                '/Participants/' + str(call.message.chat.id) +
                                '/' + str(call.message.chat.first_name) + '/' +
                                today + '/old_qn/' + upd, 'Incorrect', 0)

                        qn = qn + 1
                        ques = temp[d2]
                        if qn == 2:
                            bot.edit_message_text(
                                chat_id=call.message.chat.id,
                                text='*' + ques + '*',
                                parse_mode=telegram.ParseMode.MARKDOWN_V2,
                                message_id=call.message.message_id)
                        else:
                            bot.send_message(
                                chat_id=call.message.chat.id,
                                text='*' + ques + '*',
                                parse_mode=telegram.ParseMode.MARKDOWN_V2)
                    else:
                        ind = ind + 1
                        opt[d2] = temp[d2]
                        option.append(temp[d2][:-4])
                        strng = 'op' + str(option.index(
                            temp[d2][:-4])) + temp[d2][-4:] + str(qn - 1)
                        print(strng + ' ' + str(call.message.chat.first_name))
                        print(option)
                        bot.send_message(cid,
                                         str(ind) + ') ' + temp[d2][:-4],
                                         reply_markup=makekeyboard(strng))
                bot.send_message(cid,
                                 'Submit your Answers',
                                 reply_markup=submit('op' + str(qn - 1)))

    if (call.data.startswith("old_")):
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text="*     Select the Topic*",
                              parse_mode=telegram.ParseMode.MARKDOWN_V2,
                              message_id=call.message.message_id,
                              reply_markup=sel_top())

    if (call.data.startswith("cipot")):
        index = int(call.data[-1])
        firebase.post('/Topics/' + topics[index], data)
        data.clear()
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text='Question created Successfully ' + subIcon,
                              message_id=call.message.message_id)

    if (call.data.startswith("rcop")):
        db = firebase.get(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn', '')
        for x in db:
            score = db[x]['Score']
            correct = db[x]['Correct']
            wrong = db[x]['Incorrect']
        if 'crct' in call.data:
            score = score + 1
            correct = correct + 1
        else:
            score = score - 1
            wrong = wrong + 1
        print(f"call.data : {call.data} , type : {type(call.data)}," +
              str(score) + " " + str(correct) + " " + str(wrong))
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn/' + x,
            'Score', score)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn/' + x,
            'Correct', correct)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn/' + x,
            'Incorrect', wrong)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text=option[int(call.data[4])],
                              message_id=call.message.message_id)

    if (call.data.startswith("grop")):
        db = firebase.get(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn', '')
        for x in db:
            score = db[x]['Score']
            correct = db[x]['Correct']
            wrong = db[x]['Incorrect']
        if 'wrng' in call.data:
            score = score + 1
            correct = correct + 1
        else:
            score = score - 1
            wrong = wrong + 1

        print(f"call.data : {call.data} , type : {type(call.data)}," +
              str(score) + " " + str(correct) + " " + str(wrong))
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn/' + x,
            'Score', score)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn/' + x,
            'Correct', correct)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn/' + x,
            'Incorrect', wrong)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text=option[int(call.data[4])],
                              message_id=call.message.message_id)

    if (call.data.startswith("op_sub")):
        index = int(call.data[-1]) - 1
        db = firebase.get(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/old_qn', '')
        for x in db:
            score = db[x]['Score']
            correct = db[x]['Correct']
            wrong = db[x]['Incorrect']
        lst = top_expl.get(str(call.message.chat.id))
        if not lst:
            string1 = 'Sorry...Session Expired'
        else:
            string1 = "Your Score =  " + str(
                score) + " " + cupIcon + "\nCorrect = " + str(
                    correct) + "  " + tickIcon + "\nWrong = " + str(
                        wrong
                    ) + "  " + crossIcon + "\n*EXPLANATION*\n\n" + lst[index]
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text=string1,
                              message_id=call.message.message_id)

    if (call.data.startswith("kkcr")):
        db = firebase.get(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]), '')
        for x in db:
            score = db[x]['Score']
            correct = db[x]['Correct']
            wrong = db[x]['Incorrect']
        if 'crct' in call.data:
            score = score + 1
            correct = correct + 1
        else:
            score = score - 1
            wrong = wrong + 1
        print(f"call.data : {call.data} , type : {type(call.data)}," +
              str(score) + " " + str(correct) + " " + str(wrong))
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]) + '/' + x, 'Score', score)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]) + '/' + x, 'Correct', correct)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]) + '/' + x, 'Incorrect', wrong)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text=option[int(call.data[4])],
                              message_id=call.message.message_id)

    if (call.data.startswith("kkwr")):
        db = firebase.get(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]), '')
        for x in db:
            score = db[x]['Score']
            correct = db[x]['Correct']
            wrong = db[x]['Incorrect']
        if 'wrng' in call.data:
            score = score + 1
            correct = correct + 1
        else:
            score = score - 1
            wrong = wrong + 1

        print(f"call.data : {call.data} , type : {type(call.data)}," +
              str(score) + " " + str(correct) + " " + str(wrong))
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]) + '/' + x, 'Score', score)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]) + '/' + x, 'Correct', correct)
        firebase.put(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]) + '/' + x, 'Incorrect', wrong)
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text=option[int(call.data[4])],
                              message_id=call.message.message_id)

    if (call.data.startswith("SUBMIT")):
        index = int(call.data[-1]) - 1

        db = firebase.get(
            '/Participants/' + str(call.message.chat.id) + '/' +
            str(call.message.chat.first_name) + '/' + today + '/Q' +
            str(call.data[-1]), '')
        for x in db:
            score = db[x]['Score']
            correct = db[x]['Correct']
            wrong = db[x]['Incorrect']
        lst = expl.get(str(call.message.chat.id))
        if not lst:
            string1 = 'Sorry...Session Expired'
        else:
            string1 = "Your Score =  " + str(
                score) + " " + cupIcon + "\nCorrect = " + str(
                    correct) + "  " + tickIcon + "\nWrong = " + str(
                        wrong
                    ) + "  " + crossIcon + "\n*EXPLANATION*\n\n" + lst[index]
        bot.edit_message_text(chat_id=call.message.chat.id,
                              text=string1,
                              message_id=call.message.message_id)

    if (call.data.startswith("/quiz")):
        cid = call.message.chat.id
        result = firebase.get('/Quiz/' + today, '')
        if not result:
            bot.edit_message_text(chat_id=call.message.chat.id,
                                  text='Sorry!' + sadIcon +
                                  'Quiz Not Yet Created ',
                                  message_id=call.message.message_id)
        else:
            l1_expl = []
            qn = 1
            for d1 in result:
                opt = {}
                ind = 0

                temp = result[d1]
                for d2 in temp:
                    if d2 == 'Explanation':
                        l1_expl.append(temp[d2])
                        expl[str(cid)] = l1_expl
                        print(expl)
                    elif d2 == 'Question':
                        print(qn)
                        participant = firebase.get(
                            '/Participants/' + str(cid) + '/' +
                            str(call.message.chat.first_name) + '/' + today +
                            '/Q' + str(qn), '')
                        if not participant:
                            firebase.post(
                                '/Participants/' + str(cid) + '/' +
                                str(call.message.chat.first_name) + '/' +
                                today + '/Q' + str(qn), sd)
                        else:
                            for x in participant:
                                upd = x
                            firebase.put(
                                '/Participants/' + str(call.message.chat.id) +
                                '/' + str(call.message.chat.first_name) + '/' +
                                today + '/Q' + str(qn) + '/' + upd, 'Score', 0)
                            firebase.put(
                                '/Participants/' + str(call.message.chat.id) +
                                '/' + str(call.message.chat.first_name) + '/' +
                                today + '/Q' + str(qn) + '/' + upd, 'Correct',
                                0)
                            firebase.put(
                                '/Participants/' + str(call.message.chat.id) +
                                '/' + str(call.message.chat.first_name) + '/' +
                                today + '/Q' + str(qn) + '/' + upd,
                                'Incorrect', 0)

                        qn = qn + 1
                        ques = temp[d2]
                        if qn == 2:
                            bot.edit_message_text(
                                chat_id=call.message.chat.id,
                                text='*' + ques + '*',
                                parse_mode=telegram.ParseMode.MARKDOWN_V2,
                                message_id=call.message.message_id)
                        else:
                            bot.send_message(
                                chat_id=call.message.chat.id,
                                text='*' + ques + '*',
                                parse_mode=telegram.ParseMode.MARKDOWN_V2)
                    else:
                        ind = ind + 1
                        opt[d2] = temp[d2]
                        option.append(temp[d2][:-4])
                        strng = str(option.index(
                            temp[d2][:-4])) + temp[d2][-4:] + str(qn - 1)
                        print(strng + ' ' + str(call.message.chat.first_name))
                        print(option)
                        bot.send_message(cid,
                                         str(ind) + ') ' + temp[d2][:-4],
                                         reply_markup=makekeyboard(strng))
                bot.send_message(cid,
                                 'Submit your Answers',
                                 reply_markup=submit(str(qn - 1)))
예제 #47
0
if __name__ == "__main__":

    #main()


    sort_key = itemgetter(1)

    f = open('store1.pckl','rb')
    collect, return_list = pickle.load(f)
    f.close()

    return_list = sorted(return_list, key = lambda k: k['Style'])


    firebase = firebase.FirebaseApplication('https://aihackerthon.firebaseio.com', authentication=None)
    result = firebase.post('/SomethingLeong', return_list)
    print(result)


    '''
    img_dir = "model_with_shirts/" + return_list[0]['URL']
    input_path = os.path.abspath(img_dir)

    predicted_number = return_list[0]['Pant']
    print("Predicted Pant: {}".format(predicted_number))

    output_path = "training_pants/{image}.jpg".format(
        image= predicted_number
    )
    output_path = os.path.abspath(output_path)
예제 #48
0
bill["Exit_time"] = exsit
print("")
print("")
print("Your bill will be generated. Please wait!")
print("Hope to see you again", name, "! :)")
print("")
print("")
print("         Raghavendra Stores PVT LTD")

bill["Total"] = total
for y, z in bill.items():
    print(y, "  -  ", z)

firebase = firebase.FirebaseApplication(
    'https://pythondbtest-31f38.firebaseio.com/', None)
result = firebase.post('pythondbtest-31f38/Bill/', bill)
print(result)
if uk == 1:
    print("Stranger! Kindly Pay the amounnt of Rs.", total, "at the counter!")
    exit()
result = firebase.get('pythondbtest-31f38/Customer', '')
for y, z in result.items():
    if z["Name"] == name:
        print("User found!\n\n---------------------------")
        for i, j in z.items():
            print(i, j)
        uniq = y
        damt = z["Amount"]
        amt = damt - total
        if (amt < 0):
            amt = -amt
예제 #49
0
def insert_into_db(value):
    data = {'temp': value, 'timestamp': str(int(time.time() * 1000))}

    firebase.post('/temperature/history/', data)
    firebase.put('/temperature', 'currentTemperature', data)
예제 #50
0
def crearDatos(factor, vector, cantidad):
    global x
    global y

    from firebase import firebase
    firebase = firebase.FirebaseApplication(
        'https://python-proyect-ad812.firebaseio.com/', None)

    result = firebase.get('/Vectores/Vector' + str(vector) + '/', '')
    #print(result)

    if result == None:
        data = {"Nombre": "Vector" + str(vector)}

        if (distribucion == 0):
            y = np.random.normal(loc=0.0, scale=1.0, size=1000)
            y = abs(y / max(y) * 100)

        if (distribucion == 1):
            y = np.random.binomial(100, 0.2, 1000)
            y = abs(y / max(y) * 100)

        if (distribucion == 2):
            y = np.random.poisson(10, 1000)
            y = abs(y / max(y) * 100)

        if (distribucion == 3):
            y = np.random.power(5, 1000)
            y = abs(y / max(y) * 100)

        contador = 0
        for i in np.arange(0, 1000 * factor, factor):
            # print(i,end=":")
            # print("Y:",y[contador],end=" ; ")
            data[str(i)] = y[contador]
            contador += 1

        # print(data)
        result = firebase.post('/Vectores/Vector' + str(vector), data)
        # print(result)

        # print("Ya hice post")
        result = firebase.get('/Vectores/Vector' + str(vector) + '/', '')
        # print("Result: ",result)
        # print(len(result))

        # print("Traje el result")

        keys = []
        tiempo = []
        valores = []
        nombre = ""

        if result != None or len(result) < 1:
            for i in result:
                keys.append(i)
                diccionario = result[str(i)]
                for key in diccionario:
                    if key != "Nombre":
                        tiempo.append(float(key))
                        valores.append(diccionario.get(key))
                        # print(str(float(key))+"-->"+str(diccionario.get(key)),end=" | ")
                    else:
                        nombre = diccionario.get(key)
        else:
            print("Resultado vacio")

        print()
        print("Nombre: ", nombre)
        # print("ID: ",keys)
        # print("Valores: ",valores)
        print("Cantidad de valores y etiquetas: ", len(valores), " ",
              len(tiempo))
        print("\n")
        # print("Etiquetas: ",tiempo)

        x = tiempo
        y = valores

        plotpred()

        # print("X->",x)
        # print("Y->",y)

    else:
        print("\n\nEl vector ", vector, " ya est<C3><A1> lleno")
        from firebase import firebase
        firebase = firebase.FirebaseApplication(
            'https://python-proyect-ad812.firebaseio.com/', None)
        firebase.delete('/Vectores/Vector' + str(vector) + '/', '')
        print('deleted')
        crearDatos(factor, vector, cantidad)
예제 #51
0
    try:
        result = firebase.get('Users/'+userId+'/foodItems',None) #Get the values from foodItems and save into dict

        #Check if dict is empty From: https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work
        if bool(result) == False:
            print "No Items linked to user account"
            id,text = reader.read()
            foodType,expiryDate,category,empty= text.split(",")
            print ("Tag Id: " + str(id))
            print("Food Type: " + foodType)
            print("Expiry Date: " + expiryDate)
            print("Category:" + category)
            print("\n")

            firebase.post('Users/'+userId+'/foodItems',{'tagId':id,
                                     'foodType':foodType,
                                      'expiryDate':expiryDate,
                                      'category':category})
            print "Item Added to Firebase!"


        #If dict is not empty - Must check to see if tag matches (If so, remove the item or add it to Firebase)
        else:    
            dictionaryLength = len(result) #Get the length of result
            #print result 

            #Dict keys as list From: https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python
            rootList = [] #Create list called rootList to hold all the item root nodes
            for key in result.keys(): #Iterate and add each key from result dictionary to rootlist (Saving all the keys)
                rootList.append(key)
                
            
예제 #52
0
import serial

from firebase import firebase
from serial import SerialException

ser = serial.Serial('COM6', baudrate=9600, timeout=1)

try:

    arduino = ser.readline()
    print(arduino)
    firebase = firebase.FirebaseApplication(
        'https://ecotaxiphoneapp-9e80f.firebaseio.com/', None)
    result = firebase.post('/location', {'car': arduino})

# current location name

# insert record

except serial.SerialException:
    print("ERROR")
예제 #53
0
def post(name, mail, phone):
    student = {'Name': name, 'Email': mail, 'Phone': phone}
    result = firebase.post(table, student)
    return result
        if ear < EYE_AR_THRESH:
            COUNTER += 1

            # if the eyes were closed for a sufficient number of
            # frames, then sound the alarm
            if COUNTER >= EYE_AR_CONSEC_FRAMES:
                # if the alarm is not on, turn it on
                if not ALARM_ON:
                    ALARM_ON = True
                    buzzer.on()
                    post_data = {
                        'device': DEVICE_ID,
                        'time': datetime.now(),
                        'email': EMAIL_ADDR
                    }
                    firebase.post('/records', post_data)

                # draw an alarm on the frame
                cv2.putText(frame, "WARNING", (10, 30),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

            # draw text indicating eye status
            cv2.putText(frame, "Eye closed", (300, 30),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

        # otherwise, the eye aspect ratio is not below the blink
        # threshold, so reset the counter and alarm
        else:
            COUNTER = 0
            ALARM_ON = False
            buzzer.off()
예제 #55
0
firebase = firebase.FirebaseApplication(
    "https://makeuoft2020-268400.firebaseio.com/", None)

##################POST
# print("now going to send push notification")
# # defining the api-endpoint
# API_ENDPOINT = "https://exp.host/--/api/v2/push/send"

# # data to be sent to api
# data = {
#   "to": "ExponentPushToken[uh3CDsJFxY_vTcV_n0wUHM]",
#   "title":"hello",
#   "body": "world"
# }

# # sending post request and saving response as response object
# r = requests.post(url = API_ENDPOINT, data = data)

# #################GET
client = storage.Client()
bucket = client.get_bucket('makeuoftimagesoutput')

while (True):
    with open('1.txt', "r+") as file_obj:
        blob = bucket.blob('facesandracy.txt')
        client.download_blob_to_file(blob, file_obj)  # API request.
        data = {"hello": (file_obj).readlines()}
        result = firebase.post('users/01', (file_obj).readlines())
    time.sleep(3)
예제 #56
0
def postdatabegin():
    try:
        firebase.delete('/' + base + '/cloud', None)
        firebase.post('/' + base + '/cloud', 0)
        firebase.delete('/' + base + '/' + base + '/mode_cloud', None)
        firebase.post('/' + base + '/mode_cloud', 1)
        firebase.delete('/' + base + '/mode_state_cloud', None)
        firebase.post('/' + base + '/mode_state_cloud', 0)
        firebase.delete('/' + base + '/fan_cloud', None)
        firebase.post('/' + base + '/fan_cloud', 0)
        firebase.delete('/' + base + '/precool_time', None)
        firebase.post('/' + base + '/precool_time', 30)
        firebase.delete('/' + base + '/preheat_time', None)
        firebase.post('/' + base + '/preheat_time', 30)
        firebase.delete('/' + base + '/run_or_not_precool', None)
        firebase.post('/' + base + '/run_or_not_precool', 0)
        firebase.delete('/' + base + '/run_or_not_preheat', None)
        firebase.post('/' + base + '/run_or_not_preheat', 0)
        firebase.delete('/' + base + '/run_or_not_save', None)
        firebase.post('/' + base + '/run_or_not_save', 0)
        firebase.delete('/' + base + '/run_or_not_sleep', None)
        firebase.post('/' + base + '/run_or_not_sleep', 0)
        firebase.delete('/' + base + '/sch_cloud', None)
        firebase.post('/' + base + '/sch_cloud', 1)
        firebase.delete('/' + base + '/set_temp', None)
        firebase.post('/' + base + '/set_temp', 80)
        firebase.delete('/' + base + '/sleep_time', None)
        firebase.post('/' + base + '/sleep_time', 30)
        firebase.delete('/' + base + '/stop_it', None)
        firebase.post('/' + base + '/stop_it', 0)
    except:
        pass
예제 #57
0
from firebase import firebase
import random

firebase = firebase.FirebaseApplication('https://myawsomeprp.firebaseio.com/',
                                        None)
while True:
    toDatabase = {
        'speed': random.randint(30, 100),
        'temp': random.randint(1, 60),
        'rpm': random.randint(1000, 7000),
        'Current': random.randint(30, 100),
        'voltage': random.randint(60, 100)
    }
    result = firebase.post('/MotorData', toDatabase)
예제 #58
0
def webhook_handler():
    if request.method == "POST":
        t = time.time()
        date = datetime.datetime.fromtimestamp(t).strftime('%Y%m%d%H%M%S')

        update = telegram.Update.de_json(request.get_json(force=True), bot)
        chat_id = update.message.chat.id
        username = update.message.chat.last_name
        try:
            text = update.message.text.encode('utf-8')
        except AttributeError:
            text = update.message.text
        #text=update.message.text
        #text=text.encode('utf-8')

        if text:
            text = text.decode('utf-8')
        print(text)
        if text == 'NLP':
            bot.sendMessage(chat_id=chat_id, text='yes')
            print('get NLP form')
            print(chat_id)
        if text:
            if text.startswith('$'):
                if username:
                    dict = {
                        'Date': date,
                        'Emotion': '',
                        'Intention': '',
                        'Username': username
                    }
                else:
                    dict = {
                        'Date': date,
                        'Emotion': '',
                        'Intention': '',
                        'Username': '******'
                    }
                text = text[1:]
                result = pseg.cut(text)
                print(result)
                for w in result:
                    if w.flag == 'happy':
                        dict['Emotion'] = 'happy'
                    if w.flag == 'sad':
                        dict['Emotion'] = 'sad'
                    if w.flag == 'move':
                        dict['Intention'] = w.word
                result = firebase.patch(
                    '/Telegram' + '/' + str(date), {
                        'Emotion': dict['Emotion'],
                        'Intention': dict['Intention'],
                        'User': dict['Username']
                    })
                bot.sendMessage(chat_id=chat_id,
                                text='Emotion and intention recorded')
            if text.startswith('!result'):
                result = firebase.get('/Telegram',
                                      None,
                                      params={'print': 'pretty'},
                                      headers={'X_FANCY_HEADER': 'very fancy'})
                if result:
                    result = list(result.values())
                    print(result)
                    bot.sendMessage(chat_id=chat_id,
                                    text='總共紀錄' + str(len(result)) + '條訊息')
                    bot.sendMessage(chat_id=chat_id, text='所記錄情緒:')
                    yoyo = []
                    for w in range(len(result)):
                        print(result[w]['Emotion'])
                        yoyo.append(result[w]['Emotion'])
                        yoyodiy = ', '.join(yoyo)
                    #print(yoyo)
                    print(yoyodiy)
                    bot.sendMessage(chat_id=chat_id, text=yoyodiy)
                    bot.sendMessage(chat_id=chat_id, text='所記錄動作:')
                    yoyo = []
                    for w in range(len(result)):
                        print(result[w]['Intention'])
                        yoyo.append(result[w]['Intention'])
                        yoyodiy = ', '.join(yoyo)
                    #print(yoyo)
                    print(yoyodiy)
                    bot.sendMessage(chat_id=chat_id, text=yoyodiy)
                    ############################記錄人
                    bot.sendMessage(chat_id=chat_id, text='記錄人:')
                    yoyo = []
                    for w in range(len(result)):
                        print(result[w]['User'])
                        yoyo.append(result[w]['User'])
                        yoyodiy = ', '.join(yoyo)
                    #print(yoyo)
                    print(yoyodiy)
                    bot.sendMessage(chat_id=chat_id, text=yoyodiy)
                    ###################################
                else:
                    bot.sendMessage(chat_id=chat_id,
                                    text='Firebase Database is empty!')
            if text.startswith('!delete'):
                firebase.delete('/Telegram', None)
                bot.sendMessage(chat_id=chat_id,
                                text='資料庫已經空 Firebase data deleted')
            if text.startswith('seg='):
                #bot.sendMessage(chat_id=chat_id, text=text)
                text = text[4:]
                #text.replace(" ", "")
                result = pseg.cut(text)
                print(result)
                for w in result:
                    if w.word != ' ' and w.word != ' ' and w.word != '\n' and w.word != '\r\n':
                        print(w.word)
                        bot.sendMessage(chat_id=chat_id, text=w.word)
            #if text.startswith('pos='):
            #text=text[4:]
            #result=pseg.cut(text)
            #print(result)
            #for w in result:
            #if(w.flag=='positive'):
            #bot.sendMessage(chat_id=chat_id,text='tag: positive')
            #bot.sendMessage(chat_id=chat_id,text=w.word)
            #if(w.flag=='negative'):
            #bot.sendMessage(chat_id=chat_id,text='tag: negative')
            #bot.sendMessage(chat_id=chat_id,text=w.word)
            if text.startswith('play music'):
                print('playing')
                bot.sendAudio(chat_id=chat_id,
                              audio='CQADBQADOQAD1KPoVHjBXgkKYx1mAg',
                              caption='Richard Wagner - Das Rheingold Act II')
            if text.startswith('firebase='):
                text = text[9:]
                print('print to firebase:')
                firebase.post('/Telegram', {
                    'User': '******',
                    'Date': date,
                    'Text': text
                })
                print(text)
            if text.startswith('New security code'):
                bot.sendMessage(chat_id=chat_id,
                                text='Welcome, how may I help you?')
            if text.startswith('How about some music'):
                bot.sendMessage(chat_id=chat_id, text='Selection?')
            if text.startswith('Richard Wagner'):
                bot.sendMessage(chat_id=chat_id,
                                text='Yes, David. As you wish.')
                bot.sendAudio(chat_id=chat_id,
                              audio='CQADBQADOQAD1KPoVHjBXgkKYx1mAg',
                              caption='Richard Wagner - Das Rheingold Act II')
            #if text=='show state':
            #bot.sendMessage(chat_id=chat_id,text=str(state))
            if text == 'state to 1':
                updater.stuff(1)
                print('now state=')
                print(globalstate.state)
            if text == 'state to 2':
                updater.stuff(2)
                print('now state=')
                print(globalstate.state)
            if text == 'state to 3':
                updater.stuff(3)
                print('now state=')
                print(globalstate.state)
            if text == 'clear state':
                updater.stuff(0)
                print('now state=')
                print(globalstate.state)
            if text == 'show':
                #haha=globalstate.state
                print('show state')
                print(globalstate.state)
                if globalstate.state == 1:
                    bot.sendMessage(chat_id=chat_id, text='in state 1')
                if globalstate.state == 2:
                    bot.sendMessage(chat_id=chat_id, text='in state 2')
                if globalstate.state == 3:
                    bot.sendMessage(chat_id=chat_id, text='in state 3')
                if globalstate.state == 0:
                    bot.sendMessage(chat_id=chat_id, text='in state 0')
    print('get message by POST')
    return 'ok'
예제 #59
0
        name = st.text_input("Enter your name")
        ta = st.text_area("Enter Insight")

        if st.button("Submit"):
            if ta and name and indicator_list:
                ii_ct = country_list
                ii_il = indicator_list

                rtdata = {
                    'Name': name,
                    'Insight': ta,
                    'Plot': [ii_ct, ii_il],
                    'Approved': 'No'
                }

                firebase.post('Insights/', rtdata)

                st.success("Insight successfully submitted!")
            else:
                st.error("Please fill all fields!")

        st.markdown(""" **Note**: 
                Once you submit an insight, it will be sent for review. 
                If your insight is deemed interesting by the Admin, it will be posted on the 'Interesting Insights' page. 
            """)

if page == 'About the Dataset':
    st.write("""
        # About the dataset
        
        The primary World Bank collection of development indicators, compiled from officially-recognized international sources. 
from firebase import firebase
firebase = firebase.FirebaseApplication(
    'https://treadmill-b0a11.firebaseio.com/', None)
##result = firebase.get('/data',None)
result = firebase.post('/data', {
    'mode': 'Recovery',
    'time': '10:00:59',
    'timestamp': '27/12/2018 01:04:00'
})
print(result)