コード例 #1
0
 def clickRed(self, *args):
     if args[0].state == "normal":
         firebase = fire.FirebaseApplication(fburl, token)
         firebase.put('/', 'redLed', False)
         self.redLedButton.text = "Off"
     else:
         firebase = fire.FirebaseApplication(fburl, token)
         firebase.put('/', 'redLed', True)
         self.redLedButton.text = "On"
コード例 #2
0
 def clickYellow(self, instance):
     if (self.yellowLedButton.state == "normal"):
         firebase = fire.FirebaseApplication(fburl, token)
         firebase.put('/', 'yellowLed', False)
         self.yellowLedButton.text = "Off"
     else:
         firebase = fire.FirebaseApplication(fburl, token)
         firebase.put('/', 'yellowLed', True)
         self.yellowLedButton.text = "On"
コード例 #3
0
ファイル: Flag.py プロジェクト: rajanramprasadh/BackEnd
class Flag:
	def __init__(self):
		self.birthday=''
	def flag(*data, *a)
		firebase=firebase.FirebaseApplication('https://ramprasadhsample.firebaseio.com/', None)
		json_data=data['birthdate']
		for email in a['email']
コード例 #4
0
    def __init__(self, **kwargs):
        super(root, self).__init__(**kwargs)
        self.cols = 2

        firebase = fire.FirebaseApplication(fburl, token)
        redLedState = firebase.get('/redLed')
        if (redLedState == True):
            redLedState = "On"
        else:
            redLedState = "Off"
        yellowLedState = firebase.get('/yellowLed')
        if (yellowLedState == True):
            yellowLedState = "On"
        else:
            yellowLedState = "Off"

        self.add_widget(Label(text="Yellow LED", size_hint=(0.5, 1)))
        self.yellowLedButton = ToggleButton(text=yellowLedState,
                                            on_press=self.clickYellow,
                                            size_hint=(0.5, 0.5))
        self.add_widget(self.yellowLedButton)

        self.add_widget(Label(text="Red LED", size_hint=(0.5, 1)))
        self.redLedButton = ToggleButton(text=redLedState,
                                         on_press=self.clickRed,
                                         size_hint=(0.5, 0.5))
        self.add_widget(self.redLedButton)
コード例 #5
0
 def __init__(self, pattern):
     path = '{}/teachers_cache.txt'.format(os.getcwd())
     self.pattern = pattern
     self.teachers_file = open(path, 'r')
     self.firebase_client = firebase.FirebaseApplication(
         "https://rembot-68f41.firebaseio.com/", None)
     self.teacher_info = dict()
コード例 #6
0
 def firebase_upload(self, dns, url, name, document):
     '''
     url_endpoint - destination to store document data
     document - local file location of document
     '''
     client = firebase.FirebaseApplication(dns, None)
     error_count = 0
     while True:
         try:
             if isinstance(document, str):
                 with open(os.path.join(os.getcwd(), document), 'r') as f:
                     db_dict = json.load(f)
                     print "pushing large dict.."
                     result = client.put(url,
                                         name,
                                         db_dict,
                                         params={'print': 'silent'})
                     print result
             elif isinstance(document, dict):
                 result = client.put(url,
                                     name,
                                     document,
                                     params={'print': 'silent'})
         except Exception as e:
             print e
             if error_count > 20:
                 break
             else:
                 error_count += 1
                 continue
         else:
             error_count = 0
             break
コード例 #7
0
ファイル: Main.py プロジェクト: Harshch7931/WindGuru
 def __init__(self):
     print "Executing ..."
     firebaseDetails = FirebaseDetails()
     self.firebase = fb.FirebaseApplication(firebaseDetails.getURL(),
                                            firebaseDetails.getAuth())
     self.URL = "http://www.weatherlink.com/user/constantwind/"
     # self.test()
     self.startLoop()
コード例 #8
0
 def get(self):
     firebas = firebase.FirebaseApplication(
         'https://Urban-HeatIsland-Project.firebaseio.com/urban-heatisland-project.json',
         None)
     id = firebas.get('/id', None)
     for i in id:
         logging.info("ID" + i)
     self.render("map.html")
