def index(): profielfoto = db.execute( "SELECT profielfoto FROM users WHERE user_id = :user_id", user_id=session["user_id"])[0]['profielfoto'] gebruikersnaam = db.execute( "SELECT username FROM users WHERE user_id = :user_id", user_id=session["user_id"])[0]['username'] mijn_quizes = db.execute("SELECT * FROM quizes WHERE user_id = :username", username=session["user_id"]) participanten_lijst = [] # haal voor alle quizes van de ingelogde user de participanten op en voeg de quiznaam toe for quiz in mijn_quizes: for participant in db.execute( "SELECT * FROM participants WHERE quiz_id = :quiz", quiz=quiz['quiz_id']): participant["quizname"] = quiz["quiz_titel"] participanten_lijst.append(participant) participanten_lijst.reverse() # haal de top 5 scores uit alle participanten top_participanten = sorted(participanten_lijst, key=lambda x: x["score"]) top_participanten.reverse() return render_template("index.html", participanten_lijst=percentage(participanten_lijst), top_participanten=top_participanten[:5], profielfoto=profielfoto, gebruikersnaam=gebruikersnaam)
def return_votes(reddit, post_id): post = Submission(reddit, post_id) try: # this check makes sure we have an actual AITA post if post.subreddit.id != "2xhvq": raise NotFound except NotFound: return False vote_dict = dict.fromkeys(abbreviations, 0) for top_level_comment in post.comments: if isinstance(top_level_comment, MoreComments): continue # escaping automod try: if top_level_comment.author.id == "6l4z3": continue except AttributeError: # means the comment is deleted continue vote = re.search("|".join(abbreviations), top_level_comment.body) if vote: vote_dict[vote[0]] += 1 percentage_dict = dict.fromkeys(abbreviations, 0) all_votes = 0 for amount in vote_dict.values(): all_votes += amount for key in vote_dict: percentage_dict[key] = percentage(vote_dict[key], all_votes) return vote_dict, percentage_dict, post.title, post.permalink
def index(): totalList = db.execute("SELECT total FROM userStatus WHERE id = :id", id=session["user_id"]) total = calculate(totalList) userStatus = db.execute("SELECT * from userStatus WHERE id=:id", id=session["user_id"]) cash = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"]) user = db.execute("SELECT username FROM users WHERE id=:id", id=session["user_id"]) stockmarket = [] for s in userStatus: x = lookup(s["symbol"]) stockmarket.append(x) print(stockmarket) for s in stockmarket: for u in userStatus: if s is None: break elif u["symbol"] == s["symbol"]: u["percentage"] = percentage(u["price"], usd(s["price"])) u["marketprice"] = usd(s["price"]) global m1 global m1 message11 = m1[:] message22 = m2[:] m1 = "" m1 = "" return render_template("index.html",username=(user[0]["username"]), stocks=userStatus, \ cash=usd(float(cash[0]["cash"])), total=usd(total+float(cash[0]["cash"])), \ message1= message11, message2=message22)
iterations = 5000000000 neurons = [300] momentum = .0 learning_rate = .005 batch_size = 100 best_accuracy = 0 append_params(neurons=neurons, momentum=momentum, learning_rate=learning_rate, batch_size=batch_size) nn = NeuralNetwork(28 * 28, neurons, [ActivationType.relu, ActivationType.relu], 10, momentum=momentum, learning_rate=learning_rate) for i in range(iterations): with Timer(lambda t: print('Iteration took {:.2f} seconds'.format(t))): accuracy = nn.test(X_test, y_test) if accuracy > best_accuracy: best_accuracy = accuracy append_progress(i, accuracy) print('Accuracy: {}, Best Accuracy: {}'.format( percentage(accuracy), percentage(best_accuracy)), end=' ') mean_mse = nn.train(X_train, y_train, batch_size=batch_size, shush=True)
def compute_relation(self, relative_category): origin = self relative = relative_category p = percentage(origin.elements, relative_category.condition()) return Relation(origin, relative, p)
def sell_1(): """Sell 1 share of stock""" app.logger.debug("Sell 1 share from Button") # user reached route via form POST validated = True message = None # replace single quotes with double quotes if necessary to get valid JSON transaction = json.loads( request.form.get("transaction").replace("\'", "\"")) dis_total = float( json.loads(request.form.get("grand_total").replace("\'", "\""))) # consume the API to get the latest price api_response = lookup(transaction["stock"]) # check for potential errors if api_response is None: validated = False message = "stock does not exist" else: cur_price = float(api_response["price"]) # query the DB to get the cash available for the user user_db = User.get_by_id(session["user_id"]) # check whether the quantity for this stock is enough stock_db = Transaction.get_by_symbol(user_id=user_db.id, symbol=api_response["symbol"]) if stock_db.quantity < 1: validated = False message = "no more stock to sell" else: # add the transaction to the transaction data transaction_db = Transaction(stock_id=stock_db.id, user_id=session["user_id"], \ quantity=-1, price=cur_price, amount=-cur_price) # post the transaction data db.session.add(transaction_db) # add the amount of the transaction to the user's cash user_db.cash += cur_price # commit changes to validate the transaction db.session.commit() if validated == True: # recalculate the figures for the selected stock transaction_db = Transaction.get_by_symbol( user_id=user_db.id, symbol=api_response["symbol"]) # define a comparison indicator on the price (latest) vs average price (DB) avg_price = float( transaction_db.amount / transaction_db.quantity) if transaction_db.quantity > 0 else 0 dis_price = float(transaction["price"]) amount = float(transaction_db.quantity * cur_price) variation = (cur_price - avg_price) / avg_price if avg_price > 0 else 0 # update the figures from the existing one (raw data not converted) transaction["quantity"] = transaction_db.quantity transaction["price"] = cur_price transaction["amount"] = amount transaction["variation"] = variation if (variation < 0): transaction["price_indicator"] = "table-danger" elif (variation == 0): transaction["price_indicator"] = "table-secondary" else: transaction["price_indicator"] = "table-success" grand_total = dis_total + dis_price - cur_price # server-side rendering for filtered values return jsonify({"success": True, "transaction": transaction, "cash": usd(user_db.cash), "price": usd(cur_price), \ "amount": usd(amount), "variation": percentage(variation), "grand_total": usd(grand_total)}) else: return jsonify({"success": False, "message": message})
iterations = 100 append_params(neurons=neurons, learning_rate=learning_rate, batch_size=batch_size, momentum=momentum, iterations=iterations) nn = NeuralNetwork(2, neurons, activation, 2, momentum=momentum, learning_rate=learning_rate) with Timer(lambda t: print('Took {} seconds'.format(t))): accuracy = nn.test(X_train.tolist(), y_train.tolist()[0]) print('Accuracy: {}'.format(percentage(accuracy))) mean_mses = [] for i in range(iterations): if i % 10 == 0 or i == 0: accuracy = nn.test(X_test.tolist(), y_test.tolist()[0]) append_progress(i, accuracy) print('Accuracy: {}'.format(percentage(accuracy))) mean_mse = nn.train(X_train.tolist(), y_train.tolist()[0], batch_size=batch_size, shush=True) mean_mses.append(mean_mse) plt.plot(mean_mses) plt.suptitle('Mean MSE over time')
print('X_train.shape={}, y_train.shape={}'.format(X_train.shape, y_train.shape)) print('X_test.shape={}, y_test.shape={}'.format(X_test.shape, y_test.shape)) print('X_train={}'.format(len(X_train))) print('X_test={}'.format(len(X_test))) neurons = [5] activation = [ActivationType.relu, ActivationType.relu] momentum = 0.0 learning_rate = .000005 iterations = 150 append_params(neurons=neurons, learning_rate=learning_rate, momentum=momentum) nn = NeuralNetwork(2, neurons, activation, 2, momentum=momentum, learning_rate=learning_rate) with Timer(lambda t: print('Took {} seconds'.format(t))): accuracy = nn.test(X_train.tolist(), y_train.tolist()[0]) print('Accuracy: {}'.format(percentage(accuracy))) mean_mses = [] for i in range(iterations): if i % 10 == 0 or i == 0: accuracy = nn.test(X_test.tolist(), y_test.tolist()[0]) append_progress(i, accuracy) print('{}/{} Accuracy: {}'.format(i, iterations, percentage(accuracy))) mean_mse = nn.train(X_train.tolist(), y_train.tolist()[0], shush=True) print(mean_mse) mean_mses.append(mean_mse) plt.plot(mean_mses) plt.suptitle('Mean MSE over time B={}'.format(momentum)) figname = './mseb{}.png'.format(int(momentum * 10)) plt.savefig(figname)