def listen(): listener = socket.socket() listener.bind((TCP_IP, TCP_PORT)) listener.listen() while True: conn, _ = listener.accept() print("connection accepted") data = conn.recv(66).decode() print("data:", data) _, flags = ensicoin.wait_for_pubkey(data) print("flags: ", flags) segments = None job_id = None if flags[0][0] == "[": segments = json.loads(flags[0]) job_id = flags[1] if flags[1][0] == "[": segments = json.loads(flags[1]) job_id = flags[0] print("segments: ", segments) print("job_id: ", job_id) database.update_state(database.open_db(), 26, job_id) print("saving results") points = solidator.create_points(segments) os.mkdir(job_id) os.chdir(job_id) solidator.remove_deg_1(points, job_id, True) result = open("result.svg", "r") svg_data = result.read() result.close() os.chdir("..") shutil.rmtree(job_id) database.open_db().write("/{}/result".format(job_id), svg_data) database.update_state(database.open_db(), 31, job_id)
def delete_person(self, value): p = None if isinstance(value, Person): p = self.find_person_by_name(value) if not p: raise ValueError('{0} {1} not found in directory'.format(value.first_name, value.last_name)) elif isinstance(value, Telephone): p = self.find_person_by_phone(value) if not p: raise ValueError('No person found for {0} in directory'.format(value.__str__())) else: raise ValueError('Must delete based on either a Person or a Telephone') db = database.open_db() cursor = db.cursor() try: cursor.execute(database.DELETE_PERSON, [p.id]) t = p.telephones[0] cursor.execute(database.DELETE_TELEPHONE, [t.id, t.person_id]) db.commit() except Exception as e: db.rollback() raise e else: cursor.close() db.close()
def get_all(self): '''Selects all available person/telephone entries and returns them in an array of Person objects''' db = database.open_db() cursor = db.cursor() cursor.execute(database.SELECT_ALL) people = [] for row in cursor: p = Person() p.id = int(row['p_id']) p.first_name = row['first_name'] p.middle_name = row['middle_name'] p.last_name = row['last_name'] t = Telephone() t.id = int(row['t_id']) t.person_id = int(row['t_p_id']) t.type = row['type'] t.country = row['country'] t.area = row['area'] t.city_code = row['city_code'] t.local_number = row['local_number'] t.extension = row['extension'] p.telephones.append(t) people.append(p) db.close() return people
def add_coins(address, coins): scope, _ = open_db(DB_FPATH) with scope() as s: user = s.query( models.User).filter(models.User.address == address).first() user.coins += coins print(f"User {address} now has {user.coins} coins")
def add_user(address, coins=2000): private_key = ''.join(random.choices(ascii_letters, k=10)) scope, _ = open_db(DB_FPATH) with scope() as s: s.add( models.User(address=address, private_key=private_key, coins=coins)) print(f"Private key: {private_key}")
def get_home(): db = open_db() cur = db.execute(''' select d.id date_id, d.entry_date , ifnull(sum(f.protein),0) protein , ifnull(sum(f.carbs),0) carbs , ifnull(sum(f.fat),0) fat , ifnull(sum(f.calories),0) calories from dates d left join daily_intake i on i.date_id = d.id left join foods f on f.id = i.food_id group by d.id order by d.entry_date desc ''') raw_results = cur.fetchall() db.close() results = [] for i in raw_results: db_date = datetime.strptime(str(i['entry_date']), '%Y%m%d') ft_date = datetime.strftime(db_date, '%B %d, %Y') result = {} result['date_id'] = i['date_id'] result['entry_date'] = i['entry_date'] result['formatted_date'] = ft_date result['protein'] = i['protein'] result['carbs'] = i['carbs'] result['fat'] = i['fat'] result['calories'] = i['calories'] results.append(result) return render_template('home.html', results=results)
def add_contest(g1, g2, begin, end): scope, _ = open_db(DB_FPATH) with scope() as s: s.add( models.Contest(first_girl_id=g1, second_girl_id=g2, begin=begin, end=end))
def add_girl(name, instagram, photo): scope, _ = open_db(DB_FPATH) with scope() as s: s.add( models.Girl(name=name, instagram=instagram, ELO=Config.DEFAULT_ELO, photo=photo))
def terminate(db, job_id, mill_stub): """Finishes the job *job_id* and forwards it to the *mill_stub* """ database.update_state(database.open_db(), 2, job_id) segments = json.loads(db.read("/a_pi/{}/segments".format(job_id)).value) segments = [ mill_pb2.Segment(a=mill_pb2.Point(x=s[0], y=s[1]), b=mill_pb2.Point(x=s[2], y=s[3])) for s in segments ] mill_stub.Turn(mill_pb2.Job(id=job_id, segments=segments)) database.update_state(database.open_db(), 3, job_id) db.delete("/a_pi/{}/segments".format(job_id)) db.delete("/a_pi/{}/digit".format(job_id))
def write(job_id, text): """Writes a *text* by an html form """ print(text) database.update_state(database.open_db(), 11, job_id) display = Display(visible=0, size=(1024, 768)) display.start() browser = webdriver.Firefox() actions = webdriver.ActionChains(browser) browser.get("file:///app/test.html") message = browser.find_element_by_name("message") message.send_keys(text) job = browser.find_element_by_name("job") job.send_keys(job_id) job.submit() database.update_state(database.open_db(), 12, job_id)
def translation(segments, job_id, gpg): """Creates replicas of the segments in the eight directions """ print('translating') segments = translator.translate_segments(segments, True) database.update_state(database.open_db(), 16, job_id) send(SMTP_ADDR, segments, job_id, gpg)
async def handle_DATA(self, server, session, envelope): """Handles the content of a mail """ print('handle_DATA') message = envelope.content.decode('utf8', errors='replace') message = decrypt(message) job_id = message.split("|")[0].strip() database.update_state(database.open_db(), 20, job_id) segments = json.loads(message.split("|")[1].strip()) print('segments', segments) new_segments = [] for (x1, y1), (x2, y2) in segments: new_segments.append(split.Segment(split.Vect(x1, y1), split.Vect(x2, y2))) database.update_state(database.open_db(), 21, job_id) cut_segments = split.cut(new_segments) database.update_state(database.open_db(), 22, job_id) print('job_id: ', job_id) sk1, pk1 = ensicoin.generate_keys() database.open_db().write("/{}/address".format(job_id), pk1) sk2, pk2 = ensicoin.generate_keys() print('connecting to solidator') solidator_socket = socket.create_connection((SOLIDATOR_ADDRESS, SOLIDATOR_PORT)) print('sending pk2') solidator_socket.send(pk2.encode()) database.update_state(database.open_db(), 23, job_id) print('waiting for payment') hashtx, _ = ensicoin.wait_for_pubkey(pk1) print('hashtx: ', hashtx) ensicoin.send_to(10, hashtx, 0, sk1, 42, pk2, [job_id, "'" + json.dumps(split.generate_id_tuple(cut_segments)) + "'"], job_id) print('payment sent') database.update_state(database.open_db(), 24, job_id) return '250 Message accepted for delivery'
def get_add_food(): db = open_db() cur = db.execute(''' select f.id, f.name, f.protein, f.carbs, f.fat, f.calories from foods f order by f.name ''') foods = cur.fetchall() db.close() return render_template('add_food.html', foods=foods)
def send(host, segments, job_id, gpg): """Sends the encoded *segments* to the next service by smtp throught *host* encrypted using the *gpg* context """ import smtplib print('sending') sender = "*****@*****.**" receivers = ["*****@*****.**"] message = """{}|""".format(job_id) message += json.dumps(segments) + "\n" database.update_state(database.open_db(), 17, job_id) message = encrypt(message, gpg) database.update_state(database.open_db(), 18, job_id) smtpObj = smtplib.SMTP(host) print(smtpObj.sendmail(sender, receivers, message.encode())) database.update_state(database.open_db(), 19, job_id)
def get_day(date_id): db = open_db() cur = db.execute( ''' select d.id, d.entry_date from dates d where d.id = ? order by d.id ''', [date_id]) date = cur.fetchone() date_db = datetime.strptime(str(date['entry_date']), '%Y%m%d') date_ft = datetime.strftime(date_db, '%B %d, %Y') cur = db.execute(''' select f.id, f.name from foods f order by f.name ''') foods = cur.fetchall() cur = db.execute( ''' select i.date_id, d.entry_date, i.food_id, f.name, f.protein, f.carbs, f.fat, f.calories from daily_intake i left join dates d on d.id = i.date_id left join foods f on f.id = i.food_id where i.date_id = ? order by i.date_id, f.name ''', [date_id]) intakes = cur.fetchall() cur = db.execute( ''' select ifnull(sum(f.protein),0) protein , ifnull(sum(f.carbs),0) carbs , ifnull(sum(f.fat),0) fat , ifnull(sum(f.calories),0) calories from daily_intake i left join dates d on d.id = i.date_id left join foods f on f.id = i.food_id where i.date_id = ? ''', [date_id]) totals = cur.fetchone() db.close() return render_template('day.html', date_id=date_id, date_ft=date_ft, foods=foods, intakes=intakes, totals=totals)
def next_high_score(user): global db try: score = database.get_score(user) c=database.open_db() command = "SELECT user,pts FROM accounts WHERE pts>? ORDER BY pts ASC" c.execute(command, (score,)) data = c.fetchone() database.close_db() except: print "Error: could the next higher score" return None return data
def post_home(): str_date = request.form['date'] dat_date = datetime.strptime(str_date, '%Y-%m-%d') db_date = datetime.strftime(dat_date, '%Y%m%d') values = [db_date] db = open_db() db.execute(' insert into dates ( entry_date ) values ( ? ) ', values) db.commit() db.close() return redirect(url_for('get_home'))
def find_person_by_name(self, person): '''Finds a person based on their name''' p = None db = database.open_db() cursor = db.cursor() # create prepared statement for use in execute() sql, values = self._create_prepared_statement(database.PERSON_BY_NAME, person) cursor.execute(sql, values) result = cursor.fetchone() if result: p = self._populate_person(result) db.close() return p
def select_test(message): conn, cursor = database.open_db(database.db_name) query = f"SELECT id from {database.tests_t}" result = [elem[0] for elem in cursor.execute(query).fetchall()] result = list(set(result)) test_id = random.choice(result) query = f"UPDATE {database.status_t} SET test_id='{test_id}', question_number='0', score='0' WHERE id='{message.chat.id}'" cursor.execute(query) query = f"SELECT interest FROM {database.users_t} WHERE id='{message.chat.id}'" interest = cursor.execute(query).fetchall()[0][0] bot.send_message(message.chat.id, interest) bot.send_message(message.chat.id, messages.test_info_message + test_id) database.close_db(conn, cursor) send_question(message)
def on_post(): """Fetches segments and job_id from POST """ job_id = request.form['job'] segments = json.loads(request.form['message']) print('new job', job_id, segments) database.update_state(database.open_db(), 14, request.form['job']) translation(segments, job_id, gpg) return ""
def post_day(): date_id = request.form['date'] food_id = request.form['food'] values = [date_id, food_id] db = open_db() db.execute( ' insert into daily_intake ( date_id, food_id ) values ( ?, ? ) ', values) db.commit() db.close() return redirect(url_for('get_day', date_id=date_id))
def words_solved(): global db try: c=database.open_db() command = "SELECT pts FROM accounts" c.execute(command) data = c.fetchall() database.close_db() except: print "Error: could not get words solved" return 0 total = 0 for entry in data: total += entry[0]/100 return total
def num_users(): global db try: c=database.open_db() command = "SELECT * FROM accounts" c.execute(command) data = c.fetchall() database.close_db() except: print "Error: could not get number of users" return 0 count = 0 for entry in data: count += 1 return count
def num_gifs_flagged(): global db try: c=database.open_db() command = "SELECT * FROM flaggedgif" c.execute(command) data = c.fetchall() database.close_db() except: print "Error: could not get number of gifs flagged" return 0 count = 0 for entry in data: count += 1 return count
def send_question(message): conn, cursor = database.open_db(database.db_name) query = f"SELECT test_id, question_number, score FROM {database.status_t} WHERE id='{message.chat.id}'" result = cursor.execute(query).fetchall()[0] test_id = int(result[0]) question_number = int(result[1]) score = int(result[2]) # get number of questions in test query = f"SELECT * FROM {database.tests_t} WHERE id='{test_id}'" result = cursor.execute(query).fetchall() test_len = len(result) if question_number == 0: question_number += 1 elif 0 < question_number <= test_len: user_answer = message.text query = f"SELECT ans_1 FROM {database.tests_t} WHERE id='{test_id}' AND number='{question_number}'" correct_answer = cursor.execute(query).fetchall()[0][0] if user_answer == correct_answer: score += 1 bot.send_message(message.chat.id, messages.correct_answer_message) else: bot.send_message(message.chat.id, messages.incorrect_answer_message) question_number += 1 if question_number > test_len: bot.send_message( message.chat.id, 'Тест окончен\nВерных ответов: ' + str(score) + ' из ' + str(test_len)) database.set_status(message, config.wait) send_help(message) else: query = f"UPDATE {database.status_t} SET question_number='{question_number}', score='{score}'" cursor.execute(query) # send question query = f"SELECT question, ans_1, ans_2, ans_3, ans_4 FROM {database.tests_t} " \ f"WHERE id='{test_id}' AND number='{question_number}'" result = list(cursor.execute(query).fetchall()[0]) question = result[0] answers = result[1:] random.shuffle(answers) user_markup = telebot.types.ReplyKeyboardMarkup(True, True) user_markup.row(answers[0], answers[1]) user_markup.row(answers[2], answers[3]) bot.send_message(message.chat.id, question, reply_markup=user_markup) database.close_db(conn, cursor)
def listen(): """Start a Unitator server listening for notifications of a golfer server """ notifier = socket.socket(socket.AF_INET, socket.SOCK_STREAM) notifier.bind((TCP_IP, TCP_PORT)) notifier.listen() print('listening') while True: conn, _ = notifier.accept() print('accepted') data = conn.recv(19) if data == b'pssssst want some ?': data = b"" while True: new_data = conn.recv(1) if not new_data or new_data == b'#': break data += new_data conn.close() data = data.decode() data = data.split('|') if len(data) == 2: host, ip = data[0].split(":") job_selector = data[1] print('>', host, ip, job_selector) job_conn = send(job_selector.encode() + b'\n', host, ip) raw = recv_data(job_conn) segments = json.loads(raw) print(raw, segments) send(b'!/delete ' + job_selector.encode() + b'\n', host, ip) job_id = job_selector.split("/")[1] database.update_state(database.open_db(), 9, job_id) unit(segments, job_id)
def Turn(self, request, context): """Turns segments contained in the RPC message *request* """ print("DEEEEEEEEEE") status_db = database.open_db() database.update_state(status_db, 4, request.id) segments = MessageToDict(request)["segments"] segments = list(map(segment_to_tuple, segments)) database.update_state(status_db, 5, request.id) rotated_segments = rotate.mirror_and_turn_segments(segments, True) database.update_state(status_db, 6, request.id) write(json.dumps(list(rotated_segments)), request.id) database.update_state(status_db, 7, request.id) return mill_pb2.Response()
def post_add_food(): name = request.form['name'] protein = int(request.form['protein']) carbs = int(request.form['carbs']) fat = int(request.form['fat']) calories = (protein * 4) + (carbs * 4) + (fat * 9) values = [name, protein, carbs, fat, calories] db = open_db() db.execute( ' insert into foods ( name, protein, carbs, fat, calories ) values ( ?, ?, ?, ?, ? ) ', values) db.commit() db.close() return redirect(url_for('get_add_food'))
def menu(): connection = database.open_db() database.create_table(connection) while (user_input := input(MENU_PROMPT)) != "9": print(user_input) if user_input == "1": show_all(connection) elif user_input == "2": search_title(connection) elif user_input == "3": search_author(connection) elif user_input == "4": add(connection) elif user_input == "5": update(connection) elif user_input == "6": sort_by_rating(connection) elif user_input == "7": show_highest(connection) elif user_input == "8": delete(connection) else: print("Invalid selection.")
def save_person(self, person): '''Saves the person object into the database. Sets up the relationship between a person and a phone number as well''' db = database.open_db() cursor = db.cursor() # check if the person or number already exists person_by_name = self.find_person_by_name(person) person_by_number = self.find_person_by_phone(person.telephones[0]) if person_by_name or person_by_number: raise ValueError('Cannot enter duplicate person or a duplicate phone number') try: cursor.execute(database.INSERT_PERSON, [person.first_name, person.middle_name, person.last_name]) person_id = cursor.lastrowid t = person.telephones[0] t.person_id = person_id cursor.execute(database.INSERT_TELEPHONE, [t.person_id, t.type, t.country, t.area, t.city_code, t.local_number, t.extension]) db.commit() except Exception as e: print(e) db.rollback() raise e else: cursor.close()
def unit(segments, job_id): """Clip *segments* of the job *job_id* into a unit square and forwards them """ print("segments:", segments) segments = [ clipping.segment(clipping.p(segment[0][0], segment[0][1]), clipping.p(segment[1][0], segment[1][1])) for segment in segments ] print("segments1:", segments) clipped_segments = clipping.clip_unit_square(segments) database.update_state(database.open_db(), 10, job_id) print("clipped_segments:", clipped_segments) tuple_segments = [((segment.a.x, segment.a.y), (segment.b.x, segment.b.y)) for segment in clipped_segments] print("tuple_segments:", tuple_segments) write(job_id, json.dumps(tuple_segments, indent=4))
import database import ec from database import txn_required import jserialize as js import bserialize as bs from utils import * # 1huR1oV8uEE77HqQHCAuCzCzoq9HzXDSh # L5TG3BkBgABJ1EXqznUSgRNXbdXwUpXEAEd6MDSFPsEnS5v2yX1i keychain = database.open_db("keychain.dat") keychain.set_get_returns_none(0) class KeyEntry(bs.Entity, js.Entity): bfields = [("privatkey", bs.VarBytes), ("publickey", bs.VarBytes), ("txs", bs.VarList(bs.Hash))] fields = {"privatkey": js.Bytes, "publickey": js.Bytes, "txs": js.List(js.Hash)} @property def hash(self): return hash160(self.publickey) @staticmethod def iter_keys(txn=None): try: cur = keychain.cursor(txn=txn) while True: try: h, data = cur.next() except KeyError: break
SIDE_CHAIN = 2 ORPHAN_CHAIN = 3 INVALID_CHAIN = 4 _chains = {MAIN_CHAIN: "Main", SIDE_CHAIN: "Side", ORPHAN_CHAIN: "Orphan", INVALID_CHAIN: "Invalid"} class BlockError(Exception): pass class InvalidBlock(BlockError): pass log = logging.getLogger("pycoin.blockchain") chain = database.open_db("chain.dat", dbtype=database.DB.DB_HASH, table_name="blks") chain.set_get_returns_none(0) state = database.open_db("chain.dat", dbtype=database.DB.DB_HASH, table_name="state") blknums = database.open_db("chain.dat", dbtype=database.DB.DB_HASH, table_name="blknum") blknums.set_get_returns_none(0) orphans = {} class Block(js.Entity, bs.Entity): fields = { "block": msgs.Block, "number": js.Int, "totaldiff": js.Int, "chain": js.Int, "txs": js.List(js.Hash), "nexts": js.List(js.Hash) }
if filter == None or (filter != "mostwins" and filter != "leastwins" and filter != "mostpopular" and filter != "leastpopular"): fw.redirect("/controllers/items/landing.py") fw.write_header() fw.render_header("Items Statistics - League Analyzer", ["navbar.css", "landing.css", "fontello.css", "general.css"]) fw.render("components/navbar", { "championsActiveClass": "", "itemsActiveClass": "active" }) database.open_db() render_args = {} if filter == "mostwins": highest_wins = database.get_most_wins_items() highest_wins_rows = "" for i in range(len(highest_wins)): args = copy.copy(highest_wins[i]) args["rank"] = str(i + 1) args["endpointVersion"] = fw.endpointVersion args["percentage"] = ( "%.2f" % ((float(args["wins"]) / float(args["total"])) * 100.0)) args["wins"] = str(args["wins"]) args["webRootPath"] = fw.webRootPath highest_wins_rows += wins_row_template.safe_substitute(args)
import database import msgs script_idx = database.open_db("txs.dat", flags=[database.DB.DB_DUP], table_name="script_index") script_idx.set_get_returns_none(0) def search_script(sc): cur = script_idx.cursor() k, v = cur.set(h) while k == h: yield msgs.TxPoint.frombinary(v)[0] k, v = cur.next_dup() def index_script(tx): for tx_idx, out_p in enumerate(tx.outputs): script_idx.put(out_p.script, msgs.TxPoint.make(tx.hash, tx_idx).tobinary())
from database import txn_required #import blockchain import struct import ec import settings class TxError(Exception): pass class TxInputAlreadySpend(TxError): pass txs = database.open_db("txs.dat", dbtype=database.DB.DB_HASH, table_name="txs") txs.set_get_returns_none(0) log = logging.getLogger("pycoin.transactions") class Tx(js.Entity, bs.Entity): fields = { "tx": msgs.Tx, "block": js.Hash, "blkindex": js.Int, #"flags":js.Int, "redeemed": js.List(js.Hash), } bfields = [ ("tx", msgs.Tx), ("block", bs.Hash),
import bserialize as bs #import bsddb import logging import database from database import txn_required #import blockchain import struct import ec import settings class TxError(Exception): pass class TxInputAlreadySpend(TxError): pass txs = database.open_db("txs.dat", dbtype=database.DB.DB_HASH, table_name="txs") txs.set_get_returns_none(0) log = logging.getLogger("pycoin.transactions") class Tx(js.Entity, bs.Entity): fields = { "tx":msgs.Tx, "block":js.Hash, "blkindex":js.Int, #"flags":js.Int, "redeemed":js.List(js.Hash), } bfields = [ ("tx", msgs.Tx), ("block", bs.Hash), ("blkindex", bs.structfmt("<L")),
fields = { "tx":msgs.Tx, "block":js.Hash, "blkindex":js.Int, #"flags":js.Int, "redeemed":js.List(js.Hash), } bfields = [ ("tx", msgs.Tx), ("block", bs.Hash), ("blkindex", bs.structfmt("<L")), #("flags", bs.VarInt), ("redeemed", bs.VarList(bs.Hash)), ] addrs = database.open_db("txs.dat", table_name="txs") addrs.set_get_returns_none(0) class AddressManager(object): def __init__(self, server): self.server = server self.server.add_handler("addr", self.handle_addr) eventlet.spawn_n(self.main_thread) def handle_addr(self, node, msg): pass def main_thread(self): while True: return