コード例 #9
0
 def __init__(self,
              url='https://boiling-heat-5294.firebaseio.com/',
              secret_key='5zF8T37NlZB1HBHkb9T1zAZ6c2cPbXiXlzP5yJ8P',
              email='*****@*****.**'):
     self.authentication = firebase.FirebaseAuthentication(
         secret_key, email, True, True)
     self.fb = firebase.FirebaseApplication(url, self.authentication)
     self.url = url
コード例 #10
0
def get_firebase_app(root_url = _ROOT_URL):
    """Returns firebase db reference with given root_url

    Returns:
        FirebaseApplication: firebase db

    Args:
        root_url (str): firebase root url
    """
    return firebase.FirebaseApplication(root_url, None);
コード例 #11
0
 def upload(self, document_tuple):
     '''
     input: ('food_code': 'food_document')
     uploads given dictionary to firebase destination
     '''
     curproc = multiprocessing.current_process()
     client = firebase.FirebaseApplication(self.dns, None)
     return client.put(self.url,
                       document_tuple[0],
                       document_tuple[1],
                       params={'print': 'silent'})
コード例 #12
0
def Upload_to_Firebase(json):
    DSN = 'https://<application>.firebaseio.com/'
    database = firebase.FirebaseApplication(DSN)

    node = '/' + 'current-concerts'

    # Delete existing data
    database.delete(node, None)

    # Add new data
    database.post(node, json)
コード例 #13
0
def get_app_fb(path=None):
    url = cfg.FIREBASE_STORAGE_URL + cfg.FIREBASE_DATA_URL + "/"

    if path is not None:
        if url[-1] == "/":
            url = url[:-1]
        url += "/" + path

    if url[-1] <> "/":
        url += "/"

    f = fb.FirebaseApplication(url, None)

    return f
コード例 #14
0
    def buttonbusiness(self):
        self.btn_clicks += 1
        fb = firebase.FirebaseApplication(
            'https://rasppiqueuems.firebaseio.com/')

        varDate = arrow.now('Asia/Kuala_Lumpur').format('YYYY-MM-DD')

        date = '/' + varDate
        qnum = str(self.btn_clicks)
        queue = '/' + qnum
        utc = arrow.utcnow()

        # QR Code Content
        qrcontent = varDate + '|' + qnum
        qc = pyqrcode.create(qrcontent)
        qc.png('toPrint/qc.png', scale=8)
        # print(qc.terminal(quiet_zone=1))

        pdf = FPDF(orientation='P', format='A4')
        pdf.add_page()
        pdf.set_font("Arial", size=20)

        imgTemp = BytesIO()
        imgDoc = canvas.Canvas(imgTemp, pagesize=A4)
        path = 'toPrint/qc.png'
        imgDoc.drawImage(path, 150, 490)
        imgDoc.save()

        pdf.cell(200, 10, txt="Queue Ticket", ln=1, align="C")
        pdf.image('toPrint/qc.png', 93, 20, 33)
        pdf.cell(198, 80, qnum, 0, 1, 'C')
        pdf.cell(198, -50, txt="Counter 8", ln=1, align="C")
        pdf.output("toPrint/ticketPrint.pdf")

        fb.put(
            '', '/queues' + date + queue, {
                "QNum": qnum,
                "Status": "Pending",
                "Service": "Business",
                "Time": utc.to('Asia/Kuala_Lumpur').format('HH:mm:ss'),
                "TDate": utc.to('Asia/Kuala_Lumpur').format('YYYY-MM-DD'),
            })
        # subprocess.Popen("/home/pi/PycharmProjects/piQueue/toPrint/ticketPrint.pdf", stdin=subprocess.PIPE)
        # for windows #
        # os.startfile("/home/pi/PycharmProjects/piQueue/toPrint/ticketPrint.pdf", "print")
        # for pi #
        os.system(
            "lpr -P Printer_Name /home/pi/PycharmProjects/piQueue/toPrint/ticketPrint.pdf"
        )
コード例 #15
0
def send_data():
    firebaseq = firebase.FirebaseApplication(
        'https://smart-irrigation-outer.firebaseio.com/', None)
    result = firebaseq.get('', '')

    d = {}
    for data in result:
        if data == "present":
            continue
        else:
            #print result[data]
            for key, value in result[data].items():
                if key == "output":
                    continue
                else:
                    try:
                        d[key].append(value)
                    except KeyError:
                        d[key] = [value]
    return d
