def main(): config = { "apiKey": "AIzaSyBkQ5z8Rs5IRP4lHoiWyXV9XVQHjAh-sEI", "authDomain": "a-eye-for-the-blind.firebaseapp.com", "storageBucket": "a-eye-for-the-blind.appspot.com", "databaseURL": "https://a-eye-for-the-blind-default-rtdb.firebaseio.com/", } uid = "^^^^^^^^^^^" # unique user ID, must set before running email = '*****@*****.**' password = '******' firebase = Firebase(config) db = firebase.database() auth = firebase.auth() storage = firebase.storage() user = auth.sign_in_with_email_and_password(email, password) user = auth.refresh(user['refreshToken']) if uid == "" or email == "" or password == "": print("Please set user UID, email, or password in the lines above!") sys.exit() engine = pyttsx3.init() BATCH_SIZE = 1 eval_num_threads = 2 opt = TrainOptions().parse( ) # set CUDA_VISIBLE_DEVICES before import torch model = pix2pix_model.Pix2PixModel(opt) torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True best_epoch = 0 global_step = 0 model.switch_to_eval() video_list = 'D:/A-Eye For The Blind/2dtodepth/infile1/' save_path = 'D:/A-Eye For The Blind/2dtodepth/outfile/' uid = 'yQowLXfAMddiITuMFASMoKlSGyh1' # initialize the camera cam = cv2.VideoCapture(cv2.CAP_DSHOW) # 0 -> index of camera x = 0 while True: s, img = cam.read() cv2.imwrite("D:/A-Eye For The Blind/2dtodepth/infile1/filename.jpg", img) # save image # filename = uid + ' ' + time() storage.child(f"images/i{str(x)}.jpg").put( "D:/A-Eye For The Blind/2dtodepth/infile1/filename.jpg", user['idToken']) url = storage.child(f"images/i{str(x)}.jpg").get_url(user['idToken']) data = {f"i{str(x)}": f"{url}"} db.child(f"users/{uid}").child("images").update(data) video_data_loader = aligned_data_loader.DAVISDataLoader( video_list, BATCH_SIZE) video_dataset = video_data_loader.load_data() for i, data in enumerate(video_dataset): stacked_img = data[0] targets = data[1] output = model.run_and_save_DAVIS(stacked_img, targets, save_path) height, width, _ = output.shape width_cutoff = width // 2 half1 = output[:, :width_cutoff] half2 = output[:, width_cutoff:] width_cutoff = width // 4 s1 = half1[:, :width_cutoff] s2 = half1[:, width_cutoff:] s3 = half2[:, :width_cutoff] s4 = half2[:, width_cutoff:] commands = finalcommand(s1, s2, s3, s4) print(commands) if commands[1] == 0: if commands[0] == 0 and commands[2] == 0: engine.say("STOP!") elif commands[0] == 0: engine.say("Move right.") elif commands[2] == 2: engine.say("Move left.") else: engine.say("Move left.") engine.runAndWait() os.remove("D:/A-Eye For The Blind/2dtodepth/infile1/filename.jpg") x += 1 if cv2.waitKey(33) == ord('a'): break cam.release()
def clear_firebase(): a = f.get() if a != None: for i in a: q = Firebase('https://huafhoi.firebaseio.com/items_filter') q.remove()
def get_nome_from_codigo(codigo): # Retorna nome do senador cujo código foi passado no argumento f = Firebase(FBURL + '/senadores/' + codigo + '/NomeParlamentar') return f.get()
def delete_vote(key): print('=== Remove vote ===') result = Firebase( 'https://project-***REMOVED***.firebaseio.com/dubwars/votes/{0}'. format(key)).delete()
from datetime import datetime import requests, json import re import firebase_admin from firebase_admin import storage as admin_storage, credentials, firestore # from firebase_admin import bucket firebaseConfig = { 'apiKey': "AIzaSyBexTA9lK-ruTMWVWEFaAzSKuIrNBjZ7vs", 'authDomain': "tiktokvideos-378aa.firebaseapp.com", 'storageBucket': "tiktokvideos-378aa.appspot.com", "databaseURL": "https://tiktokvideos-378aa-default-rtdb.firebaseio.com/", "serviceAccount": "./service_account.json", } firebase = Firebase(firebaseConfig) storage = firebase.storage() data = requests.get( 'http://ytserver.eu-gb.cf.appdomain.cloud/entertain/clean/') data = data.json() for i in data: data = i['nameofvideo'] # NextDay_Date = datetime.datetime.today() - datetime.timedelta(days=2) # formatted= NextDay_Date.strftime("%y-%m-%d") excluding = re.search('17', data) if excluding: print(data) storage.delete(data)
from firebase import Firebase import urllib3 as urllib from urllib.parse import urlparse import pickle with open('google_results', 'rb') as f: googlers = pickle.load(f) with open('urls', 'rb') as f: urls = pickle.load(f) f = Firebase('https://firebase.q-dev-challenge-hannah.firebaseapp.com', auth_token='xxx') for g in range(len(googlers)): for label in googlers[g]: f.push({ 'label': label['description'], 'score': label['score'], 'url': urls[g] })
from firebase import Firebase import requests import os import hashlib import base64 import math import time firebase = Firebase('https://project-***REMOVED***.firebaseio.com/') fb_contests = Firebase( 'https://project-***REMOVED***.firebaseio.com/dubwars/contests') fb_votes = Firebase( 'https://project-***REMOVED***.firebaseio.com/dubwars/votes') URL = 'https://dubhack.dubsmash.com' CLIENT_ID = '***REMOVED***' CLIENT_SECRET = '***REMOVED***' USERNAME = '******' PASSWORD = '******' headers = {} def login(): login_data = { 'username': USERNAME, 'password': PASSWORD, 'grant_type': 'password', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET
from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext, Filters from config import TOKEN, WEBHOOK_HOST, PORT import traceback from loguru import logger import random import string from firebase import Firebase from util import typing, uploading_video, mp4_to_gif firebase = Firebase() @typing def start_handler(update: Update, context: CallbackContext): update.message.reply_text("⛔") @typing def help_handler(update: Update, context: CallbackContext): update.message.reply_text("🚫") @typing def text_handler(update: Update, context: CallbackContext): update.message.reply_text("不陪聊。") @typing def other_handler(update: Update, context: CallbackContext): update.message.reply_text("只接受 Animation。") @uploading_video def animation_handler(update: Update, context: CallbackContext): message = update.message.reply_text("please wait :)")
from aws import AWS from firebase import Firebase from time import sleep from new_face import NewFace fb = Firebase() aws = AWS(fb) nf = NewFace(fb) def listen(): while True: data = fb.get_data() aws_start_requested = data['doorbell']['streaming']['start_requested'] aws_stop_requested = data['doorbell']['streaming']['stop_requested'] new_face_request = data['doorbell']['face']['start_new'] # aws stream check if aws_start_requested == 1 and aws.is_active is False: aws.start_stream() if aws_stop_requested == 1 and aws.is_active is True: aws.stop_stream() # if new face requested if new_face_request == 1 and nf.is_active is False and aws.is_active is False: nf.take_pictures() else: fb.update_data({'doorbell/face/start_new': 0})
def clear_firebase(): a = f.get() if a != None: for i in a: q = Firebase('https://welse-141512.firebaseio.com/items' + '/' + i) q.remove()
def __init__(self): self.tweet_firebase = Firebase('https://vmx.firebaseio.com/tweets') self.report_firebase = Firebase('https://vmx.firebaseio.com/reports')
"https://www.overclockzone.com/forums/" + title['href'], 'type': slug['slug'], 'time': item.find_all('span', {'class': 'label' })[0].get_text().split(",")[1], 'image': slug['image'] } items[slug['slug']].append(item_data) c += 1 return items def clear_firebase(): a = f.get() if a != None: for i in a: q = Firebase('https://welse-141512.firebaseio.com/items' + '/' + i) q.remove() f = Firebase('https://welse-141512.firebaseio.com/items') clear_firebase() items = scrap() sorted_item = sort_scrap_item(items) paged_item = create_item_page(sorted_item) f.set(paged_item)
size_hint_x: .5 theme_text_color: "Error" halign: "center" MDTextButton: id: signup_screen text: " [color=#000000]Já tens uma conta?[/color] [u]Criar[/u]" pos_hint: {"center_x": .5, "center_y": .1} size_hint_x: .5 markup: True """) APP = MDApp.get_running_app() LOGIN = Firebase() class LoginScreen(Screen): def __init__(self, **kw): super().__init__(**kw) self.ids.signup_screen.bind(on_release=self.back) self.ids.login_button.bind(on_release=self.login) def login(self, instance): email = self.ids.email.text password = self.ids.password.text if email != "": if password != "": self.login_return = LOGIN.login(email=email, password=password) if not self.login_return == "True": self.ids.error.text = str(self.login_return)
__author__ = 'EliFinkelshteyn' from firebase import Firebase import simplejson as json f = Firebase('http://demo.firebase.com/seifeet/poll_data') for item in json.load(open('../Data/obama.json')): if isinstance(item, dict): print 'about to push!' f.push(item) print 'done!'
import pytesseract import sys kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy app = Flask(__name__) CORS(app) cred = credentials.Certificate('key.json') default_app = firebase_admin.initialize_app(cred) db = firestore.client() pb = pyrebase.initialize_app(json.load(open('fbconfig.json'))) firebase = Firebase(json.load(open('fbconfig.json'))) storage = firebase.storage() @app.route("/") def home(): return '<h1> hello </h1>' @app.route("/post/<object>", methods=['POST']) def post(object): try: db.collection(object).add( request.json ) #By url we will get collection name & By post request we will get data return jsonify({"success": True}), 200
def match_captured_image_with_thumbnails(file_path): config = { "apiKey": "AIzaSyDwu5UlB1jj-rQI05L1VEKJovXYShgWRbk", "authDomain": "koobookandroidapp.firebaseapp.com", "databaseURL": "https://koobookandroidapp.firebaseio.com", "storageBucket": "koobookandroidapp.appspot.com" } firebase = Firebase(config) db = firebase.database() storage = firebase.storage() # Load photo that was captured from android device url = "Photos/" + file_path recently_captured_photo_url = storage.child(url).get_url(None) req = urllib.request.urlopen(recently_captured_photo_url) arr = np.asarray(bytearray(req.read()), dtype=np.uint8) img = cv2.imdecode(arr, 0) height, width = img.shape[:2] img = cv2.resize(img, (round(width / 10), round(height / 10)), interpolation=cv2.INTER_AREA) # Get all thumbnail urls from firebase database allUrls = db.child("Book_thumbnail_urls").get() for i in allUrls.each(): urls = i.item[1] # For each url retrieved from the database, use it to create an image via Cv2 and use it to run the brute force matching # Then get the top 5 matches distinace values, average it and store that along with the url in a dictionary top_matches_thumbnail_urls = {} for url in urls: if type(url) is str: req = urllib.request.urlopen(url) arr = np.asarray(bytearray(req.read()), dtype=np.uint8) img2 = cv2.imdecode(arr, 0) img2 = cv2.resize(img2, (round(width / 10), round(height / 10)), interpolation=cv2.INTER_AREA) # Credit to Pysource for the code https://www.youtube.com/watch?v=Fe-KWKPk9Zc # Define detector of similarities orb = cv2.ORB_create() keypoint1, descriptor1 = orb.detectAndCompute(img, None) keypoint2, descriptor2 = orb.detectAndCompute(img2, None) # Brute Force Matching bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False) # Find matches and sort based on accuracy/confidence # The smaller the match distance, the better the match if (descriptor1 is None or descriptor2 is None) is False: matches = bf.match(descriptor1, descriptor2) matches = sorted(matches, key=lambda x: x.distance) top_matches = matches[:3] sum = 0 for top_match in top_matches: sum += top_match.distance avg = sum / 3 top_matches_thumbnail_urls[url] = avg top_matches_thumbnail_urls = sorted(top_matches_thumbnail_urls.items(), key=lambda x: x[1]) top_matches_thumbnail_urls = top_matches_thumbnail_urls[:6] top_matches_thumbnail_urls = dict(top_matches_thumbnail_urls) top_thumbnail_urls = list(top_matches_thumbnail_urls.keys()) top_thumbnail_urls_concatanated = "#".join(top_thumbnail_urls) return top_thumbnail_urls_concatanated
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import codecs import yaml from firebase import Firebase import re f = Firebase('https://omagma-abe44.firebaseio.com/gearmotors') with codecs.open('a.json', "r", encoding='utf-8', errors='ignore') as data_file: data = json.load(data_file) dump_data = json.dumps(data) y_data = yaml.safe_load(dump_data) a = y_data[0] for y in y_data: firebase_data = {} for a in y: b = a if "Rated Current".lower() in a.lower(): b = 'rated current' key = re.sub(r'[\W.\/()]+', '', b).lower() firebase_data[key] = {'name': b, 'value': y[a]} print firebase_data print '\n\n=====\n\n' r = f.push(firebase_data)
strike_price : int/float, optional the strike_price Returns ------- pd.DataFrame a DataFrame of the summary data """ df = convert_timestamp(filter_measurements(df, **kwargs), last_time_stamp=True) return { **df[['volume', 'open_interest']].sum().to_dict(), **df[['implied_volatility']].mean().to_dict() } def get_spread(self, df): data = self.get_summary(df) results = df.groupby(['type'])[['volume', 'open_interest']].sum().to_dict() return pd.DataFrame([{ **{ '_'.join([m, t]): 100 * round(results[m][t] / data[m], 2) for m in ['volume', 'open_interest'] for t in ['call', 'put'] }, **data }]) df = Firebase().get('options/AMD_options_dynamic.csv') print(OptionAnalyzer(df, 'time_series').df) #print(OptionAnalyzer(df, 'summary',type='put').df)
__author__ = 'EliFinkelshteyn' from firebase import Firebase import simplejson as json import datetime #"Fri, 21 Sep 2012 16:53:08 +0000" def getTwitterDate(date): date = date[:-6] date = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S') date += datetime.timedelta( 0, -7*60*60) return date.strftime('%s') f = Firebase('http://demo.firebase.com/seifeet/twitter_data') for item in json.load(open('../Data/romney.json')): if isinstance(item,dict): item['date'] = getTwitterDate(item['created_at']) print 'about to push!' f.push(item) print 'done!'
# Customized Versions of imported Libraries for Firebase import json from firebase import Firebase jsonFile = open('./app/python_firebase/assets/FirebaseRESTKey.json') firebaseConfig = json.load(jsonFile) firebaseObj = Firebase(firebaseConfig) fireAuth = firebaseObj.auth()
def update_elo(snip, creator, elo, count): print('=== Update Elo ===') update = {'elo': elo, 'count': count} result = Firebase( 'https://project-***REMOVED***.firebaseio.com/dubwars/contests/{0}/dubs/{1}' .format(snip, creator)).update(update)
def init_fb(): firebase = Firebase(config) return firebase
def get_contest(snip, winner, loser): dubs = Firebase( 'https://project-***REMOVED***.firebaseio.com/dubwars/contests/{0}/dubs/' .format(snip)).get() return dubs[winner], dubs[loser]
similar_entities = sorted(similar_entities, key=lambda x: x[1]) return similar_entities[-1] if __name__ == '__main__': firebase_config = { "apiKey": "AIzaSyDZKI2COnqy7jbCooNG2sIJn4_0qRrhtDw", "authDomain": "wikidata-analysis.firebaseapp.com", "databaseURL": "https://wikidata-analysis.firebaseio.com", "projectId": "wikidata-analysis", "storageBucket": "", "messagingSenderId": "35972699557", "appId": "1:35972699557:web:8e0a19c7f368ee04" } firebase = Firebase(firebase_config) db = firebase.database() # Reading topic from kafka print('Creating connection.') consumer = KafkaConsumer(bootstrap_servers=KAFKA_BROKER_URL) print('Assigning Topic.') consumer.subscribe(['queueing.wikidata']) print('Getting message.') for message in consumer: data = message.value.decode('utf-8') data = json.loads(data) wikidata_id = "" try: result_object = {
def sort_scrap_item(items): today_list = [] yesterday_list = [] totald = [] for o in items: if "Today" in o['time']: today_list.append(o) else: yesterday_list.append(o) ntd = sorted(today_list, key=lambda k: k['time'], reverse=True) nyd = sorted(yesterday_list, key=lambda k: k['time'], reverse=True) totald = ntd + nyd return totald def clear_firebase(): a = f.get() if a != None: for i in a: q = Firebase('https://huafhoi.firebaseio.com/items_filter') q.remove() f = Firebase('https://huafhoi.firebaseio.com/items_filter') clear_firebase() items = scrap() sorted_item = sort_scrap_item(items) f.set(sorted_item)
from django.http import JsonResponse from django.shortcuts import render from django.views.generic import ListView from firebase import Firebase, firebase from django.contrib.auth.models import User # Create your views here. Config = { "apiKey": "AIzaSyBSIAwxO5geJSslxclj68G33dZ-yumOEMI", "authDomain": "mapstec-81290.firebaseapp.com", "databaseURL": "https://mapstec-81290.firebaseio.com", "storageBucket": "mapstec-81290.appspot.com", "measurementId": "G-85RHV43HWV" } _firebase = Firebase(Config) db = _firebase.database() class crear_evento(ListView): template_name = 'crear_evento.html' context_object_name = 'data' model = User class informacion(ListView): template_name = 'information.html' context_object_name = 'data' model = User class tablas(ListView):
from firebase import Firebase f = Firebase('https://tfgsrkapi.firebaseio.com/data') r = f.push({'user_id': 'wilma', 'text': 'Hello'}) print r
import os API_BINANCE_KEY = os.getenv("API_BINANCE_KEY") API_BINANCE_SECRET = os.getenv("API_BINANCE_SECRET") API_LINE_KEY = os.getenv("API_LINE_KEY") API_CLIENT_SECRET = os.getenv("API_CLIENT_SECRET") LINE_NOTIFY_TOKEN = os.getenv("LINE_NOTIFY_TOKEN") LINE_BOT_ACCESS_TOKEN = os.getenv("LINE_BOT_ACCESS_TOKEN") LINE_BOT_CHANNEL_SECRET = os.getenv("LINE_BOT_CHANNEL_SECRET") from firebase import Firebase firebaseConfig = { "apiKey": os.getenv("FIREBASE_API_KEY"), "authDomain": "bottrading-databse.firebaseapp.com", "databaseURL": os.getenv("DATABASE_URL"), "projectId": "bottrading-databse", "storageBucket": "bottrading-databse.appspot.com", "messagingSenderId": "1091910107557", "appId": "1:1091910107557:web:1606a1ddaa97fbc530284c" } firebaseClient = Firebase(firebaseConfig) auth = firebaseClient.auth() user = auth.sign_in_with_email_and_password(os.getenv("FIREBASE_EMAIL_AUTH"), os.getenv("FIREBASE_PASSWORD"))
from firebase import Firebase config = { "apiKey": "AIzaSyD14k9cwnVbCt7bNcFcB8S9E3LsHs-hhSI", "authDomain": "agendaai-e8d58.firebaseapp.com", "databaseURL": "https://agendaai-e8d58.firebaseio.com", "storageBucket": "agendaai-e8d58.appspot.com", } firebase = Firebase(config) auth = firebase.auth() def register(): name = str(input("What's your name? ")) username = input("Enter a username: "******"Enter your email: ") password = input("Enter your password: "******"Enter your password again: ") while password != verfpassword: print("You must to enter the SAME password!") register() break auth.create_user_with_email_and_password(email, password) print("Your account was create succefuly...") menu() def login(): username1 = input("username: ")
class FacialRecognition: # constant private variables _BASE_DIR = os.path.dirname(os.path.abspath(__file__)) _images_dir = os.path.join(_BASE_DIR, "user") _fb = Firebase() # indicator if registration is going on is_registration_on = False # bool value returned in relation to check if trained faces file exists. @staticmethod def trainer_exists(): return os.path.exists('trainer.yml') # loads .yml file of trainer def load_trainer(self): self._face_detector.read('trainer.yml') # constructor class def __init__(self): self._video = cv2.VideoCapture( 0) # capture video from source '0' - raspi camera # load face detection instructions - Created by Rainer Lienhart. self._cascade = cv2.CascadeClassifier( 'cascades/haarcascade_frontalface_default.xml') self._face_detector = cv2.face.LBPHFaceRecognizer_create( ) # creates face recognizer if self.trainer_exists(): # checks if trainer.yml exists self.load_trainer() self._servo = Servo() self._fb = Firebase() # convert's picture to grey using open cv method @staticmethod def _convert_to_grey(picture): return cv2.cvtColor(picture, cv2.COLOR_BGR2GRAY) # method which is looping recognising face front of the camera. def recognize(self): # ret - return boolean and frame is the current frame captured from the camera ret, frame = self._video.read() gray = self._convert_to_grey(frame) # detect faces through the cascade instructions faces = self._cascade.detectMultiScale(gray, 1.3, 5) # iterating through found objects for (x, y, w, h) in faces: # if user_id was associated with the face set active user face_id, score = self._face_detector.predict(gray[y:y + h, x:x + w]) self._fb.set_active_user(face_id) # train faces method def train_faces(self): faces = [] # an empty array for faces numeric arrays ids = [] # an empty array for user's id # walk through images in /user folder for root, dirs, images in os.walk(self._images_dir): for img in images: # if img has .jpg extension if img.endswith("jpg"): face_id = int(os.path.basename( root)) # getting face_id out of the folder name path = os.path.join( root, img ) # getting the path out of the picture number and root folder grey_img = Image.open(path).convert( 'L') # converts image to gray img_arr = np.array( grey_img, 'uint8') # creating numpy array out of the picture # takes currently loaded image and detects face on it. temp = self._cascade.detectMultiScale(img_arr) for (x, y, w, h) in temp: faces.append( img_arr[y:y + h, x:x + w]) # append face's array to faces array ids.append(face_id) # appends id to an ids array self._face_detector.train( faces, np.array(ids) ) # run's and train algorithm with detector instructions self._face_detector.save('trainer.yml') # saves yml output # the user registration process def take_pictures(self): Console.clear() print('Preparing ...') sleep(2) # flushes input buffer to prevent user input concatenation with previously pressed keys stdout.flush() tcflush(stdin, TCIOFLUSH) Console.clear() # Q1 email = input("What's email address?\n") # password loop to make sure user is entering the correct one. while True: password1 = getpass.getpass( "Set up your password (min 6 chars).\n") password2 = getpass.getpass("Repeat your password.\n") if password1 == password2: break # create firebase credentials self._fb.create_user(email, password1) # time countdown before take the picture (5s) ct = 5 Console.clear() while ct > 0: print( 'Please look at the camera now. We will take a few pictures in: %s' % ct) sleep(1) ct = ct - 1 os.system('clear') # check if folder already exists if os.path.exists('user') is False: os.mkdir('user') # get random id and if exists re-randomize again user_id = random.SystemRandom().randint(10000, 99999) while True: if os.path.exists('user/%s' % user_id) is False: os.mkdir('user/%s' % user_id) self._fb.update_data({"users/%s" % user_id: email}) break else: user_id = random.SystemRandom().randint(10000, 99999) counter = 0 # will count pictures which were taken # taking user's pictures while True: ret, frame = self._video.read( ) # ret - bool, frame - current camera frame gray = self._convert_to_grey(frame) # convert picture to greyscale faces = self._cascade.detectMultiScale(gray, 1.3, 5) # detect faces # iterate through detected for (x, y, w, h) in faces: cv2.imwrite("user/%s/%s.jpg" % (user_id, counter), gray[y:y + h, x:x + w]) counter = counter + 1 if counter == 10: # at the 10th picture stop self.train_faces() # run train algorithm # print successful message Console.clear() print('Your profile was created! Thanks!') sleep(3) # update broker and system with the information on registration self._fb.update_data({"registration_on_progress": False}) self.is_registration_on = False # show a regular message on the display Console.show_reg_msg() break