def admin_edit_user(utable, js):
    field = js.get("field", "").strip()
    new_value = js.get("new_value", "").strip()
    prev_value = getattr(utable, field, sentinel)
    if prev_value == sentinel:
        return {"error": "??????"}

    if prev_value == new_value:
        return {"user_data": utable.as_json}
    if field == "current_level":
        set_level(utable, new_value)
        return {"user_data": utable.as_json}
    elif field == "last_question_answered_at":
        set_last_question_answered_at(utable, new_value)
        return {"user_data": utable.as_json}
    elif field == "email":
        if not validate_email_address(new_value):
            return {"error": "Invalid email"}
        utable.has_verified_email = False
    try:
        setattr(utable, field, new_value)
        save_to_db()
        return {"user_data": utable.as_json}
    except Exception:
        return {
            "error":
            "Could not update" if field != "email" else
            "Could not update email, maybe another account is using that address"
        }
예제 #2
0
def main(x):
    x = int(x)
    if x < 0 or x > 250:
        print('Invalid value of x')
        exit()
    else:
        database.save_to_db(x)
def answer_question(question_number: int, answer: str,
                    user: UserTable) -> dict:
    answer = (answer or "").strip()
    if len(answer) > 1000:
        return incorrect_answer
    if not answer:
        return incorrect_answer
    question: Questions = get_ques_by_id(question_number)
    if not question:
        return no_question(question_number)
    correct = replace("", question.answer)
    current = replace("", answer)
    is_correct = correct == current
    data_dict = {
        "user": user.user,
        "school": user.school,
        "attempt": current,
        "is_correct": is_correct,
        "timestamp": js_time(),
        "level": question_number,
    }
    js = f"{user.user} ({user.school}) tried to answer {user.current_level} with {current}  ({'✅' if is_correct else '❌'})"
    run_threaded_tasks(js, data_dict, is_correct)
    if is_correct:  # no
        user.current_level = user.current_level + 1  # +=1 yeah
        user.last_question_answered_at = js_time()
        save_to_db()

        return {"result": True, "next_level": user.current_level}
    else:
        return incorrect_answer
def edit_question(js: dict) -> dict:
    num: int = js.get("question_level")
    qs = get_ques_by_id(num)
    qs.question = dumps(js.get("question", qs.question))
    qs.answer = js.get("answer", qs.answer)
    qs.hint = dumps(js.get("hint", qs.hint))
    qs.special = dumps(js.get("special", qs.special))
    save_to_db()
    return qs.as_json
예제 #5
0
def menu_user():
    user_menu = input(USER_CHOICE)
    while user_menu != 'q':
        if user_menu in menu_list:
            menu_select = menu_list[user_menu]
            menu_select()
            database.save_to_db()

        else:
            print(f"Menu '{user_menu}' does not exist..")
        user_menu = input(USER_CHOICE)
def convert_to_admin_account(js: dict) -> dict:
    user = js.get("user")
    token = js.get("token")
    if token != ADMIN_TOKEN_OS:
        return {"error": "No"}
    u = get_user_by_id(user)
    if not u:
        return {"error": "User does not exist"}
    u.is_admin = True
    save_to_db()
    return u.as_json
예제 #7
0
def edit(js: dict) -> dict:
    if not is_logged_in():
        return {"error": "Not Authenticated"}
    user = js.get("user", "").strip()
    field = js.get("field", "").strip()
    if field not in ["email", "school", "ig_user_id"]:
        return {"error": "cannot edit specified field"}
    new_value = js.get("new_value", "").strip()
    if user != get_current_user():
        return {"error": "Invalid credentials"}
    invalid_data_arr = []
    if not user:
        invalid_data_arr.append("user")
    if not field:
        invalid_data_arr.append("column")
    if not new_value:
        invalid_data_arr.append("value")

    if invalid_data_arr:
        return {"error": f"Missing data: {', '.join(invalid_data_arr)}"}

    user_table = get_user_by_id(user)

    attr = getattr(user_table, field, sentinel)
    if attr == sentinel:
        return {"error": "Invalid field"}
    if attr == new_value:
        # prevent a useless write
        return {"user_data": user_table.as_json}
    try:
        setattr(user_table, field, new_value)
        if field == "email":
            if not validate_email_address(new_value):
                return {"error": "Invalid email"}
            user_table.has_verified_email = False
        save_to_db()
        return {"user_data": user_table.as_json}
    except:
        return {
            "error":
            "Could not update" if field != "email" else
            "Could not update email, maybe another account is using that address"
        }