コード例 #16
0
ファイル: firebase_my.py プロジェクト: weeneen02/code_traning
    def __init__(self, uid=None, passwd=None):
        self.firebase = firebase.FirebaseApplication(
            "https://mynote-724e7.firebaseio.com/", None)
        self.user_hash = None
        self.allowed = False
        try:
            self.users = self.firebase.get("/users/", None)
        except:
            print("Connection Error")
            pass

        if uid and passwd:
            self.login_account(uid, passwd)
        else:
            print("You don't input ID, PASSWD")
            ans = raw_input("Would you like create your own account?")

            if ans in ["yes", "y"]:
                self.enroll_account()
                print("Wel come!")
            else:
                print("Now is offline")
コード例 #17
0
ファイル: master.py プロジェクト: lubert/rdiodj
    def handle(self, room_name, *args, **kwargs):
        self.firebase = firebase.FirebaseApplication(settings.FIREBASE_URL)
        auth = firebase.FirebaseAuthentication(settings.FIREBASE_TOKEN,
                                               '*****@*****.**')
        self.firebase.authentication = auth
        self.rdio = Rdio(RDIO_OAUTH2_KEY, RDIO_OAUTH2_SECRET, {})
        self.party_name = room_name
        self.party_data = self.get_party_data()
        self.currently_playing = None
        self.last_saw_users = datetime.now()

        self.currently_playing = None
        if 'player' in self.party_data and 'playingTrack' in self.party_data[
                'player']:
            track_key = self.party_data['player']['playingTrack']['trackKey']
            self.current_track_duration = self.rdio.get(
                keys=track_key)[track_key]['duration']
            self.current_start_time = datetime.now() - timedelta(
                seconds=self.party_data['player']['position'])
        else:
            self.current_track_duration = None
            self.current_start_time = None

        self.run()
コード例 #18
0
def accessdbFirebaseWithAuth(dsn, SECRET_KEY, email, admin=False):
    '''
    ------------FUNZIONAMENTO----------------
    Funzione tramite la quale si apre la connessione col Database

    Parametri d'ingresso:  dsn -> url del database
                           SECRET_KEY -> Chiave segreta del database Firebase
                           email -> email fittizia da attribuire ad ogni centralina  (utile alla scrittura dei log)
                           admin -> possibilità di accedere al database in modalità admin  (utile all'utilizzo della funzione quando il file viene richiamato come script per effettuare test)
    Parametro di ritorno:  db -> variabile che contiene il collegamento al database tramite cui si effettuano le operazioni su di esso

    '''

    from firebase import firebase
    import datetime

    auth = firebase.FirebaseAuthentication(
        SECRET_KEY, email, admin,
        admin)  # funzione che serve a creare l'autenticazione
    db = firebase.FirebaseApplication(
        dsn, auth
    )  # accedo al database con l'url "dsn" e l'autorizzazione e istanzio l'oggetto db

    return db  # ritorna l'oggetto tramite il quale accediamo al DataBase
コード例 #19
0
import firebase as fb
import matplotlib.pyplot as plt

(superSecret, url) = ('IMXOxXD3FjOOUoMGJlkAK5pAtn89mGIWAEnaKJhP', 'https://1678-strat-dev-2016.firebaseio.com/') 
basicURL = "http://www.thebluealliance.com/api/v2/"
headerKey = "X-TBA-App-Id"		
headerValue = "blm:OPRs:004"

auth = fb.FirebaseAuthentication(superSecret, "*****@*****.**", True, True)

def zscore(lis, x):
	return (x - np.mean(lis)) / np.std(lis)

def oprFromZScore(lis, z):
	return (z * np.std(lis)) + np.mean(lis)

firebase = fb.FirebaseApplication(url, auth)
teams = map(lambda k: k.encode('utf-8'), firebase.get('/Teams', None).keys())
fpas = map(lambda k: np.log(firebase.get('/Teams/' + k + '/calculatedData', 'firstPickAbility')), teams)
o = requests.get(basicURL + "event/" + "2016casj" + "/stats" ,headers={headerKey:headerValue}).json()["oprs"]
oprs = map(lambda k: o[k], teams)
normalOPRs = map(lambda e: np.log10(e), oprs)
zscores = map(lambda a: zscore(fpas, a), fpas)
print zscores
zScoreToLogOPR = map(lambda a: oprFromZScore(normalOPRs, a), zscores)
fpaToOPR = map(lambda a: 10 ** a, zScoreToLogOPR)
print len(fpaToOPR), len(oprs)
print zip(oprs, fpaToOPR)
plt.hist(oprs, bins=10)
plt.hist(fpaToOPR, bins=12, alpha = 0.3)
plt.show()
コード例 #20
0
import firebase

