def id_probe(_id): sql = f"SELECT * FROM msg WHERE id={_id}" db = Connection() try: return db.get(sql)[0][3] except IndexError: return None
def fetch_id(uid, tpuid): db = Connection() sql = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}))""" try: return db.get(sql)[-1][0] except IndexError: return None
def is_accepted(uid, tpuid): db = Connection() sql = f"""SELECT * FROM `friends` WHERE ((`uid`={uid} AND `tpuid`={tpuid}) OR (`uid`={tpuid} AND `tpuid`={uid}))""" try: return db.get(sql)[-1][3] == 1 except IndexError: return 501
def login(self, email, pwd): _pwd = hashlib.sha256(pwd.encode()).hexdigest() sql = """ SELECT * FROM users WHERE email='%s' AND pwd='%s' """ % (email, _pwd) obj = Connection() if (obj.check(sql)): return obj.get(sql)[0] else: return False
def fetch_requests(uid): db = Connection() sql = f"SELECT * FROM `friends` WHERE `tpuid`={uid} AND flag=0" res = db.get(sql) ret = [] for i in res: ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'sender': fetchName(i[1]), 'recv': fetchName(i[2]) }) return ret
def fetch_friend_request(uid): sql = f"SELECT * FROM `friends` WHERE (`tpuid`={uid} OR `uid`={uid}) AND flag=0" db = Connection() res = db.get(sql) ret = [] for i in res: ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'sender': fetchName(i[1]), 'recv': fetchName(i[2]), 'datetime': i[4] }) return ret
def compute_neighbors(data, uid, babcock_mode=False): if (type(data) == dict): dst = haversine(data, {'x': 0, 'y': 0}) else: dst = data if babcock_mode: sql = f"SELECT * FROM `users` WHERE `id`!={uid}" else: update = f"UPDATE `users` SET dfe={dst} WHERE `id`={uid}" sql = f"SELECT * FROM `users` WHERE ( dfe>={dst}-2 AND dfe<={dst}+2 ) AND `id`!={uid}" db = Connection() res = db.get(sql) ret = [] for i in res: ret.append({'tpuid': i[0], 'name': i[1], 'bio': i[4]}) # print(ret, "nnin") return ret, dst
class Notifications: def __init__(self, uid): self.uid = uid self.db = Connection() def send(self, msg, link): sql = """ INSERT INTO notifications ( `uid`, `msg`, `link` ) VALUES ( %s, '%s', '%s' ) """ % (self.uid, msg, link) return self.db.set(sql) def fetch(self, spec="*"): sql = f"SELECT * FROM notifications WHERE `uid`={self.uid}" dat = self.db.get(sql) ret = [] for i in dat: ret.append({ 'id': i[0], 'msg': i[2], 'link': i[3], 'seen': i[4], 'datetime': i[5] }) return ret def see(self, _id): sql = f"UPDATE notifications SET `seen`=1 WHERE `id`={_id} AND `uid`={self.uid}" return self.db.set(sql) @staticmethod def super_see(uid, link=""): db = Connection() sql = f"UPDATE notifications SET `seen`=1 WHERE `link`='{link}' AND `uid`={uid}" return db.set(sql) @staticmethod def super_pop(uid, link=""): db = Connection() sql = f"DELETE FROM notifications WHERE `link`='{link}' AND `uid`={uid}" return db.set(sql)
def fetch_friends(uid): db = Connection() sql = f"SELECT * FROM `friends` WHERE (`uid`={uid} OR `tpuid`={uid}) AND flag=1" res = db.get(sql) ret = [] for i in res: if (uid == i[1]): ret.append({ 'id': i[0], 'uid': i[1], 'tpuid': i[2], 'prober': i[2], 'name': fetchName(i[2]) }) else: ret.append({ 'id': i[0], 'uid': i[1], 'prober': i[1], 'tpuid': i[2], 'name': fetchName(i[1]) }) return ret
class Messenger: def __init__(self, uid): self.uid = uid self.db = Connection() def send_message(self, msg, tpuid, _id, date_sent, quoted=0): msg = msg.replace('\\', '\\\\').replace('\"', '\\\"').replace('\'', "\\\'") # msg = json.dumps( msg ) sql = """ INSERT INTO msg ( `id`,`uid`, `tpuid`, `msg`, `quoted`, `date-sent`) VALUES (%s, %s, %s, '%s', '%s', '%s') """ % (_id, self.uid, tpuid, msg, quoted, date_sent) return self.db.set(sql) def room_id(self, tpuid): uid = self.uid sql = f"SELECT id FROM friends WHERE (tpuid={tpuid} OR `uid`={tpuid}) AND (`uid`={uid} OR tpuid={uid})" return self.db.get(sql)[0][0] def delete_message(self, _id): sql = f"DELETE FROM msg WHERE id={_id} AND `uid`={self.uid}" return self.db.set(sql) def see(self, tpuid): sql = f"UPDATE msg SET seen=1 WHERE `tpuid`={self.uid} AND `uid`={tpuid}" return self.db.set(sql) def seen(self, tpuid): sql = f"SELECT * FROM msg WHERE `tpuid`={tpuid}" try: return self.db.get(sql)[-1][5] == 1 except IndexError: return False def fetch_msg(self, tpuid, _id=0, fil=0): if (tpuid != '*'): sql = f"SELECT * FROM msg WHERE (`uid`={self.uid} AND `tpuid`={tpuid}) OR (`tpuid`={self.uid} AND `uid`={tpuid}) AND id>={_id}" else: sql = f"SELECT * FROM msg WHERE (`uid`={self.uid} OR `tpuid`={self.uid}) AND id>={_id}" res = self.db.get(sql) ret = [] for i in res: filtered = i[3] offensive = json.load(open("extras/offensive.json", "r")) for j in offensive: filtered = filtered.replace(j, offensive[j]) ret.append({ 'id': i[0], 'uid': i[1], 'msg': i[3], 'filtered': filtered, 'quoted': Messenger.id_probe(i[4]), 'seen': i[5] == 1, 'date-sent': i[6] }) return ret @staticmethod def id_probe(_id): sql = f"SELECT * FROM msg WHERE id={_id}" db = Connection() try: return db.get(sql)[0][3] except IndexError: return None
class Watch: def __init__(self): print("#> INITIALIZING STOCK API PIPELINE ") [self.sell,self.buy,self.trade] = [SellingConditions(),TradingConditions(),BuyingConditions()] self.notif = Notification() self.prev_hist = {} self.complist = pd.Series( open("symbols.txt", "r").readlines() ) # self.complist = pd.read_csv('companylist.csv') tolower = lambda x: x.lower().strip() # self.tickers = ['msft'] self.db = Connection() self.tickers = self.complist.apply( tolower ) th = Thread(target = self.main, args = ()) th.daemon = True th.start() print("### STOCK API PIPELINE RUNNING ON %s " % th) def main(self, stock = "*"): run_event = Event() run_event.set() while True: try: for i in self.tickers: try: ticker = yf.Ticker(i) hist = ticker.history(period = "min") except: continue # hist = pd.read_csv("ext/dat.csv") hist.pop("Volume") if (i not in self.prev_hist): if ( len(hist) > 0 ): self.resolve_movers(hist, i) self.prev_hist[i] = hist.iloc[-1].to_dict() else: self.handle_delisted( i ) else: if ( hist.iloc[-1].to_dict() != self.prev_hist[i] ): if ( len(hist) > 0 ): self.resolve_movers(hist, i) self.prev_hist[i] = hist.iloc[-1].to_dict() else: self.handle_delisted( i ) except KeyboardInterrupt: print("#> TERMINATING STOCK API PIPELINE... ") run_event.clear() print("### TERMINATION SUCCESSFUL ") sys.exit() except requests.exceptions.ConnectionError: print("### COULD NOT CONNECT TO STOCK MARKET API\n#> RETRYING... ") def handle_delisted(self, symbol = ""): # method to resolve those that have seen their conditions # info = ticker.info selling = self.exec_delisted( 'sell',symbol ) buying = self.exec_delisted( 'buy', symbol ) trading = self.exec_delisted( 'trade', symbol ) # print("Sellers: ", selling) # print("Buyers: ", buying) # print("Others: ", trading) t1 = Thread(target = self.notif.bulk, args = (selling, symbol, 'delisted')) t1.start() t2 = Thread(target = self.notif.bulk, args = (buying, symbol, 'delisted')) t2.start() t3 = Thread(target = self.notif.bulk, args = (trading, symbol, 'delisted')) t3.start() def resolve_movers(self, req, symbol = ""): # method to resolve those that have seen their conditions # info = ticker.info selling = self.exec_sql( 'sell', req, symbol ) buying = self.exec_sql( 'buy', req, symbol, 'less' ) trading = self.exec_sql( 'trade', req, symbol, 'equal' ) # print("Sellers: ", selling) # print("Buyers: ", buying) # print("Others: ", trading) t1 = Thread(target = self.notif.bulk, args = (selling, symbol, 'selling')) t1.start() t2 = Thread(target = self.notif.bulk, args = (buying, symbol, 'buying')) t2.start() t3 = Thread(target = self.notif.bulk, args = (trading, symbol, 'trade')) t3.start() def exec_delisted(self, tbl, symb): sql = f"SELECT `uid` FROM `%s` WHERE `name`='{symb}'" % tbl try: uids = self.db.get(sql) self.db.set(f"DELETE FROM `%s` WHERE `name`='{symb}'" % tbl) return uids except Exception as e: raise e def exec_sql( self, tbl, req, symbol, arith_meth = "greater" ): if ( arith_meth == "greater" ): sql = """ SELECT `uid` FROM `%s` WHERE `open`<=%s AND close<=%s AND high<=%s AND low<=%s AND dividends<=%s AND splits<=%s AND name='%s' """ % ( tbl, req.Open.iloc[-1], req.Close.iloc[-1], req.High.iloc[-1], req.Low.iloc[-1], req.Dividends.iloc[-1], req['Stock Splits'].iloc[-1], symbol ) elif ( arith_meth == "less" ): sql = """ SELECT `uid` FROM `%s` WHERE `open`>=%s AND close>=%s AND high>=%s AND low>=%s AND dividends>=%s AND splits>=%s AND name='%s' """ % ( tbl, req.Open.iloc[-1], req.Close.iloc[-1], req.High.iloc[-1], req.Low.iloc[-1], req.Dividends.iloc[-1], req['Stock Splits'].iloc[-1], symbol ) elif ( arith_meth == "equal" ): sql = """ SELECT `uid` FROM `%s` WHERE `open`=%s AND close=%s AND high=%s AND low=%s AND dividends=%s AND splits=%s AND name='%s' """ % ( tbl, req.Open.iloc[-1], req.Close.iloc[-1], req.High.iloc[-1], req.Low.iloc[-1], req.Dividends.iloc[-1], req['Stock Splits'].iloc[-1], symbol ) try: return self.db.get( sql ) except Exception as e: print(req) raise e
def name(uid): db = Connection() sql = f"SELECT * FROM users WHERE id={uid}" return db.get(sql)[0][1] if db.check(sql) == True else "Anonymous"