예제 #8
0
def alarm():
    global cancel_alarm
    global alarm_countdown
    acc_array = cache.cache['acc']['value'].tolist()
    if additional != '':
        temp, light, hum, co2 = tuple(
            [float(x) for x in additional.split(' ')])
    else:
        temp, light, hum, co2 = (0, 0, 0, 0)
    if not cancel_alarm:
        print('Alarm!!!')
        is_seizure = True
        try:
            send_sms('Seizure Alert!')
        except Exception:
            print('cannot send sms')
    else:
        print('False alarm!!!')
        is_seizure = False

    save_to_db(temp, light, hum, co2, acc_array, True)
    cancel_alarm = False
    alarm_countdown = False
예제 #9
0
def answer_question(question_number: int, answer: str,
                    user: UserTable) -> dict:
    answer = (answer or "").strip()
    if not answer:
        return incorrect_answer
    question: Questions = get_ques_by_id(question_number)
    if not question:
        return no_question(question_number)
    correct = replace("", question.answer)
    current = replace("", answer)
    is_correct = correct == current
    js = f"{user.user} ({user.school}) tried to answer {user.current_level} with {current}  ({'✅' if is_correct else '❌'})"
    if is_correct:
        post_level_up_webhook(js)
    else:
        post_incorrect_webhook(js)
    if is_correct:  # no
        user.current_level = user.current_level + 1  # +=1 yeah
        user.last_question_answered_at = js_time()
        save_to_db()

        return {"result": True, "next_level": user.current_level}
    else:
        return incorrect_answer
예제 #10
0
    def download_sp500(self, startdate, enddate, dbfilename):
        """
        Downloads S&P500 tickers from Wikipedia and daily time series from Yahoo! Finance
        """    
        
        # Download list of tickers, company name and GICS Sectors from Wikipedia
        url = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
        page = html.parse(url)
        symbol = page.xpath('//table[@class="wikitable sortable"]/tr/td[1]/a/text()')
        company = page.xpath('//table[@class="wikitable sortable"]/tr/td[2]/a/text()')
        sector = page.xpath('//table[@class="wikitable sortable"]/tr/td[4]/text()')
        
        # Add the index itself
        symbol.append('^GSPC')
        company.append('S&P 500')
        sector.append(None)
        
        # Since Dec-12, BRK.B Yahoo! Finance lists BRK.B as BRK-B
        if 'BRK.B' in symbol: symbol[symbol.index('BRK.B')]='BRK-B'
        
        # Debugging: restrict to the first 10 stocks of the index