url = 'https://pythontestcode.firebaseio.com/'
connection = firebase.FirebaseApplication(url)

node = []

see = 'download'

result = connection.get('/AmnatCharoen/speedtest/Bangkok', None)

print result

for i in result:
    print result[i][see][0]
コード例 #21
0
import RPi.GPIO as GPIO
import firebase
import time

fburl = "https://kivyled.firebaseio.com/"
token = "STPBn7iDLmuAITbCgSvAjVKV7HfzxBX1FyTSnzQj"

firebase = firebase.FirebaseApplication(fburl, token)

# Use the BCM GPIO numbers as the numbering scheme
GPIO.setmode(GPIO.BCM)

# Use GPIO12, 16, 20 and 21 for the buttons.
buttons = {'red': 24, 'yellow': 23}

# Set GPIO numbers in the list: [12, 16, 20, 21] as input with pull-down resistor.
GPIO.setup(buttons.values(), GPIO.IN, GPIO.PUD_DOWN)

redStatus = firebase.get('/redLed')
yellowStatus = firebase.get('/yellowLed')

while True:
    # Check each button to determine whether any of them has been pressed. If
    # the OK button is pressed, the program exits the while loop and writes the
    # movement_list to the Firebase database. If any of the directional buttons
    # are pressed, the commands should be stored in the movement_list.

    # Write your code here
    if (redStatus == False):
        GPIO.output(23) = GPIO.HIGH
        time.sleep(0.25)
コード例 #22
0
import firebase as firebase

fb = firebase.FirebaseApplication('https://sentimentcloud.firebaseio.com',
                                  None)

job = {'duration': 30, 'status': 'waiting', 'keywords': 'happy'}

fb.put('/jobs', 'j-20', job)
コード例 #23
0
                        value["car_id"]]["timestamp"] < value["timestamp"]:
                    # Same car_id but newer data
                    cars[value["car_id"]] = value
            except:
                cars[value["car_id"]] = value

    for key, value in cars.items():
        print(key, value)

    return cars


@socketio.on('trigger_camera')
def trigger_camera():
    print('trigger_camera received, broadcasting')
    emit('trigger_camera', broadcast=True)


@socketio.on('update_ui')
def update_ui():
    print('update ui in main')
    emit('update_ui_for_browser', broadcast=True)


if __name__ == '__main__':
    PREV_STATION = 1
    MY_STATION_ID = 2
    firebase = firebase.FirebaseApplication(
        'https://metronome-nyc.firebaseio.com', None)
    socketio.run(app)
            cam.release()
    gc.collect()


#Initialize Files Directory
OS_UPPER_PATH = os.getcwd()
weights_file = OS_UPPER_PATH + "/KERAS_Weights_CNR_Parks_tuned_lr_1_e4_dc_5e_4_A.h5"
temp_img_name = "tmp_big_img_captured.jpg"
temp_cropped_img_name = "_tmp_cropped_img.jpg"
time_output_name = "time_statistics.txt"
garbage_list = []
time_counter = TimeCounter()
writer = FileWriterObject(OS_UPPER_PATH + "/" + time_output_name)

#Initialize firebase
firebase = firebase.FirebaseApplication(
    'https://car-park-detection.firebaseio.com', None)

#Crop position set
img_crop_pos = {}
img_crop_pos[0] = ImageCropSet(x=458, y=518, w=60, h=60)
img_crop_pos[1] = ImageCropSet(x=385, y=480, w=67, h=56)
img_crop_pos[2] = ImageCropSet(x=646, y=504, w=60, h=60)
img_crop_pos[3] = ImageCropSet(x=149, y=310, w=16, h=16)
img_crop_pos[4] = ImageCropSet(x=133, y=301, w=15, h=15)
img_crop_pos[5] = ImageCropSet(x=458, y=518, w=60, h=60)
img_crop_pos[6] = ImageCropSet(x=385, y=480, w=67, h=56)
img_crop_pos[7] = ImageCropSet(x=646, y=504, w=60, h=60)
img_crop_pos[8] = ImageCropSet(x=149, y=310, w=16, h=16)
img_crop_pos[9] = ImageCropSet(x=133, y=301, w=15, h=15)
img_crop_pos[10] = ImageCropSet(x=149, y=310, w=16, h=16)
img_crop_pos[11] = ImageCropSet(x=133, y=301, w=15, h=15)
コード例 #25
0
 def __init__(self):
     os.chdir('/home/vinicius/rembot')
     self.file = open('contact/teachers_cache.txt', 'w')
     self.firebase_client = firebase.FirebaseApplication(
         "https://rembot-68f41.firebaseio.com/", None)
コード例 #26
0
ファイル: Raspberry.py プロジェクト: ahon-rc/RPi
import RPi.GPIO as GPIO
import firebase as firebase

x=y=z=0;
LED=3;
FAN=5;
AC=7;

GPIO.cleanup();
GPIO.setmode(GPIO.BOARD);
GPIO.setup(LED,GPIO.OUT);
GPIO.setup(FAN,GPIO.OUT);
GPIO.setup(AC,GPIO.OUT);

firebase = firebase.FirebaseApplication('https://awesome-9caed.firebaseio.com/',None);
while True:
    x = firebase.get('LIGHT',None);
    y = firebase.get('FAN',None);
    z = firebase.get('AC',None);
    if(x==1):
        GPIO.output(LED,True);
    else:
        GPIO.output(LED,False);
    if(y==1):
        GPIO.output(FAN,True);
    else:
        GPIO.output(FAN,False);
    if(z==1):
        GPIO.output(AC,True);
    else:
        GPIO.output(AC,False);
コード例 #27
0
import serial

import subprocess

GPIO.setmode(GPIO.BOARD)

GPIO.setwarnings(False)

LED_OUT = 10

MOTION_IN = 8

device_file = ""

url = 'https://temp-sensor-94648.firebaseio.com'
fb = firebase.FirebaseApplication(url, None)

GPIO.setup(LED_OUT, GPIO.OUT)

GPIO.setup(MOTION_IN, GPIO.IN)
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

print("Sensor initializing............")

time.sleep(1)

print('Sensor Ready....')
コード例 #28
0
#Test
User1 = 'xXBfXTFkDFb466ZsFGDTCCq3fkw1'

#API Token
stripe.api_key = 'sk_test_TdclpRssaEx5YI1mr5sVOdJu'
token = 'AIzaSyBIzEsqTlE5GvUHS1ZBxR8BNDnwGYzfxk4'
DNS = 'https://qwkpass.firebaseio.com/'
DNSUSERS = 'https://qwkpass.firebaseio.com/Users'
path = r'C:\Users/Brendan\Desktop\qwkpass-firebase-adminsdk-nsrie-62475f3567.json'
users = '/Users'

#Authentication
cred = credentials.Certificate(path)
default_app = firebase_admin.initialize_app(cred)
db = firebase.FirebaseApplication(DNS)

#Main
while 1 == 1:
    charge = []

    #Scan User
    name = input('Please scan your pass to exit! \n')

    #Convert User to str
    info = db.get(users, name)
    info_str = (str(info))

    if info_str == 'None':
        print("Case 1")
        print('Error! You are not registered!')
コード例 #29
0
import json
import firebase

from firebase.firebase import FirebaseApplication, FirebaseAuthentication
from firebase import jsonutil

firebase = firebase.FirebaseApplication(
    'https://team-foobar-maze-generator.firebaseio.com/', None)
key = 'abcdefghijklmnopqrstuvwxyz'


def encrypt(n, plaintext):

    result = ''

    for l in plaintext.lower():
        try:
            i = (key.index(l) + n) % 26
            result += key[i]
        except ValueError:
            result += l

    return result.lower()


def decrypt(n, ciphertext):

    result = ''

    for l in ciphertext:
        try:
コード例 #30
0
#!/usr/bin/env python

import os
import time
import firebase
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

app = firebase.FirebaseApplication("https://seatbookingsystem.firebaseio.com/",
                                   None)
status = app.get("/1", "status")

debug = True


def set_status(code):
    global status
    os.system("./set_status.py {}".format(code))
    status = code


def print_debug(signal, strength):
    if debug:
        print("Current status: {}, current signal: {}, strength: {}".format(
            status, signal, strength))


def listen_at(port, threshold=2, limit=20, delay=0.5):
    GPIO.setup(port, GPIO.IN)
    strength = 0