#        symbol = symbol[:10]
#        company = company[:10]
#        sector = sector[:10] 
        
        # If database doesn't exist, create it
        if not os.path.exists(dbfilename):
            database.create_db(dbfilename)    
        
        conn = sqlite3.connect(dbfilename, 
               detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
        c = conn.cursor()
        
        # Load data from Wikipedia into Load table
        conn.execute("CREATE TABLE LoadAssets (Cd text, Name text, SectorName text)")
        sql = "INSERT INTO LoadAssets (Cd, Name, SectorName) VALUES (?, ?, ?)"    
        c.executemany(sql, zip(symbol, company, sector))
        conn.commit()
        
        # Download time series from Yahoo! finance and store into db
        i = 0
        for s in list(symbol):
            data = database.get_yahoo_prices(s, startdate, enddate)
            database.save_to_db(data, dbfilename)   
            self.downloaded.emit(i) # emit signal to update progressbar
            i += 1
        
        # From: http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
        # Note: Telecommunication Services is listed as Telecommunications Services
        conn.execute("DELETE FROM GicsSectors")
        conn.execute("INSERT INTO GicsSectors VALUES(10, 'Energy')")
        conn.execute("INSERT INTO GicsSectors VALUES(15, 'Materials')")
        conn.execute("INSERT INTO GicsSectors VALUES(20, 'Industrials')")
        conn.execute("INSERT INTO GicsSectors VALUES(25, 'Consumer Discretionary')")
        conn.execute("INSERT INTO GicsSectors VALUES(30, 'Consumer Staples')")
        conn.execute("INSERT INTO GicsSectors VALUES(35, 'Health Care')")
        conn.execute("INSERT INTO GicsSectors VALUES(40, 'Financials')")
        conn.execute("INSERT INTO GicsSectors VALUES(45, 'Information Technology')")
        conn.execute("INSERT INTO GicsSectors VALUES(50, 'Telecommunications Services')")
        conn.execute("INSERT INTO GicsSectors VALUES(55, 'Utilities')")
        
        conn.execute("DELETE FROM Assets WHERE Cd IN (SELECT Cd FROM LoadAssets)")
        
        conn.execute("""
        INSERT INTO Assets
        SELECT l.Cd, l.Name, g.Id
        FROM LoadAssets l
        LEFT JOIN GicsSectors g ON l.SectorName = g.Name""")
        
        conn.execute("DROP TABLE LoadAssets")
        conn.commit()
       
        c.close()
        conn.close()
예제 #11
0
def execute_request(instrument, market_code, instrument_dir, today_only):
    # logging.info("Start to update {} at the {}".format(str(instrument),
    #                                                    datetime.datetime.now(pytz.timezone('Europe/Moscow')).strftime('%Y-%m-%d %H:%M:%S')))
    path_to_dir = UPLOAD_FOLDER + "/" + instrument_dir
    file_instrument_name = instrument.replace(" ", "_").replace(
        "&", "_").replace("/", "_") + "_"
    instrument_code = str(all_instruments.get(instrument))

    list_of_dates = get_list_of_dates(today_only)
    successfully_download = True
    for i in range(0, len(list_of_dates) - 1):
        file_name = file_instrument_name + list_of_dates[i].strftime(
            "%m.%d.%Y") + "_" + list_of_dates[i + 1].strftime(
                "%m.%d.%Y") + "_" + instrument_code
        url_request = quotes_str.format(
            file_name, market_code, instrument_code, list_of_dates[i].day,
            list_of_dates[i].month - 1, list_of_dates[i].year,
            list_of_dates[i].strftime("%m.%d.%Y"), list_of_dates[i + 1].day,
            list_of_dates[i + 1].month - 1, list_of_dates[i + 1].year,
            list_of_dates[i + 1].strftime("%m.%d.%Y"), periods.get("_HOUR"),
            file_name)

        retries = 0
        while True and retries < 4:
            try:
                retries += 1
                urllib.request.urlretrieve(
                    url_request,
                    os.path.join(path_to_dir, file_name + "_TEMP.csv"))
                successfully_download = True
            except:
                successfully_download = False
                time.sleep(.7)
                logging.info("Could not make request to url {}".format(
                    str(url_request)))
            else:
                break
        time.sleep(.5)
    # logging.info("{} Was downloaded and now begin to parse files. time: {}".format(str(instrument),
    #                                                    datetime.datetime.now(pytz.timezone('Europe/Moscow')).strftime(
    #                                                        '%Y-%m-%d %H:%M:%S')))
    if not successfully_download:
        for temp_file in glob.glob(path_to_dir + "/*.csv"):
            if "_TEMP" in str(temp_file):
                os.unlink(temp_file)
    else:
        # merge in one csv file and remove after that
        list_of_files = sorted(glob.glob(path_to_dir + "/*.csv"),
                               key=os.path.getctime)
        files = []
        for the_file in list_of_files:
            if instrument_code == str(the_file.split("_")[-2:-1][0]):
                files.append(the_file)

        combined_csv = prepare_csv_file(files)
        if not combined_csv.empty:
            combined_csv = combined_csv.drop_duplicates()
            save_to_db(combined_csv, instrument)
        else:
            logging.info("Empty dataframe from file " + str(instrument))
        for file in files:
            os.unlink(file)
    logging.info("End update {} at the {}".format(
        str(instrument),
        datetime.datetime.now(
            pytz.timezone('Europe/Moscow')).strftime('%Y-%m-%d %H:%M:%S')))
예제 #12
0
def requalify(user: UserTable):
    user.is_disqualified = False
    save_to_db()
    return {"user_data": user.as_json}
예제 #13
0
def set_last_question_answered_at(user: UserTable, tstamp):
    ts = safe_int(tstamp)
    user.last_question_answered_at = ts
    save_to_db()
    return SUCCESS
예제 #14
0
def set_level(user: UserTable, level_to_set):
    level_to_set = safe_int(level_to_set)
    user.current_level = level_to_set
    save_to_db()
    return SUCCESS
예제 #15
0
    def download_sp500(self, startdate, enddate, dbfilename):
        """
        Downloads S&P500 tickers from Wikipedia and daily time series from Yahoo! Finance
        """

        # Download list of tickers, company name and GICS Sectors from Wikipedia
        url = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
        page = html.parse(url)
        symbol = page.xpath(
            '//table[@class="wikitable sortable"]/tr/td[1]/a/text()')
        company = page.xpath(
            '//table[@class="wikitable sortable"]/tr/td[2]/a/text()')
        sector = page.xpath(
            '//table[@class="wikitable sortable"]/tr/td[4]/text()')

        # Add the index itself
        symbol.append('^GSPC')
        company.append('S&P 500')
        sector.append(None)

        # Since Dec-12, BRK.B Yahoo! Finance lists BRK.B as BRK-B
        if 'BRK.B' in symbol: symbol[symbol.index('BRK.B')] = 'BRK-B'

        # Debugging: restrict to the first 10 stocks of the index
        #        symbol = symbol[:10]
        #        company = company[:10]
        #        sector = sector[:10]

        # If database doesn't exist, create it
        if not os.path.exists(dbfilename):
            database.create_db(dbfilename)

        conn = sqlite3.connect(dbfilename,
                               detect_types=sqlite3.PARSE_DECLTYPES
                               | sqlite3.PARSE_COLNAMES)
        c = conn.cursor()

        # Load data from Wikipedia into Load table
        conn.execute(
            "CREATE TABLE LoadAssets (Cd text, Name text, SectorName text)")
        sql = "INSERT INTO LoadAssets (Cd, Name, SectorName) VALUES (?, ?, ?)"
        c.executemany(sql, zip(symbol, company, sector))
        conn.commit()

        # Download time series from Yahoo! finance and store into db
        i = 0
        for s in list(symbol):
            data = database.get_yahoo_prices(s, startdate, enddate)
            database.save_to_db(data, dbfilename)
            self.downloaded.emit(i)  # emit signal to update progressbar
            i += 1

        # From: http://en.wikipedia.org/wiki/Global_Industry_Classification_Standard
        # Note: Telecommunication Services is listed as Telecommunications Services
        conn.execute("DELETE FROM GicsSectors")
        conn.execute("INSERT INTO GicsSectors VALUES(10, 'Energy')")
        conn.execute("INSERT INTO GicsSectors VALUES(15, 'Materials')")
        conn.execute("INSERT INTO GicsSectors VALUES(20, 'Industrials')")
        conn.execute(
            "INSERT INTO GicsSectors VALUES(25, 'Consumer Discretionary')")
        conn.execute("INSERT INTO GicsSectors VALUES(30, 'Consumer Staples')")
        conn.execute("INSERT INTO GicsSectors VALUES(35, 'Health Care')")
        conn.execute("INSERT INTO GicsSectors VALUES(40, 'Financials')")
        conn.execute(
            "INSERT INTO GicsSectors VALUES(45, 'Information Technology')")
        conn.execute(
            "INSERT INTO GicsSectors VALUES(50, 'Telecommunications Services')"
        )
        conn.execute("INSERT INTO GicsSectors VALUES(55, 'Utilities')")

        conn.execute(
            "DELETE FROM Assets WHERE Cd IN (SELECT Cd FROM LoadAssets)")

        conn.execute("""
        INSERT INTO Assets
        SELECT l.Cd, l.Name, g.Id
        FROM LoadAssets l
        LEFT JOIN GicsSectors g ON l.SectorName = g.Name""")

        conn.execute("DROP TABLE LoadAssets")
        conn.commit()

        c.close()
        conn.close()